text
stringlengths
10
2.72M
/* * Copyright 2008, Myron Marston <myron DOT marston AT gmail DOT com> * * This file is part of Fractal Composer. * * Fractal Composer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * at your option any later version. * * Fractal Composer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Fractal Composer. If not, see <http://www.gnu.org/licenses/>. */ package com.myronmarston.music.scales; import com.myronmarston.music.Note; import com.myronmarston.music.NoteName; import com.myronmarston.util.ClassHelper; import com.myronmarston.util.MathHelper; import org.simpleframework.xml.*; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.lang.reflect.UndeclaredThrowableException; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Scales are used to convert a Note to a MidiNote and to provide the midi file * with a time signature. Since each Note contains data on its identity * relative to a given scale, the Scale must be used to convert it to a concrete * MidiNote (e.g., pitch, etc). * * All extending classes need to have the @Root annotation to be serializable * by the simple XML framework and also need to provide two constructors: * a no-argument one (which should set the scale with some reasonable default * key) and one that takes a note name to specify the key. * * @author Myron */ @Root public abstract class Scale implements Cloneable { @Element private KeySignature keySignature; /** * A list of all valid scale types, mapped to a list of valid key names for * that scale type. */ public final static Map<Class, List<NoteName>> SCALE_TYPES; /** * The scale that should be used before the user specifies one--a chromatic scale. */ public final static Scale DEFAULT; /** * Initializes the default scale and the scale types list. */ static { try { DEFAULT = new ChromaticScale(); } catch (InvalidKeySignatureException ex) { throw new UndeclaredThrowableException(ex, "An exception occurred while instantiating a ChromaticScale. This indicates a programming error."); } List<Class> scaleTypeList; try { scaleTypeList = ClassHelper.getSubclassesInPackage(Scale.class.getPackage().getName(), Scale.class); } catch (ClassNotFoundException ex) { // our code above is guarenteed to pass a valid package name, so we // should never get this exception; if we do, there is a bug in the // code somewhere, so throw an assertion error. throw new UndeclaredThrowableException(ex, "An exception occurred while getting the scale types. This indicates a programming error."); } //TODO: make SCALE_TYPES unmodifiable SCALE_TYPES = new LinkedHashMap<Class, List<NoteName>>(scaleTypeList.size()); for (Class scaleType : scaleTypeList) { try { if (Modifier.isAbstract(scaleType.getModifiers())) continue; @SuppressWarnings("unchecked") Constructor constructor = scaleType.getDeclaredConstructor(); Scale s = (Scale) constructor.newInstance(); SCALE_TYPES.put(scaleType, s.getValidKeyNames()); } catch (Exception ex) { // the reflection code above has lots of declared exceptions, // but they should only occur if we have a programming error, // so we'll just wrap them in an undeclared exception if they // occur... throw new UndeclaredThrowableException(ex, "An exception occurred while getting the valid key names. This indicates a programming error."); } } } /** * The number of chromatic pitches in one octave: 12. */ public final static int NUM_CHROMATIC_PITCHES_PER_OCTAVE = 12; /** * Constructor. * * @param keySignature the key signature of the scale */ protected Scale(KeySignature keySignature) { this.keySignature = keySignature; } /** * Gets the tonal center of the scale. * * @return the key name */ public NoteName getKeyName() { return keySignature.getKeyName(); } /** * Gets the key signature of the scale. * * @return the key signature */ public KeySignature getKeySignature() { return keySignature; } /** * Gets an array of integers representing the number of half steps above * the tonic for each scale step. * * @return array of integers */ abstract public int[] getScaleStepArray(); /** * Gets an array of integers of letter numbers above the tonic letter number. * * @return letter number array. */ abstract public int[] getLetterNumberArray(); /** * Normalizes a chromatic adjustment, putting it in the range -6 to 6. * * @param chromaticAdjustment the chromatic adjustment to normalize * @return the normalized value */ static public int getNormalizedChromaticAdjustment(int chromaticAdjustment) { // put it in the range -6..6 if it is outside of that... if (chromaticAdjustment > (Scale.NUM_CHROMATIC_PITCHES_PER_OCTAVE / 2)) { return chromaticAdjustment - Scale.NUM_CHROMATIC_PITCHES_PER_OCTAVE; } if (chromaticAdjustment < -(Scale.NUM_CHROMATIC_PITCHES_PER_OCTAVE / 2)) { return chromaticAdjustment + Scale.NUM_CHROMATIC_PITCHES_PER_OCTAVE; } return chromaticAdjustment; } /** * Normalizes the given scale step value to be between 0 and the number of * scale steps for this scale minus 1. For example, for diatonic scales, * the value is put in the range 0 to 7. * * @param scaleStep the scale step to normalize * @return the normalized scale step */ public int getNormalizedScaleStep(int scaleStep) { return MathHelper.getNormalizedValue(scaleStep, this.getScaleStepArray().length); } /** * Sets the scaleStep and chromaticAdjustment on the given note, based on * the passed noteName. * * @param note the scaleStep and chromatic adjustment will be set on this * note * @param noteName the noteName of the pitch that should be used to * determine the pitch values */ public void setNotePitchValues(Note note, NoteName noteName) { int intervalAboveTonic = this.getKeyName().getPositiveIntervalSize(noteName); int scaleStepIndex = Arrays.binarySearch(this.getLetterNumberArray(), intervalAboveTonic); if (scaleStepIndex >= 0) { // our scale contains this letter, so we can use it to determine our scale step // and then figure out our necessary chromaticAdjustment setNotePitchValues_Helper(note, noteName, scaleStepIndex); } else { // our scale does not contain this letter (example: F# for C major // pentatonic-C D E G A). We need to figure out which of our scale // steps this is closest to, and use that, modifying the chromatic // adjustment accordingly // find the two closest note letters... int letterNumberArrayInsertionPt = -scaleStepIndex - 1; int nearestLowerScaleStepIndex = (letterNumberArrayInsertionPt == 0 ? this.getLetterNumberArray().length - 1 : letterNumberArrayInsertionPt - 1); int nearestHigherScaleStepIndex = (letterNumberArrayInsertionPt == this.getLetterNumberArray().length ? 0 : letterNumberArrayInsertionPt); // figure out which of these two is closest to our given note... int lowerScaleStepNumHalfStepsAboveTonic = this.getScaleStepArray()[nearestLowerScaleStepIndex]; int higherScaleStepNumHalfStepsAboveTonic = this.getScaleStepArray()[nearestHigherScaleStepIndex]; int givenNoteHalfStepsAboveTonic = this.getKeyName().getPositiveChromaticSteps(noteName); int distanceFromLowerScaleStep = Math.abs(getNormalizedChromaticAdjustment(givenNoteHalfStepsAboveTonic - lowerScaleStepNumHalfStepsAboveTonic)); int distanceFromHigherScaleStep = Math.abs(getNormalizedChromaticAdjustment(higherScaleStepNumHalfStepsAboveTonic - givenNoteHalfStepsAboveTonic)); if (distanceFromLowerScaleStep < distanceFromHigherScaleStep) { setNotePitchValues_Helper(note, noteName, nearestLowerScaleStepIndex); } else { setNotePitchValues_Helper(note, noteName, nearestHigherScaleStepIndex); } } } /** * Helper method for setNotePitchValues(). Sets the scaleStep and * chromatic adjustment on the note, given a noteName and a scaleStepIndex. * * @param note the scaleStep and chromatic adjustment will be set on this * note * @param noteNameForPitch the noteName of the pitch that should be used to * determine the pitch values * @param scaleStepIndex the index of the scaleStep withing this scales's * scaleStepArray that should be used */ protected void setNotePitchValues_Helper(Note note, NoteName noteNameForPitch, int scaleStepIndex) { note.setScaleStep(scaleStepIndex); int givenNoteHalfStepAboveTonic = this.getKeyName().getPositiveChromaticSteps(noteNameForPitch); int diatonicNoteHalfStepsAboveTonic = this.getScaleStepArray()[scaleStepIndex]; int chromaticAdjustment = getNormalizedChromaticAdjustment(givenNoteHalfStepAboveTonic - diatonicNoteHalfStepsAboveTonic); note.setChromaticAdjustment(chromaticAdjustment); } /** * Gets a list of valid keys for this scale type. * * @return a list of valid keys */ public List<NoteName> getValidKeyNames() { return this.getKeySignature().getTonality().getValidKeyNames(); } /** * Gets a new scale that is of the same type, but uses a different key. * * @param key the new key * @return the new scale * @throws com.myronmarston.music.scales.InvalidKeySignatureException if * the given key produces a KeySignature with more than 7 sharps or * flats */ public Scale getCopyWithDifferentKey(NoteName key) throws InvalidKeySignatureException { Scale scale = this.clone(); scale.keySignature = new KeySignature(this.keySignature.getTonality(), key); return scale; } /** * Gets a recommended number of letter numbers to transpose, based on the * given number of scale steps. * * @param transposeScaleSteps the number of scale steps * @return the recommended number of letter numbers to transpose */ public int getRecommendedTransposeLetterNumber(int transposeScaleSteps) { return this.getLetterNumberArray()[this.getNormalizedScaleStep(transposeScaleSteps)]; } @Override public Scale clone() { try { return (Scale) super.clone(); } catch (CloneNotSupportedException ex) { // We have implemented the Cloneable interface, so we should never // get this exception. If we do, there's something very, very wrong... throw new UndeclaredThrowableException(ex, "Unexpected error while cloning. This indicates a programming or JVM error."); } } @Override public String toString() { return this.getKeyName().toString() + this.getClass().getSimpleName().replaceAll("([A-Z])", " $1"); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Scale other = (Scale) obj; if (this.keySignature != other.keySignature && (this.keySignature == null || !this.keySignature.equals(other.keySignature))) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 79 * hash + (this.keySignature != null ? this.keySignature.hashCode() : 0); hash = 79 * hash + this.getClass().hashCode(); return hash; } }
package pl.manufacturer.object.util; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class ArgumentTypeUtil { private ArgumentTypeUtil() { } public static boolean isBaseType(Type type) { return type.equals(String.class) || type.equals(Boolean.class) || type.equals(Boolean.TYPE) || type.equals(Integer.class) || type.equals(Integer.TYPE) || type.equals(Long.class) || type.equals(Long.TYPE) || type.equals(Double.class) || type.equals(Double.TYPE) || type.equals(Float.class) || type.equals(Float.TYPE) || type.equals(Character.class) || type.equals(Character.TYPE) || type.equals(Byte.class) || type.equals(Byte.TYPE) || type.equals(Short.class) || type.equals(Short.TYPE); } public static Class getCollectionArgumentTypeFromSetterMethod(Method method) { Type[] types = method.getGenericParameterTypes(); ParameterizedType pType = (ParameterizedType) types[0]; return (Class<?>) pType.getActualTypeArguments()[0]; } }
package com.huotn.bootjsp.bootjsp.controller; /** * @Description: WeixinController * * @Auther: leichengyang * @Date: 2019/4/29 0029 * @Version 1.0 */ import com.huotn.bootjsp.bootjsp.common.MenuMain; import com.huotn.bootjsp.bootjsp.config.weixin.mp.WeChatUtil; import com.huotn.bootjsp.bootjsp.pojo.AccessToken; import com.huotn.bootjsp.bootjsp.service.WechatService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Enumeration; @Controller public class WeixinController { @Resource private RestTemplate restTemplate; @Autowired private WechatService wechatService; @Autowired private MenuMain menue; @Value("${appid}") private String appid; @Value("${secret}") private String secret; /** * ๅคšๅช’ไฝ“ๆ–‡ไปถไธŠไผ  * ๅ‚ๆ•ฐ๏ผšaccess_token๏ผŒtype๏ผšๅ›พ็‰‡๏ผˆimage๏ผ‰ใ€่ฏญ้Ÿณ๏ผˆvoice๏ผ‰ใ€่ง†้ข‘๏ผˆvideo๏ผ‰ๅ’Œ็ผฉ็•ฅๅ›พ๏ผˆthumb๏ผ‰ */ public String uploadMediaUrl = "http://file.api.weixin.qq.com/cgi-bin/media/upload"; /** * ๅคšๅช’ไฝ“ๆ–‡ไปถไธ‹่ฝฝ * ๅ‚ๆ•ฐ๏ผšaccess_token๏ผŒmedia_id๏ผšไธŠไผ ๅŽไผšๅพ—ๅˆฐ */ public String downloadMediaUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get"; @RequestMapping(value = "getAccessToken") public String getAccessToken() { String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; AccessToken accessToken = restTemplate.getForObject(url, AccessToken.class); if (StringUtils.hasText(accessToken.getAccess_token())) { return accessToken.getAccess_token(); } return null; } // @GetMapping(value = "wechat") // public String validate(@RequestParam(value = "signature") String signature, // @RequestParam(value = "timestamp") String timestamp, // @RequestParam(value = "nonce") String nonce, // @RequestParam(value = "echostr") String echostr) { // if (WeChatUtil.checkSignature(signature, timestamp, nonce)) { // return echostr; // } else { // return null; // } // } @GetMapping(value = "wechat") public void get(HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("WechatController ---- WechatController"); System.out.println("========WechatController========= "); System.out.println("่ฏทๆฑ‚่ฟ›ๆฅไบ†..."); Enumeration pNames = request.getParameterNames(); while (pNames.hasMoreElements()) { String name = (String) pNames.nextElement(); String value = request.getParameter(name); // out.print(name + "=" + value); String log = "name =" + name + " value =" + value; System.out.println(log); } String signature = request.getParameter("signature");/// ๅพฎไฟกๅŠ ๅฏ†็ญพๅ String timestamp = request.getParameter("timestamp");/// ๆ—ถ้—ดๆˆณ String nonce = request.getParameter("nonce"); /// ้šๆœบๆ•ฐ String echostr = request.getParameter("echostr"); // ้šๆœบๅญ—็ฌฆไธฒ PrintWriter out = response.getWriter(); if (WeChatUtil.checkSignature(signature, timestamp, nonce)) { out.print(echostr); } out.close(); out = null; } /** * ๆญคๅค„ๆ˜ฏๅค„็†ๅพฎไฟกๆœๅŠกๅ™จ็š„ๆถˆๆฏ่ฝฌๅ‘็š„ */ @PostMapping(value = "wechat") @ResponseBody public String processMsg(HttpServletRequest request) { // ่ฐƒ็”จๆ ธๅฟƒๆœๅŠก็ฑปๆŽฅๆ”ถๅค„็†่ฏทๆฑ‚ return wechatService.processRequest(request); } @GetMapping(value="/wxmenu") public void home() { String token=""; String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + "wx5f0e6b073a6f4d49" + "&secret=" + "08cf359d7664a8af8d1d71334c236f63"; AccessToken accessToken = restTemplate.getForObject(url, AccessToken.class); if (StringUtils.hasText(accessToken.getAccess_token())) { token=accessToken.getAccess_token(); } menue.createMenu(token); } @GetMapping(value="/wxmenu/get") public void getMenu() throws UnsupportedEncodingException { String token=""; String url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=53_Xrj46-JcQeYq3CDBgrxGDLxkXtzkq5Fvrn9Iy_arXUaZJ7t1jzjKpUqzLvDpbLtMB6L8HZkKZrFMD8jkjXGs_jH8QuNtiX6j4ZcfFepl7VN1KekLFhtIA-PqNrdQcFiFeUWF9p9Clv1c5YifKJVgAHAFEQ"; String menuInfo=restTemplate.getForObject(url, String.class); System.out.println(new String(menuInfo.getBytes("UTF-8"),"ISO-8859-1")); } }
package com.article.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; @SpringBootApplication @EnableElasticsearchRepositories (basePackages = {"com.article.repository"}) @ComponentScan(basePackages = {"com.article"}) public class CrawlerApplication { public static void main(String[] args) throws Exception{ SpringApplication.run(CrawlerApplication.class, args); } }
package guis; import java.util.ArrayList; import org.lwjgl.input.Mouse; import engineTester.MainGameLoop; public class Menu { public ArrayList<GuiButton> buttons = new ArrayList<GuiButton>(); public GuiTexture background; public Menu(GuiTexture background, GuiButton... button){ for(GuiButton b : button){ buttons.add(b); } this.background = background; } public void render(){ renderBackground(); renderButtons(); } private void renderButtons(){ for(GuiButton b : buttons){ b.render(); } } private void renderBackground(){ MainGameLoop.guiTextures.add(background); } public void update(){ updateButtons(); updateBackground(); if(Mouse.isButtonDown(0)){ onClick(); } } private void updateButtons(){ if(Mouse.isInsideWindow()){ int DX = Math.abs(Mouse.getX()); int DY = Math.abs(Mouse.getY()); for(GuiButton b : buttons){ b.update(DX, DY); } } } private void updateBackground(){ } private void onClick(){ for(GuiButton b : buttons){ if(b.onClick()){ stopRender(); return; } } } public void stopRender(){ stopRenderButtons(); stopRenderBackground(); } private void stopRenderButtons(){ for(GuiButton b : buttons){ b.stopRender(); } } private void stopRenderBackground(){ MainGameLoop.guiTextures.remove(background); MainGameLoop.state = GameStates.GAME; } }
package commands; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; public class Log extends Command { private static String logChannel; private static boolean logChannelCheck; public Log() { super.name = "log"; super.aliases = new String[] {"logcheck"}; super.arguments = "enable/disable"; super.help = "Enables/disables log events in the desired channel."; super.ownerCommand = true; logChannelCheck = false; logChannel = ""; } @Override protected void execute(CommandEvent event) { String[] messageA = event.getMessage().getContentRaw().split(" "); if (messageA.length > 2) event.reply("Too many args for this command."); if (messageA[0].equals(".logcheck")) { if (logChannel.equals("")) { event.reply("There is no log channel."); } else { event.reply(event.getGuild().getTextChannelById(logChannel).getAsMention() + " " + logChannelCheck); } } else if (messageA[0].equals(".log")) { if (messageA[1].equals("enable")) { setLogChannel(event.getChannel().getId()); setLogChannelCheck(true); event.reply("Logs have been set up in this channel."); } else { setLogChannelCheck(false); event.reply("Logs have been disabled in this channel."); } } } public static String getLogChannel() { return logChannel; } public static boolean getLogChannelCheck() { return logChannelCheck; } public void setLogChannel(String log) { logChannel = log; } public void setLogChannelCheck(boolean bool) { logChannelCheck = bool; } }
package mx.infotec.inflector.engine; import java.io.BufferedReader; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import mx.infotec.inflector.engine.Dictionary.Analysis; /** * * @author Roberto Villarejo Martinez <roberto.villarejo@infotec.mx> * */ public class SpanishInflector implements Inflector{ public final Dictionary dict; public final Logger log = LoggerFactory.getLogger(SpanishInflector.class); public SpanishInflector(BufferedReader reader) throws IOException { dict = new Dictionary(reader); } /** * Singularize a word * @param word * @return the response */ public String singularize(String word) { return this.process(word, 'S'); } /** * Pluralize given word * @param word * @return the response */ public String pluralize (String word) { return this.process(word, 'P'); } private String process(String word, char number) { Analysis an = dict.searchForm(word); if (an == null) return null; char genre = an.getTag().charAt(2); // Can be 'M' or 'F' String pluralTag = "NC" + genre + number + "000"; String result; result = dict.getForms(an.getLemma(), pluralTag); if (result != null ) return result; String invariableTag = "NC" + genre + "N000"; return dict.getForms(an.getLemma(), invariableTag); } }
//ะฟะพะดัั‡ะตั‚ ัะบะพะปัŒะบะพ ะบะฐะบะธั… ะฑัƒะบะพะฒ ะฒะพ ะฒะฒะตะดะตะฝั‹ั… ัั‚ั€ะพั‡ะบะฐั… package Tasks; import java.io.*; import java.util.*; public class Task53 { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // ะะปั„ะฐะฒะธั‚ List<Character> alphabet = Arrays.asList( 'ะฐ', 'ะฑ', 'ะฒ', 'ะณ', 'ะด', 'ะต', 'ั‘', 'ะถ', 'ะท', 'ะธ', 'ะน', 'ะบ', 'ะป', 'ะผ', 'ะฝ', 'ะพ', 'ะฟ', 'ั€', 'ั', 'ั‚', 'ัƒ', 'ั„', 'ั…', 'ั†', 'ั‡', 'ัˆ', 'ั‰', 'ัŠ', 'ั‹', 'ัŒ', 'ั', 'ัŽ', 'ั'); // ะ’ะฒะพะด ัั‚ั€ะพะบ ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < 10; i++) { String line = reader.readLine(); list.add(line.toLowerCase()); } ArrayList<Character> ch = new ArrayList<>(); for(String a: list){ char[] c = a.toCharArray(); for(Character b: c) { ch.add(b); } } for (int i = 0; i < 33; i++){ int n = 0; for (char c: ch){ if(alphabet.get(i) == c){ n++; } } System.out.println(alphabet.get(i) + " " + n); } } }
package com.example.netflix_project.src.main.home; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.netflix_project.R; import com.example.netflix_project.src.BaseActivity; import com.example.netflix_project.src.main.home.Adapter.MoviesAdapter; import com.example.netflix_project.src.main.home.Adapter.PreviewAdapter; import com.example.netflix_project.src.main.interfaces.MovieGenreView; import com.example.netflix_project.src.main.interfaces.NewGenreView; import com.example.netflix_project.src.main.interfaces.PopularMovieView; import com.example.netflix_project.src.main.models.Movie; import com.example.netflix_project.src.main.models.MovieService; import java.util.List; public class GenreActivity extends Fragment implements PopularMovieView, NewGenreView, MovieGenreView { private View view; private String genre; TextView mGenreList, mMenu; //๋ฆฌ์‚ฌ์ดํด๋Ÿฌ๋ทฐ private RecyclerView mPopularRecycler, mPreviewRecycler, mNewMvRecycler; private MoviesAdapter mAdapterPopular, mAdapterNew; private PreviewAdapter mPreviewAdapter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view=inflater.inflate(R.layout.movie,container,false); genre=GenrePageActivity.genre; mGenreList=view.findViewById(R.id.home_movie_genre_list); mGenreList.setText(genre); //-------๋ฏธ๋ฆฌ๋ณด๊ธฐ--------- mPreviewRecycler=view.findViewById(R.id.movie_select_preview_recycler); mPreviewRecycler.setLayoutManager(new GridLayoutManager(getContext(),1,GridLayoutManager.HORIZONTAL,false)); //------์žฅ๋ฅด๋ณ„ ์ธ๊ธฐ์žˆ๋Š” ์ฝ˜ํ…์ธ ------- mPopularRecycler=view.findViewById(R.id.movie_select_popular_recycler); mPopularRecycler.setLayoutManager(new GridLayoutManager(getContext(),1,GridLayoutManager.HORIZONTAL,false)); //-------์žฅ๋ฅด๋ณ„ ์ƒˆ๋กœ์šด ์ฝ˜ํ…์ธ ------- mNewMvRecycler=view.findViewById(R.id.movie_select_now_list); mNewMvRecycler.setLayoutManager(new GridLayoutManager(getContext(),1,GridLayoutManager.HORIZONTAL,false)); //-------์žฅ๋ฅด ๋ฆฌ์ŠคํŠธ ๋ณด๊ธฐ--------------- mGenreList=view.findViewById(R.id.home_movie_genre_list); mGenreList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getContext(), GenreListActivity.class); startActivity(intent); } }); //---------์ „์ฒด ๋ฉ”๋‰ด------------- mMenu=view.findViewById(R.id.movie_menu_select); mMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getContext(), MenuActivity.class); startActivity(intent); } }); getMovies(); return view; } private void getMovies() { MovieService movieService =new MovieService((MovieGenreView)this); MovieService moviesRepositoryPopular=new MovieService((PopularMovieView) this); MovieService moviesRepositoryNew=new MovieService((NewGenreView) this); movieService.getMovieGenre(GenrePageActivity.num); moviesRepositoryPopular.getPopularGenreMovie(); moviesRepositoryNew.getNewGenreMovie(); } @Override public void onGenreMovieSuccess(List<Movie> movies) { mPreviewAdapter=new PreviewAdapter(getContext(),movies); mPreviewRecycler.setAdapter(mPreviewAdapter); } @Override public void onGenreNewMovieSuccess(List<Movie> movies) { mAdapterNew=new MoviesAdapter(getContext(),movies); mNewMvRecycler.setAdapter(mAdapterNew); } @Override public void onGenrePopularMovieSuccess(List<Movie> movies) { mAdapterPopular=new MoviesAdapter(getContext(),movies); mPopularRecycler.setAdapter(mAdapterPopular); } @Override public void onError() { Toast.makeText(getContext(), " getString(R.string.network_error", Toast.LENGTH_LONG).show(); } // public void onClickMenu(View view){ // Intent intent=new Intent(getApplicationContext(), MenuActivity.class); // startActivity(intent); // } }
package kr.co.wisenut.editor.dao.impl; import java.util.List; import kr.co.wisenut.editor.dao.EditorDao; import kr.co.wisenut.db.*; import kr.co.wisenut.editor.model.Country; import kr.co.wisenut.editor.model.FormVO; import kr.co.wisenut.editor.model.Period; import kr.co.wisenut.editor.model.ScenePersonMapping; import kr.co.wisenut.editor.model.Scene; import kr.co.wisenut.editor.model.Video; import kr.co.wisenut.util.StringUtil; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; @Repository("SceneMapper") public class EditorDaoImpl implements EditorDao { private static final Logger logger = LoggerFactory.getLogger(EditorDaoImpl.class); private final SessionService sessionService = new SessionService(DB_ENV.PROD0); @Override public List<Video> getVideoList(FormVO vo){ SqlSession session = null; List<Video> videoList = null; try{ session = sessionService.getSession(); videoList = session.selectList("VideoMapper.getVideoList", vo); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return videoList; } @Override public List<Scene> getSceneList(FormVO vo){ SqlSession session = null; List<Scene> sceneList = null; try{ session = sessionService.getSession(); sceneList = session.selectList("SceneMapper.getSceneList", vo); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return sceneList; } @Override public List<Period> getPeriodList(){ SqlSession session = null; List<Period> periodList = null; try{ session = sessionService.getSession(); periodList = session.selectList("EntryMapper.periodList"); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return periodList; } @Override public List<Country> getCountryList(String domAbr){ SqlSession session = null; List<Country> countryList = null; try{ session = sessionService.getSession(); logger.debug("[getCountryList] domAbr : " + domAbr); if(null != domAbr && !"".equals(domAbr)){ countryList = session.selectList("EntryMapper.countryList", domAbr); }else{ countryList = session.selectList("EntryMapper.countryList"); } }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return countryList; } @Override public List<Country> getCountryList(FormVO vo){ SqlSession session = null; List<Country> countryList = null; try{ session = sessionService.getSession(); if(null == vo.getDomAbr() || "".equals(vo.getDomAbr())){ countryList = session.selectList("EntryMapper.countryList"); }else{ countryList = session.selectList("EntryMapper.countryList", vo.getDomAbr()); } }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return countryList; } @Override public List<ScenePersonMapping> getPersonList(String celebrityNm){ SqlSession session = null; List<ScenePersonMapping> personList = null; try{ session = sessionService.getSession(); if(null == celebrityNm || "".equals(celebrityNm)){ personList = session.selectList("EntryMapper.personList"); }else{ personList = session.selectList("EntryMapper.personList", celebrityNm); } }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return personList; } @Override public Scene findScene(FormVO vo) { SqlSession session = null; Scene theScene = null; try{ session = sessionService.getSession(); theScene = (Scene)session.selectOne("SceneMapper.findScene", vo); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return theScene; } @Override public Video findVideo(String id) { SqlSession session = null; Video theVideo = null;; try{ session = sessionService.getSession(); theVideo = (Video)session.selectOne("VideoMapper.findVideo", id); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return theVideo; } public void printString(String str){ System.out.println(str); } @Override public int updateScene(FormVO vo){ SqlSession session = null; int resultCount = 0; try{ session = sessionService.getSession(); resultCount = session.update("SceneMapper.updateScene", vo); session.commit(); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); session.rollback(); }finally{ session.close(); } logger.info("Update count : " + resultCount); return resultCount; } @Override public int insertScene(FormVO vo){ SqlSession session = null; int resultCount = 0; try{ session = sessionService.getSession(); resultCount = session.insert("SceneMapper.insertScene", vo); session.commit(); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); session.rollback(); }finally{ session.close(); } logger.info("Insert count : " + resultCount); return resultCount; } @Override public int deleteScene(FormVO vo){ SqlSession session = null; int resultCount = 0; try{ session = sessionService.getSession(); resultCount = session.delete("SceneMapper.deleteScene", vo); session.commit(); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); session.rollback(); }finally{ session.close(); } logger.info("Delete count : " + resultCount); return resultCount; } @Override public String findVideoFilePath(FormVO vo) { SqlSession session = sessionService.getSession(); String filePath = null; try{ session = sessionService.getSession(); filePath = (String)session.selectOne("VideoMapper.findVideoFile", vo); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return filePath; } @Override public int scenePersonMapping(FormVO vo) { SqlSession session = null; int resultCount = 0; try{ session = sessionService.getSession(); resultCount = session.insert("EntryMapper.scenePersonMapping", vo); session.commit(); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); session.rollback(); }finally{ session.close(); } logger.info("Insert count : " + resultCount); return resultCount; } @Override public int deletePersonFromMapping(FormVO vo) { SqlSession session = null; int resultCount = 0; try{ session = sessionService.getSession(); if(vo.getPersonKorNm() != null){ resultCount = session.delete("EntryMapper.deletePersonFromMapping", vo); }else{ // ์žฅ๋ฉด์ด ์‚ญ์ œ๋˜๋ฉด scene_person_mapping ์˜ ํŠน์ • ์žฅ๋ฉด ๊ด€๋ จ ์ •๋ณด๋ฅผ ๋ชจ๋‘ ์‚ญ์ œ. resultCount = session.delete("EntryMapper.deleteMapping", vo); } session.commit(); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); session.rollback(); }finally{ session.close(); } logger.info("Delete count : " + resultCount); return resultCount; } @Override public List<ScenePersonMapping> getScenePersonMapping(FormVO vo) { SqlSession session = null; List<ScenePersonMapping> personList = null; try{ session = sessionService.getSession(); personList = session.selectList("EntryMapper.getScenePersonMapping", vo); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return personList; } @Override public int getVideoTotalCount(FormVO vo) { SqlSession session = null; int totalCount = 0; try{ session = sessionService.getSession(); totalCount = (Integer)session.selectOne("VideoMapper.getVideoTotalCount", vo); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return totalCount; } @Override public int getNewScnId() { SqlSession session = null; int scnId = 0; try{ session = sessionService.getSession(); scnId = (Integer)session.selectOne("SceneMapper.getNewScnId"); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return scnId; } @Override public int getMaxRuntime() { SqlSession session = null; int maxRuntime = 0; try{ session = sessionService.getSession(); maxRuntime = (Integer)session.selectOne("VideoMapper.getMaxRuntime"); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); }finally{ session.close(); } return maxRuntime; } }
package com.zemoso.training.service; import com.zemoso.training.entity.User; import com.zemoso.training.exception.ResourceNotFoundException; import com.zemoso.training.exception.ValidationException; import com.zemoso.training.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserServiceImpl implements UserService { private final UserRepository userRepository; @Autowired public UserServiceImpl(UserRepository userRepository){ this.userRepository = userRepository; } @Override public User createNewUser(User user) { if(user == null) { throw new ValidationException("User information is not provided."); } return userRepository.save(user); } @Override public List<User> getAllUsers() { List<User> users = userRepository.findAll(); if(users.isEmpty()) { throw new ResourceNotFoundException("No users found."); } return users; } @Override public User findUserByUserName(String username) { Optional<User> optionalUser = userRepository.findByUserName(username); if(optionalUser.isPresent()){ return optionalUser.get(); } else{ throw new ResourceNotFoundException(username + " not found."); } } @Override public User updateUser(User user) { Optional<User> existingUser = userRepository.findById(user.getUserId()); User user1; if(existingUser.isPresent()){ user1 = existingUser.get(); } else { throw new ResourceNotFoundException(user.getUsername() + " User not found."); } user1.setUserId(user.getUserId()); user1.setUserId(user.getUserId()); user1.setActive(user.isActive()); user1.setAdmin(user.isAdmin()); user1.setEmail(user.getEmail()); user1.setName(user.getName()); user1.setUsername(user.getUsername()); return userRepository.save(user1); } }
package hiring.service; import com.google.gson.Gson; import hiring.daointerface.DataBaseDaoImpl; import hiring.database.DataBaseException; import hiring.dto.ErrorDto; import java.io.File; abstract public class ServerService { private static DataBaseDaoImpl dataBaseDao = new DataBaseDaoImpl(); public static String startDataBase(){ dataBaseDao.startDataBase(); return ""; } public static String saveDataBase(String file){ ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); if(file == null){ errorDto.setError("Wrong file name"); return gson.toJson(errorDto); } File file1 = new File(file); try { dataBaseDao.saveDataBase(file1); }catch (DataBaseException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String loadDataBase(String file){ ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); if(file == null){ errorDto.setError("Wrong file name"); return gson.toJson(errorDto); } File file1 = new File(file); try { dataBaseDao.loadDataBase(file1); }catch (DataBaseException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } }
package ProjectStarterCode.model; public class Food { /** * Produces the food that the snake will eat, which * will be in one of the tiles of the board. */ public Tile location; public Board board; /** * Produces a food object which will be placed on a tile of the board * * @param board the board in which the food will be placed */ public Food(Board board) { this.board = board; this.location = null; spawnFood(); } /** * Produces a food object which will be placed on a tile of the board * * @param board the board in which the food will be placed * @param x is the x coordinate of where the food will be placed on the Board * @param y is the y coordinate of where the food will be placed on the Board */ public Food(Board board, int x, int y) { this.board = board; this.location = board.tiles[x][y]; board.tiles[x][y].setInsideTile("food"); } /** * Spawns food on a random tile that contains * nothing, if food is not on the board */ public void spawnFood() { //needs to look at board and choose unoccupied tile if (!foodIsOnBoard()) { int x = (int) (Math.random() * board.tiles.length); int y = (int) (Math.random() * board.tiles.length); while (board.tiles[x][y].getInsideTile().compareTo("nothing") != 0) { x = (int) (Math.random() * board.tiles.length); y = (int) (Math.random() * board.tiles.length); } board.tiles[x][y].setInsideTile("food"); location = board.tiles[x][y]; } } /** * Checks whether food is on board * * @return true or false, depending if food is found or not on the board. */ public boolean foodIsOnBoard() { //iterate through tiles of board and check if food is there for (int i = 0; i < board.tiles.length; i++) { for (int j = 0; j < board.tiles[0].length; j++) { if (board.tiles[i][j].getInsideTile().compareTo("food") == 0) { return true; } } } return false; } /** * Returns the String with the location of the food * * @return the String with the location of the food */ @Override public String toString() { return location.toString(); } }
/* * Copyright (c) MyScript. All rights reserved. */ package com.myscript.iink.samples.search; import com.google.gson.annotations.SerializedName; import java.util.List; public class JiixRawContent { @SerializedName("type") public String type; @SerializedName("elements") public List<Element> elements; public class Element { @SerializedName("type") public String type; @SerializedName("words") public List<Word> words; @SerializedName("chars") public List<Char> chars; } public class Word { @SerializedName("label") public String label; @SerializedName("first-char") public int firstChar; @SerializedName("last-char") public int lastChar; @SerializedName("bounding-box") public BoundingBox boundingBox; } public class Char { @SerializedName("label") public String label; @SerializedName("word") public int word; @SerializedName("bounding-box") public BoundingBox boundingBox; } public class BoundingBox { @SerializedName("x") public float x; @SerializedName("y") public float y; @SerializedName("width") public float width; @SerializedName("height") public float height; } }
package statealarma; import java.util.Scanner; public class pruebaEstado { public static void main(String...args){ Alarma alarma = new Alarma(); Activa activa= new Activa(); mantenimenito mantenimineto = new mantenimenito(); int opcion = 0 ; @SuppressWarnings("resource") Scanner sc= new Scanner(System.in); do { menu(); opcion =sc.nextInt(); switch(opcion){ case 1 : alarma.setestado(activa); break; case 2: alarma.setestado(mantenimineto); break; case 0 : System.exit(0); default: System.out.println("opcion cerrada"); } alarma.ejecutar(); }while(opcion!=0); } private static void menu() { // TODO Auto-generated method stub StringBuffer menus =new StringBuffer(); menus.append("******* \n"); menus.append("***seleccion estado de alarma *** \n"); menus.append("*1 - Activa. 2 - mantenimiento 0 - salir \n"); menus.append("******* \n"); System.out.println(menus.toString()); } }
package pp.model.comparators; import pp.model.xml.CGlad; import java.util.Comparator; /** * Created by alsa on 25.06.2016. */ public class GladAgeComparator implements Comparator<CGlad> { @Override public int compare(CGlad o1, CGlad o2) { return Long.valueOf(o1.getAge()).compareTo(o2.getAge()); } }
package cn.ccuwxy.service; import cn.ccuwxy.dao.UserInfoDao; import cn.ccuwxy.dao.UserInfoImpl; import cn.ccuwxy.model.UserInfo; public class UserInfoServiceImpl implements UserInfoService { private UserInfoDao userInfoDao = new UserInfoImpl(); @Override public boolean intoUserInfo(UserInfo userInfo) { return userInfoDao.intoUserInfo(userInfo); } @Override public UserInfo findByStuNumber(String stuNumber) { return userInfoDao.findByStuNumber(stuNumber); } }
package raft.server; public interface TimeoutManager extends LifeCycle { boolean isElectionTimeout(); long getElectionTimeoutTicks(); void resetElectionTimeoutTicks(); void clearAllTimeoutMark(); void clearElectionTickCounter(); void clearAllTickCounters(); long getLastClearTimeoutAt(); }
package io; import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("What is your name? "); String name = scanner.nextLine(); System.out.print("How old are you? "); int age = scanner.nextInt(); System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1)); System.out.printf("Hello, %s. Next year, you'll be %d\n", name, age + 1); System.out.println(String.format("Hello, %s. Next year, you'll be %d", name, age + 1)); scanner.close(); } }
/* * 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 morfologia; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Luciano */ public class Modificador extends Thread{ private volatile Archivo archivo; private int fila; private int col; private final Figura figura; public Modificador(final Archivo archivo, final int fila, final int col, final Figura figura) { this.archivo = archivo; this.fila = fila; this.col = col; this.figura = figura; } @Override public void run() { int tamaรฑo = archivo.getData2D().length; for (int i = 0; i < tamaรฑo; i++) { try { this.fila=i; figura.modificar(fila, col); //System.out.println(col); } catch (Exception ex) { Logger.getLogger(Modificador.class.getName()).log(Level.SEVERE, null, ex); } } } }
package com.zc.base.sys.modules.user.entity; public class Reply { private String account; private String ipAddr; private String replyCreateTime; public Reply(String account, String ipAddr, String replyCreateTime) { this.account = account; this.ipAddr = ipAddr; this.replyCreateTime = replyCreateTime; } public Reply() { } public String getAccount() { return this.account; } public void setAccount(String account) { this.account = account; } public String getIpAddr() { return this.ipAddr; } public void setIpAddr(String ipAddr) { this.ipAddr = ipAddr; } public String getReplyCreateTime() { return this.replyCreateTime; } public void setReplyCreateTime(String replyCreateTime) { this.replyCreateTime = replyCreateTime; } }
package com.jerry.cyclicbarrier; /** * Date: 17/9/7 18:36 * * @author jerry.R */ public class ArriveTask implements Runnable { @Override public void run() { System.out.println("inside CyclicBarrier..."); } }
package net.awesomekorean.podo.lesson.lessonVideo; import net.awesomekorean.podo.R; public class LessonVideoHangul implements Video { String title = "Hangul"; int[] videoImage = { R.drawable.hangul00, R.drawable.hangul01, R.drawable.hangul02, R.drawable.hangul03, R.drawable.hangul04, R.drawable.hangul05, R.drawable.hangul06, R.drawable.hangul07, R.drawable.hangul08, R.drawable.hangul09}; String[] videoTitle = { "Intro", "ใ…,ใ…“,ใ…—,ใ…œ,ใ…ก,ใ…ฃ", "ใ„ฑ,ใ„ด,ใ…,ใ……", "ใ…‘,ใ…•,ใ…›,ใ… ", "ใ„ท,ใ„น,ใ…‚,ใ…ˆ", "ใ„ฑ,ใ„ด,ใ„น,ใ…,ใ…‚,ใ…‡,ใ„ท,ใ……,ใ…ˆ", "ใ…,ใ…”,ใ…’,ใ…–", "ใ…‹,ใ…,ใ…Œ,ใ…Š,ใ…Ž", "ใ…˜,ใ…,ใ…™,ใ…ž,ใ…š,ใ…Ÿ,ใ…š", "ใ„ฒ,ใ…ƒ,ใ„ธ,ใ…†,ใ…‰"}; String[] videoId = { "mP4yU2tWtn0", "3xP1EyHJh6g", "47LZ-GrYrz4", "UXsRZJaVjyQ", "l3ouwQ3l_2g", "h1iWxQT2U5k", "YFrliCF2kWA", "J8TZEAd4mzo", "r9_IeMM09d8", "pWBOHngyek0"}; String[] videoLength = {"0:48", "2.49", "4:05", "1:37", "3:20", "6:58", "1:17", "2:38", "2:32", "3:35"}; public String getTitle() { return title; } @Override public String[] getVideoTitle() { return videoTitle; } @Override public int[] getVideoImage() { return videoImage; } @Override public String[] getVideoId() { return videoId; } @Override public String[] getVideoLength() { return videoLength; } }
package ch3; import java.util.Scanner; public class ex_C2F { public static void main(String[] args) { // TODO Auto-generated method stub //f = c * 9/5 +32 Scanner scn = new Scanner(System.in); double f; double c; double m = 9/5; int cons = 32; System.out.print("input> "); c = scn.nextDouble(); f = c*m+cons; System.out.printf("Result> %.1fC = %.1fF\n",c,f); } }
/* * 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.context.support; import org.junit.jupiter.api.Test; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.testfixture.beans.TestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; import org.springframework.util.Assert; import static org.assertj.core.api.Assertions.assertThat; /** * Tests the interaction between {@link ApplicationContext} implementations and * any registered {@link BeanFactoryPostProcessor} implementations. Specifically * {@link StaticApplicationContext} is used for the tests, but what's represented * here is any {@link AbstractApplicationContext} implementation. * * @author Colin Sampaleanu * @author Juergen Hoeller * @author Chris Beams * @since 02.10.2003 */ class BeanFactoryPostProcessorTests { @Test void registeredBeanFactoryPostProcessor() { StaticApplicationContext ac = new StaticApplicationContext(); ac.registerSingleton("tb1", TestBean.class); ac.registerSingleton("tb2", TestBean.class); TestBeanFactoryPostProcessor bfpp = new TestBeanFactoryPostProcessor(); ac.addBeanFactoryPostProcessor(bfpp); assertThat(bfpp.wasCalled).isFalse(); ac.refresh(); assertThat(bfpp.wasCalled).isTrue(); ac.close(); } @Test void definedBeanFactoryPostProcessor() { StaticApplicationContext ac = new StaticApplicationContext(); ac.registerSingleton("tb1", TestBean.class); ac.registerSingleton("tb2", TestBean.class); ac.registerSingleton("bfpp", TestBeanFactoryPostProcessor.class); ac.refresh(); TestBeanFactoryPostProcessor bfpp = (TestBeanFactoryPostProcessor) ac.getBean("bfpp"); assertThat(bfpp.wasCalled).isTrue(); ac.close(); } @Test @SuppressWarnings("deprecation") void multipleDefinedBeanFactoryPostProcessors() { StaticApplicationContext ac = new StaticApplicationContext(); ac.registerSingleton("tb1", TestBean.class); ac.registerSingleton("tb2", TestBean.class); MutablePropertyValues pvs1 = new MutablePropertyValues(); pvs1.add("initValue", "${key}"); ac.registerSingleton("bfpp1", TestBeanFactoryPostProcessor.class, pvs1); MutablePropertyValues pvs2 = new MutablePropertyValues(); pvs2.add("properties", "key=value"); ac.registerSingleton("bfpp2", org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.class, pvs2); ac.refresh(); TestBeanFactoryPostProcessor bfpp = (TestBeanFactoryPostProcessor) ac.getBean("bfpp1"); assertThat(bfpp.initValue).isEqualTo("value"); assertThat(bfpp.wasCalled).isTrue(); ac.close(); } @Test void beanFactoryPostProcessorNotExecutedByBeanFactory() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerBeanDefinition("tb1", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("tb2", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("bfpp", new RootBeanDefinition(TestBeanFactoryPostProcessor.class)); TestBeanFactoryPostProcessor bfpp = (TestBeanFactoryPostProcessor) bf.getBean("bfpp"); assertThat(bfpp.wasCalled).isFalse(); } @Test void beanDefinitionRegistryPostProcessor() { StaticApplicationContext ac = new StaticApplicationContext(); ac.registerSingleton("tb1", TestBean.class); ac.registerSingleton("tb2", TestBean.class); ac.addBeanFactoryPostProcessor(new PrioritizedBeanDefinitionRegistryPostProcessor()); TestBeanDefinitionRegistryPostProcessor bdrpp = new TestBeanDefinitionRegistryPostProcessor(); ac.addBeanFactoryPostProcessor(bdrpp); assertThat(bdrpp.wasCalled).isFalse(); ac.refresh(); assertThat(bdrpp.wasCalled).isTrue(); assertThat(ac.getBean("bfpp1", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); assertThat(ac.getBean("bfpp2", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); ac.close(); } @Test void beanDefinitionRegistryPostProcessorRegisteringAnother() { StaticApplicationContext ac = new StaticApplicationContext(); ac.registerSingleton("tb1", TestBean.class); ac.registerSingleton("tb2", TestBean.class); ac.registerBeanDefinition("bdrpp2", new RootBeanDefinition(OuterBeanDefinitionRegistryPostProcessor.class)); ac.refresh(); assertThat(ac.getBean("bfpp1", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); assertThat(ac.getBean("bfpp2", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); ac.close(); } @Test void prioritizedBeanDefinitionRegistryPostProcessorRegisteringAnother() { StaticApplicationContext ac = new StaticApplicationContext(); ac.registerSingleton("tb1", TestBean.class); ac.registerSingleton("tb2", TestBean.class); ac.registerBeanDefinition("bdrpp2", new RootBeanDefinition(PrioritizedOuterBeanDefinitionRegistryPostProcessor.class)); ac.refresh(); assertThat(ac.getBean("bfpp1", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); assertThat(ac.getBean("bfpp2", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); ac.close(); } @Test void beanFactoryPostProcessorAsApplicationListener() { StaticApplicationContext ac = new StaticApplicationContext(); ac.registerBeanDefinition("bfpp", new RootBeanDefinition(ListeningBeanFactoryPostProcessor.class)); ac.refresh(); assertThat(ac.getBean(ListeningBeanFactoryPostProcessor.class).received).isInstanceOf(ContextRefreshedEvent.class); ac.close(); } @Test void beanFactoryPostProcessorWithInnerBeanAsApplicationListener() { StaticApplicationContext ac = new StaticApplicationContext(); RootBeanDefinition rbd = new RootBeanDefinition(NestingBeanFactoryPostProcessor.class); rbd.getPropertyValues().add("listeningBean", new RootBeanDefinition(ListeningBean.class)); ac.registerBeanDefinition("bfpp", rbd); ac.refresh(); assertThat(ac.getBean(NestingBeanFactoryPostProcessor.class).getListeningBean().received).isInstanceOf(ContextRefreshedEvent.class); ac.close(); } public static class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor { public String initValue; public void setInitValue(String initValue) { this.initValue = initValue; } public boolean wasCalled = false; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { wasCalled = true; } } public static class PrioritizedBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered { @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { registry.registerBeanDefinition("bfpp1", new RootBeanDefinition(TestBeanFactoryPostProcessor.class)); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } public static class TestBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { public boolean wasCalled; @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { assertThat(registry.containsBeanDefinition("bfpp1")).isTrue(); registry.registerBeanDefinition("bfpp2", new RootBeanDefinition(TestBeanFactoryPostProcessor.class)); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { this.wasCalled = true; } } public static class OuterBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { registry.registerBeanDefinition("anotherpp", new RootBeanDefinition(TestBeanDefinitionRegistryPostProcessor.class)); registry.registerBeanDefinition("ppp", new RootBeanDefinition(PrioritizedBeanDefinitionRegistryPostProcessor.class)); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } public static class PrioritizedOuterBeanDefinitionRegistryPostProcessor extends OuterBeanDefinitionRegistryPostProcessor implements PriorityOrdered { @Override public int getOrder() { return HIGHEST_PRECEDENCE; } } public static class ListeningBeanFactoryPostProcessor implements BeanFactoryPostProcessor, ApplicationListener<ApplicationEvent> { public ApplicationEvent received; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override public void onApplicationEvent(ApplicationEvent event) { Assert.state(this.received == null, "Just one ContextRefreshedEvent expected"); this.received = event; } } public static class ListeningBean implements ApplicationListener<ApplicationEvent> { public ApplicationEvent received; @Override public void onApplicationEvent(ApplicationEvent event) { Assert.state(this.received == null, "Just one ContextRefreshedEvent expected"); this.received = event; } } public static class NestingBeanFactoryPostProcessor implements BeanFactoryPostProcessor { private ListeningBean listeningBean; public void setListeningBean(ListeningBean listeningBean) { this.listeningBean = listeningBean; } public ListeningBean getListeningBean() { return listeningBean; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } }
package com.gaoshin.onsalelocal.osl.entity; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class NotificationList { private List<Notification> items = new ArrayList<Notification>(); public List<Notification> getItems() { return items; } public void setItems(List<Notification> items) { this.items = items; } }
package com.gateway.client; import com.gateway.app.Config; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; public class ApiRequestService { private static final Logger logger = LoggerFactory.getLogger(ApiRequestService.class); /** * Constructs an object used to complete the API. * Contains information about which operation to target and what info is needed in the request body. * Also populates with some pre-filled test data (such as order amount, currency, etc). * * @param apiOperation indicates API operation to target (PAY, AUTHORIZE, CAPTURE, etc) * @return ApiRequest */ public static ApiRequest createApiRequest(String apiOperation, Config config) { ApiRequest req = new ApiRequest(); req.setApiOperation(apiOperation); req.setOrderAmount("5000"); req.setOrderCurrency(config.getCurrency()); req.setOrderId(Utils.createUniqueId("order-")); req.setTransactionId(Utils.createUniqueId("trans-")); if (apiOperation.equals("CAPTURE") || apiOperation.equals("REFUND") || apiOperation.equals("VOID") || apiOperation.equals("UPDATE_AUTHORIZATION")) { req.setOrderId(null); } if (apiOperation.equals("RETRIEVE_ORDER") || apiOperation.equals("RETRIEVE_TRANSACTION")) { req.setApiMethod("GET"); req.setOrderId(null); req.setTransactionId(null); } if (apiOperation.equals("CREATE_CHECKOUT_SESSION")) { req.setApiMethod("POST"); } return req; } /** * Constructs API endpoint * * @param apiProtocol REST or NVP * @param config contains frequently used information like Merchant ID, API password, etc. * @return url */ public static String getRequestUrl(ApiProtocol apiProtocol, Config config, ApiRequest request) { switch (apiProtocol) { case REST: String url = getApiBaseURL(config.getGatewayHost(), apiProtocol) + "/version/" + config.getApiVersion() + "/merchant/" + config.getMerchantId() + "/order/" + request.getOrderId(); if (Utils.notNullOrEmpty(request.getTransactionId())) { url += "/transaction/" + request.getTransactionId(); } return url; case NVP: return getApiBaseURL(config.getGatewayHost(), apiProtocol) + "/version/" + config.getApiVersion(); default: throwUnsupportedProtocolException(); } return null; } /** * Constructs API endpoint to create a new session * * @param apiProtocol REST or NVP * @param config contains frequently used information like Merchant ID, API password, etc. * @return url */ public static String getSessionRequestUrl(ApiProtocol apiProtocol, Config config) { return getApiBaseURL(config.getGatewayHost(), apiProtocol) + "/version/" + config.getApiVersion() + "/merchant/" + config.getMerchantId() + "/session"; } /** * Constructs API endpoint to create a new token * * @param apiProtocol REST or NVP * @param config contains frequently used information like Merchant ID, API password, etc. * @return url */ public static String getTokenRequestUrl(ApiProtocol apiProtocol, Config config) { return getApiBaseURL(config.getGatewayHost(), apiProtocol) + "/version/" + config.getApiVersion() + "/merchant/" + config.getMerchantId() + "/token"; } /** * Constructs API endpoint for session-based requests with an existing session ID * * @param apiProtocol REST or NVP * @param config contains frequently used information like Merchant ID, API password, etc. * @param sessionId used to target a specific session * @return url */ public static String getSessionRequestUrl(ApiProtocol apiProtocol, Config config, String sessionId) { switch (apiProtocol) { case REST: return getApiBaseURL(config.getGatewayHost(), apiProtocol) + "/version/" + config.getApiVersion() + "/merchant/" + config.getMerchantId() + "/session/" + sessionId; case NVP: return getApiBaseURL(config.getGatewayHost(), apiProtocol) + "/version/" + config.getApiVersion(); default: throwUnsupportedProtocolException(); } return null; } /** * Constructs API endpoint for 3DS requests * * @param apiProtocol REST or NVP * @param config contains frequently used information like Merchant ID, API password, etc. * @param secureId used to target a specific secureId * @return url */ public static String getSecureIdRequest(ApiProtocol apiProtocol, Config config, String secureId) { return getApiBaseURL(config.getGatewayHost(), apiProtocol) + "/version/" + config.getApiVersion() + "/merchant/" + config.getMerchantId() + "/3DSecureId/" + secureId; } /** * Constructs the API payload based on properties of ApiRequest * * @param request contains info on what data the payload should include (order ID, amount, currency, etc) depending on the operation (PAY, AUTHORIZE, CAPTURE, etc) * @return JSON string */ public static String buildJSONPayload(ApiRequest request) { JsonObject secureId = new JsonObject(); if (Utils.notNullOrEmpty(request.getPaymentAuthResponse())) { // Used for 3DS Process ACS Result operation secureId.addProperty("paRes", request.getPaymentAuthResponse()); } JsonObject authenticationRedirect = new JsonObject(); // Used for 3DS check enrollment operation if (Utils.notNullOrEmpty(request.getSecureIdResponseUrl())) { authenticationRedirect.addProperty("responseUrl", request.getSecureIdResponseUrl()); authenticationRedirect.addProperty("pageGenerationMode", "CUSTOMIZED"); secureId.add("authenticationRedirect", authenticationRedirect); } // Used for hosted checkout - CREATE_CHECKOUT_SESSION operation JsonObject order = new JsonObject(); if (Utils.notNullOrEmpty(request.getApiOperation()) && request.getApiOperation().equals("CREATE_CHECKOUT_SESSION")) { // Need to add order ID in the request body only for CREATE_CHECKOUT_SESSION. Its presence in the body will cause an error for the other operations. if (Utils.notNullOrEmpty(request.getOrderId())) order.addProperty("id", request.getOrderId()); } if (Utils.notNullOrEmpty(request.getOrderAmount())) order.addProperty("amount", request.getOrderAmount()); if (Utils.notNullOrEmpty(request.getOrderCurrency())) order.addProperty("currency", request.getOrderCurrency()); JsonObject wallet = new JsonObject(); if (Utils.notNullOrEmpty(request.getWalletProvider())) { order.addProperty("walletProvider", request.getWalletProvider()); // Used for Masterpass operations if(request.getWalletProvider().equals("MASTERPASS_ONLINE")) { JsonObject masterpass = new JsonObject(); if(Utils.notNullOrEmpty(request.getMasterpassOriginUrl())) masterpass.addProperty("originUrl", request.getMasterpassOriginUrl()); if(Utils.notNullOrEmpty(request.getMasterpassOauthToken())) masterpass.addProperty("oauthToken", request.getMasterpassOauthToken()); if(Utils.notNullOrEmpty(request.getMasterpassOauthVerifier())) masterpass.addProperty("oauthVerifier", request.getMasterpassOauthVerifier()); if(Utils.notNullOrEmpty(request.getMasterpassCheckoutUrl())) masterpass.addProperty("checkoutUrl", request.getMasterpassCheckoutUrl()); if (!masterpass.entrySet().isEmpty()) wallet.add("masterpass", masterpass); } } JsonObject transaction = new JsonObject(); if (Utils.notNullOrEmpty(request.getTransactionAmount())) transaction.addProperty("amount", request.getTransactionAmount()); if (Utils.notNullOrEmpty(request.getTransactionCurrency())) transaction.addProperty("currency", request.getTransactionCurrency()); if (Utils.notNullOrEmpty(request.getTargetTransactionId())) transaction.addProperty("targetTransactionId", request.getTargetTransactionId()); JsonObject expiry = new JsonObject(); if (Utils.notNullOrEmpty(request.getExpiryMonth())) expiry.addProperty("month", request.getExpiryMonth()); if (Utils.notNullOrEmpty(request.getExpiryYear())) expiry.addProperty("year", request.getExpiryYear()); JsonObject card = new JsonObject(); if (Utils.notNullOrEmpty(request.getSecurityCode())) card.addProperty("securityCode", request.getSecurityCode()); if (Utils.notNullOrEmpty(request.getCardNumber())) card.addProperty("number", request.getCardNumber()); if (!expiry.entrySet().isEmpty()) card.add("expiry", expiry); JsonObject provided = new JsonObject(); if (!card.entrySet().isEmpty()) provided.add("card", card); JsonObject sourceOfFunds = new JsonObject(); if (Utils.notNullOrEmpty(request.getSourceType())) sourceOfFunds.addProperty("type", request.getSourceType()); if (Utils.notNullOrEmpty(request.getSourceToken())) sourceOfFunds.addProperty("token", request.getSourceToken()); if (!provided.entrySet().isEmpty()) sourceOfFunds.add("provided", provided); JsonObject browserPayment = new JsonObject(); if (Utils.notNullOrEmpty(request.getBrowserPaymentOperation())) browserPayment.addProperty("operation", request.getBrowserPaymentOperation()); if (Utils.notNullOrEmpty(request.getSourceType()) && request.getSourceType().equals("PAYPAL")) { JsonObject paypal = new JsonObject(); paypal.addProperty("paymentConfirmation", "CONFIRM_AT_PROVIDER"); browserPayment.add("paypal", paypal); } JsonObject interaction = new JsonObject(); if (Utils.notNullOrEmpty(request.getReturnUrl()) && Utils.notNullOrEmpty(request.getApiOperation())) { // Return URL needs to be added differently for browser payments and hosted checkout payments if (request.getApiOperation().equals("CREATE_CHECKOUT_SESSION")) { interaction.addProperty("returnUrl", request.getReturnUrl()); } else if (request.getApiOperation().equals("INITIATE_BROWSER_PAYMENT") || request.getApiOperation().equals("CONFIRM_BROWSER_PAYMENT")) { browserPayment.addProperty("returnUrl", request.getReturnUrl()); } } if (Utils.notNullOrEmpty(request.getInteractionOperation())){ interaction.addProperty("operation", request.getInteractionOperation()); } if (Utils.notNullOrEmpty(request.getInteractionTimeout())){ interaction.addProperty("timeout", request.getInteractionTimeout()); } if (Utils.notNullOrEmpty(request.getInteractionTimeoutUrl())){ interaction.addProperty("timeoutUrl", request.getInteractionTimeoutUrl()); } JsonObject session = new JsonObject(); if (Utils.notNullOrEmpty(request.getSessionId())) session.addProperty("id", request.getSessionId()); // Add all the elements to the main JSON object we'll return from this method JsonObject data = new JsonObject(); if (Utils.notNullOrEmpty(request.getApiOperation())) data.addProperty("apiOperation", request.getApiOperation()); if (Utils.notNullOrEmpty(request.getSecureId())) data.addProperty("3DSecureId", request.getSecureId()); if (!order.entrySet().isEmpty()) data.add("order", order); if (!wallet.entrySet().isEmpty()) data.add("wallet", wallet); if (!transaction.entrySet().isEmpty()) data.add("transaction", transaction); if (!sourceOfFunds.entrySet().isEmpty()) data.add("sourceOfFunds", sourceOfFunds); if (!browserPayment.entrySet().isEmpty()) data.add("browserPayment", browserPayment); if (!interaction.entrySet().isEmpty()) data.add("interaction", interaction); if (!session.entrySet().isEmpty()) data.add("session", session); if (!secureId.entrySet().isEmpty()) data.add("3DSecure", secureId); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(data); } /** * Constructs the API payload request map based on properties of ApiRequest * * @param request contains info on what data the payload should include (order ID, amount, currency, etc) depending on the operation (PAY, AUTHORIZE, CAPTURE, etc) * @return JSON string */ public static Map<String, String> buildMap(ApiRequest request) { Map<String, String> keyValueMap = new HashMap<>(); keyValueMap.put("apiOperation", "PAY"); keyValueMap.put("order.id", request.getOrderId()); keyValueMap.put("order.amount", request.getOrderAmount()); keyValueMap.put("order.currency", request.getOrderCurrency()); keyValueMap.put("transaction.id", request.getTransactionId()); keyValueMap.put("session.id", request.getSessionId()); keyValueMap.put("sourceOfFunds.type", "CARD"); return keyValueMap; } /** * Constructs API request to initiate browser payment * * @param request needed to determine the current context * @param operation indicates API operation to target (PAY, AUTHORIZE, CAPTURE, etc) * @param source provider for the browser payment * @return ApiRequest * @throws MalformedURLException */ public static ApiRequest createBrowserPaymentsRequest(HttpServletRequest request, String operation, String source, Config config) throws Exception { try { ApiRequest req = new ApiRequest(); req.setApiOperation("INITIATE_BROWSER_PAYMENT"); req.setTransactionId(Utils.createUniqueId("trans-")); req.setOrderId(Utils.createUniqueId("order-")); req.setOrderAmount("50.00"); req.setOrderCurrency(config.getCurrency()); req.setOrderDescription("Wonderful product that you should buy!"); req.setBrowserPaymentOperation(operation); req.setSourceType(source); req.setReturnUrl(getCurrentContext(request) + "/browserPaymentReceipt?transactionId=" + req.getTransactionId() + "&orderId=" + req.getOrderId()); return req; } catch(Exception e) { logger.error("Unable to create browser payment request", e); throw e; } } /** * This method updates the Hosted Session with order info (description, amount, currency, ID) * * @param protocol REST or NVP * @param request contains info on what data the payload should include (order ID, amount, currency, etc) depending on the operation (PAY, AUTHORIZE, CAPTURE, etc) * @param config contains frequently used information like Merchant ID, API password, etc. * @param sessionId used to target a specific session * @throws Exception */ public static void updateSessionWithOrderInfo(ApiProtocol protocol, ApiRequest request, Config config, String sessionId) throws Exception { RESTApiClient connection = new RESTApiClient(); try { String updateSessionRequestUrl = ApiRequestService.getSessionRequestUrl(protocol, config, sessionId); ApiRequest updateSessionRequest = new ApiRequest(); updateSessionRequest.setOrderAmount(request.getOrderAmount()); updateSessionRequest.setOrderCurrency(request.getOrderCurrency()); updateSessionRequest.setOrderId(request.getOrderId()); String updateSessionPayload = ApiRequestService.buildJSONPayload(updateSessionRequest); connection.sendTransaction(updateSessionPayload, updateSessionRequestUrl, config); } catch (Exception e) { logger.error("Unable to update session", e); throw e; } } /** * This helper method gets the current context so that an appropriate return URL can be constructed * * @return current context string */ public static String getCurrentContext(HttpServletRequest request) throws MalformedURLException { try { URL url = new URL(request.getRequestURL().toString()); return url.getProtocol() + "://" + url.getAuthority(); } catch (MalformedURLException e) { logger.error("Unable to parse return URL", e); throw e; } } /** * Returns the base URL for the API call (either REST or NVP) * * @param gatewayHost * @param apiProtocol (REST or NVP) * @return base url or throw exception */ private static String getApiBaseURL(String gatewayHost, ApiProtocol apiProtocol) { switch (apiProtocol) { case REST: return gatewayHost + "/api/rest"; case NVP: return gatewayHost + "/api/nvp"; default: throwUnsupportedProtocolException(); } return null; } private static void throwUnsupportedProtocolException() { throw new IllegalArgumentException("Unsupported API protocol!"); } }
/* ==================================================================== * * Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved. * * ==================================================================== * */ package com.aof.webapp.action.party; import java.io.IOException; import java.sql.SQLException; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.util.MessageResources; import com.aof.component.domain.party.UserLogin; import com.aof.core.persistence.hibernate.Hibernate2Session; import com.aof.util.UtilDateTime; import com.aof.webapp.action.BaseAction; import net.sf.hibernate.*; /** * @author xxp * @version 2003-7-2 * */ public class ListCustUserLoginAction extends BaseAction { public ActionForward perform(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) { // Extract attributes we will need Logger log = Logger.getLogger(ListCustUserLoginAction.class.getName()); Locale locale = getLocale(request); MessageResources messages = getResources(); try{ List result = new ArrayList(); net.sf.hibernate.Session session = Hibernate2Session.currentSession(); Query q = session.createQuery("select ul from UserLogin as ul inner join ul.party as p inner join p.partyRoles as pr where pr.roleTypeId = 'CUSTOMER'"); //q.setMaxResults(length.intValue()); //q.setFirstResult(offset.intValue()); result = q.list(); //Criteria crit = session.createCriteria(UserLogin.class); //crit.setMaxResults(50); //result = crit.list(); request.setAttribute("userLogins",result); }catch(Exception e){ log.error(e.getMessage()); }finally{ try { Hibernate2Session.closeSession(); } catch (HibernateException e1) { log.error(e1.getMessage()); e1.printStackTrace(); } catch (SQLException e1) { log.error(e1.getMessage()); e1.printStackTrace(); } } return (mapping.findForward("success")); } }
package com.example.lamelameo.picturepuzzle; import android.content.ActivityNotFoundException; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.*; import java.io.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; public class PhotoCropping extends AppCompatActivity { private static final String TAG = "PhotoCropping"; private ImageView cropView; private String mCurrentPhotoPath = null; private ArrayList<String> savedPhotos = new ArrayList<>(); private int mGridRows = 4; private static final int REQUEST_IMAGE_CAPTURE = 1; private static final int REQUEST_GALLERY_SELECT = 0; private static final int REQUEST_PHOTO_CROP = 2; private float cropYBounds, cropXBounds, photoYBounds, photoXBounds; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photo_cropping); if (savedInstanceState != null) { mCurrentPhotoPath = (String)savedInstanceState.getCharSequence("photoPath"); savedPhotos = savedInstanceState.getStringArrayList("savedPhotos"); } // Buttons cropView = findViewById(R.id.cropView); Bitmap savedPhoto = BitmapFactory.decodeFile(mCurrentPhotoPath); cropView.setImageBitmap(savedPhoto); ImageView rotateRight = findViewById(R.id.rotateRight); ImageView rotateLeft = findViewById(R.id.rotateLeft); rotateRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rotatePhoto(90); } }); rotateLeft.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rotatePhoto(270); } }); // start game button onclicklistener Button startGame = findViewById(R.id.startGame); final Intent gameIntent = new Intent(this, PuzzleActivity.class); startGame.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mCurrentPhotoPath != null) { //TODO: 1.save photo only on game start as this means user wants photo? // 2.SEND newly saved photos to puzzle in case add function to move from Puzzle to Main directly gameIntent.putExtra("photoPath", mCurrentPhotoPath); gameIntent.putExtra("puzzleNum", -1); gameIntent.putExtra("numColumns", mGridRows); startActivity(gameIntent); } else { Toast photoToast = Toast.makeText(getApplicationContext(), "Take a photo with Camera or choose one from Gallery.", Toast.LENGTH_LONG); photoToast.show(); } } }); ImageView cameraButton = findViewById(R.id.takePhoto); Button galleryButton = findViewById(R.id.galleryButton); // send intent to take photo using camera on button click cameraButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchTakePictureIntent(); } }); // open gallery picker on gallery button click galleryButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent, REQUEST_GALLERY_SELECT); } }); //TODO: use to change overlay of photo previews... setForeground requires higher min SDK // final int[] gridOverlays = {R.drawable.gridoverlay3, R.drawable.gridoverlay4, // R.drawable.gridoverlay5, R.drawable.gridoverlay6}; // set gridsize based on the checked radio button, this value will be used as an intent extra when starting the game final RadioGroup setGrid = findViewById(R.id.radioGroup); setGrid.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { for (int x = 0; x<4; x++) { RadioButton radioButton = (RadioButton)group.getChildAt(x); if (radioButton.getId() == checkedId) { mGridRows = x + 3; // update grid size for use in load button listener in this context // Drawable gridOverlay = getResources().getDrawable(gridOverlays[x], null); // cropView.setForeground(gridOverlay); break; } } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putCharSequence("photoPath", mCurrentPhotoPath); outState.putStringArrayList("savedPhotos", savedPhotos); } @Override public void onBackPressed() { // super.onBackPressed(); // send list of paths of newly saved photos to main activity so the recycler can be updated. Intent intent = new Intent(); intent.putStringArrayListExtra("savedPhotos", savedPhotos); if (savedPhotos.size() != 0) { setResult(RESULT_OK, intent); } else { setResult(RESULT_CANCELED); } finish(); } //TODO: for use in self made cropping function private View.OnClickListener arrowClickListener = new View.OnClickListener() { @Override public void onClick(View v) { // float xCoord = cropView.getX(); // cropView.setX(xCoord + 100); // have to determine bounds or crop view can move outside of its constraints float yCoord = cropView.getY(); Log.i(TAG, "onClick cropY: "+yCoord); Log.i(TAG, "onClick photoY: "+ cropView.getY()); float height = cropView.getHeight(); cropYBounds = yCoord + height; //TODO: why is photo view y values giving 0 if ((cropYBounds + 10) < photoYBounds) { // only move crop outline if less than bounds of photo view cropView.setY(yCoord + 10); } else { Toast toast = Toast.makeText(getApplicationContext(), "Reached Bounds.", Toast.LENGTH_SHORT); toast.show(); } } }; /** * Create and show a Toast to display an exception message encountered by the app * @param exception the Exception the app has produced */ private void createErrorToast(Exception exception) { // gives the exceptions name and message (if any) String errorMessage = exception.toString(); String exceptionName = exception.getClass().toString(); Toast errorToast = Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT); errorToast.show(); } /** * Creates and invokes an Intent to take a photo using the camera */ private void dispatchTakePictureIntent() { Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Check there is a camera activity if (cameraIntent.resolveActivity(getPackageManager()) != null) { // Create a File to save the photo into File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // error when making file ex.printStackTrace(); } // if successful in creating File, save the photo into it if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(this, "com.example.android.fileprovider", photoFile); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE); } } } /** * Save the full sized image taken from camera to an app private directory that is deleted if app is removed * @return a File to store a photo taken with the camera intent * throws IOException error when making File */ private File createImageFile() throws IOException { // Locale locale = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); File image = File.createTempFile(imageFileName, ".jpg", storageDir); mCurrentPhotoPath = image.getAbsolutePath(); return image; } /** * Gets the image taken with the camera intent as a Bitmap to display in an ImageView {@link #cropView} as a preview * @param requestCode request code is 1 for our camera intent * @param resultCode RESULT_OK means we got a photo, RESULT_CANCELLED means no photo * @param data returns result data from the camera Intent we used, can use getExtras to obtain this */ @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // TODO: toast for each time photo is saved to app?? // for cancelled results, must remove created file if empty and clear the photo path to avoid errors if (resultCode == RESULT_CANCELED) { try { File photoFile = new File(mCurrentPhotoPath); if (photoFile.length() == 0) { boolean emptyFileDeleted = photoFile.delete(); } } catch (Exception e) { e.printStackTrace(); } // If a previously loaded photo is still present in the preview, retrieve its path and set mCurrentPhotoPath // else, clear mCurrentPhotoPath or will get errors trying to access null image in game activity if (cropView.getTag() != null) { mCurrentPhotoPath = (String)cropView.getTag(); } else { mCurrentPhotoPath = null; } } if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { // got a photo from camera intent // we already have the photo file path, which we will use to crop the photo and save in same file path File croppedPhotoFile = new File(mCurrentPhotoPath); // this is the URI to save the photo into after cropping - for camera photos it will overwrite // must use provider as we are sending photo saved in app folder to cropper activity outside app Uri croppedPhotoURI = FileProvider.getUriForFile(this, "com.example.android.fileprovider", croppedPhotoFile); dispatchCropIntent(croppedPhotoURI, croppedPhotoURI); } else { // process gallery image selection using image URI from gallery sending to gallery cropper, then saving // to app using data given back by intent in getData(), no permission problems if (requestCode == REQUEST_GALLERY_SELECT && resultCode == RESULT_OK && data != null) { // get the URI for the photo selected from gallery and send it to the android photo editor to crop Uri selectedPhotoURI = data.getData(); // Create a File in the app pictures directory to save the edited photo into File croppedPhotoFile = null; try { croppedPhotoFile = createImageFile(); } catch (IOException ex) { // error when making file ex.printStackTrace(); } // if successful in creating File, save a copy of the photo into it to then be edited if (croppedPhotoFile != null) { Uri croppedPhotoURI = Uri.fromFile(croppedPhotoFile); dispatchCropIntent(selectedPhotoURI, croppedPhotoURI); } } // get the cropped photo and send ImageView in app for a preview if (requestCode == REQUEST_PHOTO_CROP && resultCode == RESULT_OK && data != null) { // update num saved photos to send to main activity for updating the recycler view // savedPhotos.add(mCurrentPhotoPath); String photoPath = mCurrentPhotoPath; savedPhotos.add(photoPath); // output URI is saved in the intent data, see link below // https://android.googlesource.com/platform/packages/apps/Gallery2/+/c9f743a/src/com/android/gallery3d/app/CropImage.java Uri croppedPhotoUri = data.getData(); //TODO: is it appropriate to use photopath to save paths - if we add to arraylist then value changes ??? // BUG: by selecting gallery photo then cancel a new selection (clears photopath) took photo then start // game pressing back twice, got a blank image in recycler + the new photos, if select blank choice // and start, app crashes - note: gallery selected photo is deleted in directory while photo is present try { Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(croppedPhotoUri)); cropView.setImageBitmap(bitmap); cropView.setTag(mCurrentPhotoPath); } catch (FileNotFoundException e) { e.printStackTrace(); } } } } private void dispatchCropIntent(Uri data, Uri saveUri) { //TODO: need a backup if device cant run this crop intent try { // catch exception for devices without this crop activity Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(data, "image/*"); // must flag both read and write permissions or will get security error intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); intent.putExtra(MediaStore.EXTRA_OUTPUT, saveUri); // output file uri // output smaller photo //TODO: could be too large if user has poor quality camera or it will just scale it and look blurry? intent.putExtra("outputX", 1000); intent.putExtra("outputY", 1000); // set aspect ratio to 1:1 for a square image intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // intent.putExtra("return-data", true); intent.putExtra("scale", true); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); startActivityForResult(intent, REQUEST_PHOTO_CROP); } catch (ActivityNotFoundException e) { e.printStackTrace(); createErrorToast(e); } } /** * Rotates the given photo by 90 degrees given a direction of rotation and saves the new image over the old one * @param direction has value of either 90 or 270, determines if the photo rotates right or left, respectively */ private void rotatePhoto(float direction) { if (mCurrentPhotoPath != null) { // rotate image to correct orientation - default is landscape Matrix matrix = new Matrix(); matrix.postRotate(direction); Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath); Bitmap rotatedBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); // update preview and over write the old photo cropView.setImageBitmap(rotatedBmp); File rotatedPhoto = new File(mCurrentPhotoPath); try { FileOutputStream fileOutputStream = new FileOutputStream(rotatedPhoto); try { rotatedBmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream); } finally { fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
import java.util.*; public class RepublicDay { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n1=sc.nextInt(); int n2=sc.nextInt(); int p=0; for(int i=1;i<n1 && i<=n2;i++) { if(n1%i==0 && n2%i==0) p=i; } System.out.println(p); } }
package aplicacionmovil.com.aplicacion; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.Timer; import java.util.TimerTask; public class Juego extends AppCompatActivity { int numSec = 57; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_juego); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable(){ @Override public void run(){ TextView txtTime = (TextView) findViewById(R.id.txtTime); numSec = numSec + 1; int min = numSec/60; int sec = numSec%60; txtTime.setText(String.valueOf((min<10) ? "0"+min : min)+ ":" +String.valueOf((sec<10) ? "0"+sec : sec)); } }); } }, 0, 1000); } }
/** * Sencha GXT 3.0.1 - Sencha for GWT * Copyright(c) 2007-2012, Sencha, Inc. * licensing@sencha.com * * http://www.sencha.com/products/gxt/license/ */ package com.sencha.gxt.explorer.client.tabs; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.sencha.gxt.explorer.client.model.Example.Detail; import com.sencha.gxt.widget.core.client.TabItemConfig; import com.sencha.gxt.widget.core.client.TabPanel; import com.sencha.gxt.widget.core.client.button.TextButton; import com.sencha.gxt.widget.core.client.button.ToggleButton; import com.sencha.gxt.widget.core.client.event.SelectEvent; import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler; @Detail(name = "Advanced Tabs", category = "Tabs", icon = "advancedtabs") public class AdvancedTabsExample implements IsWidget, EntryPoint { private VerticalPanel vp; private TabPanel advanced; private int index = 0; public Widget asWidget() { if (vp == null) { vp = new VerticalPanel(); vp.setSpacing(10); HorizontalPanel hp = new HorizontalPanel(); hp.setSpacing(5); TextButton add = new TextButton("Add Tab"); add.addSelectHandler(new SelectHandler() { @Override public void onSelect(SelectEvent event) { addTab(); advanced.setActiveWidget(advanced.getWidget(advanced.getWidgetCount() - 1)); } }); hp.add(add); ToggleButton toggle = new ToggleButton("Enable Tab Context Menu"); hp.add(toggle); vp.add(hp); advanced = new TabPanel(); advanced.setPixelSize(600, 250); advanced.setAnimScroll(true); advanced.setTabScroll(true); advanced.setCloseContextMenu(true); toggle.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { advanced.setCloseContextMenu(event.getValue()); } }); toggle.setValue(true); while (index < 7) { addTab(); } advanced.setActiveWidget(advanced.getWidget(6)); vp.add(advanced); } return vp; } public void onModuleLoad() { RootPanel.get().add(asWidget()); } private void addTab() { Label item = new Label("Tab Body " + (index + 1)); item.addStyleName("pad-text"); advanced.add(item, new TabItemConfig("New Tab " + ++index, index != 1)); } }
package com.brainacademy.factory; public class ShapeFactory { public Shape createShape(ShapeType type) { switch (type) { case CIRCLE: return new Circle(); case RECTANGLE: return new Rectangle(); default: throw new RuntimeException("Unknown shape type"); } } }
package com.codingchili.instance.model.questing; import java.util.*; import com.codingchili.core.storage.Storable; /** * @author Robin Duda * <p> * A quest object as defined in configuration. */ public class Quest implements Storable { private List<QuestStage> stage = new ArrayList<>(); public String id; public String name; public String description; public List<QuestStage> getStage() { return stage; } public void setStage(List<QuestStage> stage) { this.stage = stage; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } @Override public String getId() { return id; } public String getName() { return name; } public QuestStage getFirstStage() { return stage.get(0); } public Optional<QuestStage> getStageById(String id) { return stage.stream() .filter(stage -> stage.getId().equals(id)) .findFirst(); } public boolean isFinalStage(String id) { return stage.get(stage.size() - 1).getId().equals(id); } public Optional<QuestStage> getNextStage(String stageId) { for (int i = 0; i < stage.size() - 1; i++) { if (stage.get(i).getId().equals(stageId)) { return Optional.of(this.stage.get(i + 1)); } } return Optional.empty(); } }
package com.itheima.day_01.homework.phone; public class PhoneDemo { /* ๅˆ†ๆžไปฅไธ‹้œ€ๆฑ‚๏ผŒๅนถ็”จไปฃ็ ๅฎž็Žฐ ่ฆๆฑ‚:ๅฎŒๆˆไปฃ็ (ๆŒ‰็…งๆ ‡ๅ‡†ๆ ผๅผๅ†™)๏ผŒ็„ถๅŽๅœจๆต‹่ฏ•็ฑปไธญๆต‹่ฏ•ใ€‚ 1.ๆ‰‹ๆœบ็ฑปPhone ๅฑžๆ€ง:ๅ“็‰Œbrand,ไปทๆ ผprice ๆ— ๅ‚ๆž„้€ ,ๆœ‰ๅ‚ๆž„้€  ่กŒไธบ:ๆ‰“็”ต่ฏcall,ๅ‘็ŸญไฟกsendMessage,็Žฉๆธธๆˆ,playGame 2.ๆต‹่ฏ•็ฑป ๅˆ›ๅปบPhone็ฑปๅฏน่ฑก,่ฐƒ็”จPhone็ฑปไธญ็š„ๆ–นๆณ• ๆ€่€ƒ:ๅ‡่ฎพๆ‰€ๆœ‰็š„ๆ‰‹ๆœบ้ƒฝๆœ‰ๅฑžๆ€งๅฑๅน•็š„ๅฐบๅฏธ(int size), ่€Œไธ”ๅ‡่ฎพๆ‰€ๆœ‰ๆ‰‹ๆœบ็š„ๅฑๅน•ๅฐบๅฏธไธบ6,ๅบ”่ฏฅๅฆ‚ไฝ•ๅฎž็Žฐ? */ public static void main(String[] args) { Phone.setSize(6); Phone p1 = new Phone("ๅŽไธบ", 3999); Phone p2 = new Phone("ๅฐ็ฑณ", 2999); Phone p3 = new Phone("้ญ…ๆ—", 1999); Phone p4 = new Phone("่‹นๆžœ", 5999); Phone p5 = new Phone("ไธ‰ๆ˜Ÿ", 5999); System.out.println(p1.getBrand() + " ," + p1.getPrice() + " ," + Phone.getSize()); p1.call(); p1.sendMessage(); p1.playGame(); System.out.println(p2.getBrand() + " ," + p2.getPrice() + " ," + Phone.getSize()); System.out.println(p3.getBrand() + " ," + p3.getPrice() + " ," + Phone.getSize()); System.out.println(p4.getBrand() + " ," + p4.getPrice() + " ," + Phone.getSize()); System.out.println(p5.getBrand() + " ," + p5.getPrice() + " ," + Phone.getSize()); } }
/* * Copyright (C) 2009, backport-android-bluetooth - http://code.google.com/p/backport-android-bluetooth/ * * 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 backport.android.bluetooth.samples; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface.OnDismissListener; import android.os.Handler; abstract class SamplesUtils { public static void indeterminate(Context context, Handler handler, String message, final Runnable runnable, OnDismissListener dismissListener) { try { indeterminateInternal(context, handler, message, runnable, dismissListener, true); } catch (Exception e) { ; // nop. } } public static void indeterminate(Context context, Handler handler, String message, final Runnable runnable, OnDismissListener dismissListener, boolean cancelable) { try { indeterminateInternal(context, handler, message, runnable, dismissListener, cancelable); } catch (Exception e) { ; // nop. } } /** * Progressใƒ€ใ‚คใ‚ขใƒญใ‚ฐใ‚’ๆง‹ๆˆใ™ใ‚‹. * * @param cancelListener * @return */ private static ProgressDialog createProgressDialog(Context context, String message) { ProgressDialog dialog = new ProgressDialog(context); dialog.setIndeterminate(false); dialog.setMessage(message); return dialog; } private static void indeterminateInternal(Context context, final Handler handler, String message, final Runnable runnable, OnDismissListener dismissListener, boolean cancelable) { final ProgressDialog dialog = createProgressDialog(context, message); dialog.setCancelable(cancelable); if (dismissListener != null) { dialog.setOnDismissListener(dismissListener); } dialog.show(); new Thread() { @Override public void run() { // ้–ขๆ•ฐใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆใคใใ‚‹ใฎใ‚ใ‚“ใฉใƒผใ ใฃใŸ. runnable.run(); handler.post(new Runnable() { public void run() { try { dialog.dismiss(); } catch (Exception e) { ; // nop. } } }); }; }.start(); } }
package com.epic.MIS; import com.epic.MIS.model.Bank; import com.epic.MIS.model.Employee; import com.epic.MIS.repository.BankRepository; import com.epic.MIS.repository.EmployeeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MisApplication implements CommandLineRunner { @Autowired private EmployeeRepository employeeRepository; @Autowired private BankRepository bankRepository; public static void main(String[] args) { SpringApplication.run(MisApplication.class, args); } @Override public void run(String... args) throws Exception { Employee e1 = new Employee(); e1.setId(1); e1.setFirstName("Akalankaa"); e1.setLastName("Gamage"); e1.setEmail("akala@gmail.com"); e1.setPassword("admin"); e1.setRole("employee"); employeeRepository.save(e1); Bank b1 = new Bank(); b1.setBankName("HNB"); b1.setAmount(100); bankRepository.save(b1); Bank b2 = new Bank(); b2.setBankName("BOC"); b2.setAmount(150); bankRepository.save(b2); Bank b3 = new Bank(); b3.setBankName("DFCC"); b3.setAmount(200); bankRepository.save(b3); } }
package cn.itcast.bookstore.search.dao; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import cn.itcast.bookstore.book.domain.Book; import cn.itcast.jdbc.TxQueryRunner; public class SearchDao { private QueryRunner qr = new TxQueryRunner(); /** * ๆœ็ดข * * @return List<Book> */ public List<Book> search(String condition) { try { String sql = "select * from book where bname LIKE ? and del = 0"; return qr.query(sql, new BeanListHandler<Book>(Book.class),condition); } catch (SQLException e) { throw new RuntimeException(e); } } }
package com.s1mple.service; import com.s1mple.entity.DormRepair; import com.s1mple.entity.PageInfo; import java.util.List; /** * @author s1mple * @create 2020/4/6-16:39 */ public interface DormRepairService { /** * ๅˆ†้กตๆŸฅ่ฏข * @param d_id * @param d_dormbuilding * @param pageIndex * @param pageSize * @return */ public PageInfo<DormRepair> findPageInfo(Integer d_id, String d_dormbuilding, Integer pageIndex, Integer pageSize); /** * ๆทปๅŠ ๅฎฟ่ˆไฟกๆฏ * @param dormrepair * @return */ public int addDormRepair(DormRepair dormrepair); /** * ๅˆ ้™คๅฎฟ่ˆไฟกๆฏ * @param r_id * @return */ public int deleteDormRepair(Integer r_id); /** * ไฟฎๆ”นๅฎฟ่ˆไฟกๆฏ * @param dormrepair * @return */ public int updateDormRepair(DormRepair dormrepair); public DormRepair findDormRepairById(Integer r_id); public List<DormRepair> getAll(); }
package com.utils; public class ZJ_NumberUtils { public static Integer getInteger(String str) { try { if (null == str || "".equals(str)) { return null; } else { return Double.valueOf(str).intValue(); } } catch (Exception e) { return null; } } public static Double getDouble(String str) { try { if (null == str || "".equals(str)) { return null; } else { return Double.valueOf(str); } } catch (Exception e) { return null; } } }
package cn.novelweb.tool.upload.fastdfs.exception; /** * <p>้žFastDFSๆœฌ่บซ็š„้”™่ฏฏ็ ๆŠ›ๅ‡บ็š„ๅผ‚ๅธธ๏ผŒsocket่ฟžไธไธŠๆ—ถๆŠ›ๅ‡บ็š„ๅผ‚ๅธธ</p> * <p>2020-02-03 16:18</p> * * @author LiZW **/ public class FastDfsConnectException extends FastDfsUnavailableException { public FastDfsConnectException(String message, Throwable t) { super(message, t); } }
package org.dbdoclet.tidbit.perspective.docbook.html; import javax.swing.JCheckBox; import org.dbdoclet.Identifier; import org.dbdoclet.jive.widget.GridPanel; import org.dbdoclet.tidbit.common.Constants; import org.dbdoclet.tidbit.perspective.panel.docbook.IndexPanel; import org.dbdoclet.tidbit.project.Project; import org.dbdoclet.tidbit.project.driver.AbstractDriver; public class HtmlIndexPanel extends IndexPanel{ private JCheckBox indexLinksToSection; private JCheckBox indexPreferTitleabbrev; public HtmlIndexPanel() { createGui(); } private static final long serialVersionUID = 1L; @Override protected void createGui() { super.createGui(); incrRow(); addComponent(createIndexPanel()); addHorizontalGlue(); addVerticalGlue(); } private GridPanel createIndexPanel() { GridPanel indexPanel = new GridPanel("HTML"); indexPanel.startSubPanel(); indexLinksToSection = jf.createCheckBox(new Identifier(Constants.PARAM_INDEX_LINKS_TO_SECTION), Constants.PARAM_INDEX_LINKS_TO_SECTION); indexPanel.addComponent(indexLinksToSection); indexPreferTitleabbrev = jf.createCheckBox(new Identifier(Constants.PARAM_INDEX_PREFER_TITLE_ABBREV), Constants.PARAM_INDEX_PREFER_TITLE_ABBREV); indexPanel.addComponent(indexPreferTitleabbrev); return indexPanel; } @Override public void syncView(Project project, AbstractDriver driver) { super.syncView(project, driver); indexLinksToSection.setSelected(driver.isParameterEnabled(Constants.PARAM_INDEX_LINKS_TO_SECTION, false)); indexPreferTitleabbrev.setSelected(driver.isParameterEnabled(Constants.PARAM_INDEX_PREFER_TITLE_ABBREV, false)); } @Override public void syncModel(Project project, AbstractDriver driver) { super.syncModel(project, driver); driver.setParameter(Constants.PARAM_INDEX_LINKS_TO_SECTION, indexLinksToSection.isSelected()); driver.setParameter(Constants.PARAM_INDEX_PREFER_TITLE_ABBREV, indexPreferTitleabbrev.isSelected()); } }
package com.javainuse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.persistence.Entity; import javax.persistence.Id; @Component @Entity //@Scope(value = "prototype") public class Employee { @Id private String id; private String name; public Employee() { this.name = name; } public Employee(String id,String name) { this.name = name; this.id=id; } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + '}'; } public String getId() { return id; } @Required public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } // // public Department getDepartment() { // return department; // } // // public void setDepartment(Department department) { // this.department = department; // } // // @Autowired // private Department department; }
package express.product.pt.cn.fishepress.callbacklistener; /** * httpUtils็š„ๅ›ž่ฐƒ็›‘ๅฌๆŽฅๅฃ */ public interface HttpCallBackListener { void onFinish(String result); void onError(Exception error); }
package com.grocery.codenicely.vegworld_new.home.provider; import com.grocery.codenicely.vegworld_new.helper.Urls; import com.grocery.codenicely.vegworld_new.home.OnHomeDataRequest; import com.grocery.codenicely.vegworld_new.home.api.HomeDetailsRequestInterface; import com.grocery.codenicely.vegworld_new.home.model.HomeData; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by Meghal on 6/19/2016. */ public class RetrofitHomeDetailsProvider implements HomeDetailsProvider { private Call<HomeData> homeDataCall; @Override public void requestHomeData(String access_token,String fcm, final OnHomeDataRequest onHomeDataRequest) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor) /* .connectTimeout(30,TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30,TimeUnit.SECONDS)*/ .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(Urls.BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); final HomeDetailsRequestInterface homeDetailsRequestInterface = retrofit.create(HomeDetailsRequestInterface.class); homeDataCall = homeDetailsRequestInterface.getHomeData(access_token,fcm); homeDataCall.enqueue(new Callback<HomeData>() { @Override public void onResponse(Call<HomeData> call, Response<HomeData> response) { onHomeDataRequest.onSuccess(response.body()); } @Override public void onFailure(Call<HomeData> call, Throwable t) { onHomeDataRequest.onFailure(); t.printStackTrace(); } }); } @Override public void onDestroy() { if(homeDataCall!=null){ homeDataCall.cancel(); } } }
package com.larryhsiao.nyx.core.tags; import com.silverhetch.clotho.Action; import com.silverhetch.clotho.Source; import java.sql.Connection; import java.sql.PreparedStatement; /** * Action to update a Tag. */ public class UpdateTag implements Action { private final Source<Connection> db; private final Tag tag; private final boolean increaseVer; public UpdateTag(Source<Connection> db, Tag tag) { this(db, tag, true); } public UpdateTag(Source<Connection> db, Tag tag, boolean increaseVer) { this.db = db; this.tag = tag; this.increaseVer = increaseVer; } @Override public void fire() { Connection conn = db.value(); try (PreparedStatement stmt = conn.prepareStatement( //language=H2 "UPDATE TAGS " + "SET TITLE=?1, VERSION = ?4, delete=?2 " + "WHERE ID=?3" )) { stmt.setString(1, tag.title()); stmt.setInt(2, tag.deleted() ? 1 : 0); stmt.setLong(3, tag.id()); stmt.setInt(4, increaseVer ? tag.version() + 1 : tag.version()); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } }
package edu.mum.sonet; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @Disabled @SpringBootTest class SonetApplicationTests { @Test void contextLoads() { } }
package com.csair.datatrs.common; /** * ๅค„็†ๅ™จๆŽฅๅฃ * Created by cloudoo on 2015/5/4. * ๆ˜ฏๅฆ่€ƒ่™‘ไฝฟ็”จ่ดฃไปป้“พๆจกๅผ * */ public interface Processor<T> { public T doit(); }
package web.command.impl; import classes.util.Resultado; import dominio.evento.IDominio; import web.command.AbsCommand; public class AlterarCommand extends AbsCommand { @Override public Resultado execute(IDominio entidade) { return fachada.alterar(entidade); } }
package com.memory.platform.core.springmvc; import javax.servlet.http.HttpServletRequest; import org.springframework.context.ApplicationContext; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.support.RequestContextUtils; /** * springmvcไธŽspring็š„้ƒฝๆœ‰ไธ€ไธชไธŠไธ‹ๆ–‡๏ผŒไป–ไปฌไน‹้—ดๆ˜ฏ็ˆถๅญๅ…ณ็ณปใ€‚ * springmvc็š„ไธŠไธ‹ๆ–‡ๅฏไปฅ่ฎฟ้—ฎspringไธŠไธ‹ๆ–‡็š„ๆ‰€ๆœ‰beanใ€‚ * ่€Œไฝœไธบ็ˆถไธŠไธ‹ๆ–‡็š„springๅˆ™ไธ่ƒฝ่ฎฟ้—ฎspringmvc็š„beanใ€‚ * Spring็š„ไธŠไธ‹ๆ–‡ๆ˜ฏ็”ฑโ€œorg.springframework.web.context.ContextLoaderListenerโ€่ดŸ่ดฃๅˆ›ๅปบ๏ผŒ * springmvc็š„ไธŠไธ‹ๆ–‡ๆ˜ฏ็”ฑโ€œorg.springframework.web.servlet.DispatcherServletโ€่ดŸ่ดฃๅˆ›ๅปบ๏ผŒ * ไธ”ๅฏไปฅๆœ‰ๅคšไธชDispatcherServlet * @author */ public class SpringMvcContextHolder { public SpringMvcContextHolder() { } /** * ๅ–ๅพ—SpringMVC็š„ApplicationContext */ public static ApplicationContext getApplicationContext() { HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); ApplicationContext applicationContext = RequestContextUtils.getWebApplicationContext(request); return applicationContext; } /** * ไปŽSpringMVC็š„ApplicationContextไธญๅ–ๅพ—Bean, ่‡ชๅŠจ่ฝฌๅž‹ไธบๆ‰€่ต‹ๅ€ผๅฏน่ฑก็š„็ฑปๅž‹. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { return (T) getApplicationContext().getBean(name); } /** * ไปŽSpringMVC็š„ApplicationContextไธญๅ–ๅพ—Bean, ่‡ชๅŠจ่ฝฌๅž‹ไธบๆ‰€่ต‹ๅ€ผๅฏน่ฑก็š„็ฑปๅž‹. */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { return (T) getApplicationContext().getBeansOfType(clazz); } }
package ru.malichenko.market; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") public class FullServerRunTest { // @Autowired // private TestRestTemplate restTemplate; // // @Test // @WithMockUser(username = "Bob", roles = "USER") // public void fullRestTest() { // // Spring page class ... // List<Genre> genres = restTemplate.getForObject("/api/v1/genres", List.class); // assertThat(genres).isNotNull(); // assertThat(genres).isNotEmpty(); // } }
package test.AbstractFactory.factory.inter; import test.AbstractFactory.button.inter.Button; import test.AbstractFactory.textField.inter.TextField; /** * ็•Œ้ข็šฎ่‚คๅทฅๅŽ‚ๆŽฅๅฃ๏ผšๆŠฝ่ฑกๅทฅๅŽ‚ * @author lho * */ public interface SkinFactory { public Button createButton(); public TextField createTextField(); }
package com.clickbus.placesmanager.services; import com.clickbus.placesmanager.dto.request.StateRequestModel; import com.clickbus.placesmanager.dto.response.StateResponseModel; import com.clickbus.placesmanager.entities.State; import com.clickbus.placesmanager.exception.ResourceNotFoundException; import com.clickbus.placesmanager.repository.StateRepository; import com.clickbus.placesmanager.utils.ModelMapperFactory; import lombok.AllArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @AllArgsConstructor @Service public class StateServiceImpl implements StateService { private StateRepository stateRepository; @Override public StateResponseModel createState(StateRequestModel stateRequestModel) { ModelMapper modelMapper = ModelMapperFactory.getInstance(); State createdState = modelMapper.map(stateRequestModel, State.class); return modelMapper.map(stateRepository.save(createdState), StateResponseModel.class); } @Override public List<StateResponseModel> getStates() { ModelMapper modelMapper = ModelMapperFactory.getInstance(); List<State> stateList = stateRepository.findAll(); return Optional.ofNullable(stateList) .filter(list -> !list.isEmpty()) .orElseThrow(ResourceNotFoundException::new) .stream() .map(state -> modelMapper.map(state, StateResponseModel.class)) .collect(Collectors.toList()); } }
package com.zhicai.byteera.activity.product.entity; import android.os.Parcel; import android.os.Parcelable; /** Created by bing on 2015/6/2. */ @SuppressWarnings("unused") public class ProductEntity implements Parcelable { private String productId; private String smallImage; //ๅคดๅƒ private String productTitle; //ๆ ‡้ข˜ private float productIncome; //ๆ”ถ็›Š๏ผŒๅ€ผไธบ 0.05 ๅฐฑๆ˜ฏ 5% private float product_income_in_limit; //ๆŠ•่ต„ๆœŸ้™ๅ†…็š„ๆ”ถ็›Š(ๆ”ถ็›Š*ๆœŸ้™/365) private int productCoin; //่ž่ต„้‡‘้ข private int productLimit; //ๆœŸ้™, ๅ€ผไธบ 5 ๅฐฑๆ˜ฏ 5ไธชๆœˆ private boolean productWatch; //ๆ˜ฏๅฆๅ…ณๆณจ๏ผŒๆ˜ฏ0ๅฐฑๆ˜ฏๆฒกๅ…ณๆณจ๏ผŒๅ…ถไป–็š„้ƒฝๆ˜ฏๅ…ณๆณจ private int serializedSize; private float progress; //ๆŠ•ๆ ‡่ฟ›ๅบฆ, 1ไธบๆปกๆ ‡, ๅฐไบŽ1ๆ—ถไธบๆœชๆปกๆ ‡ private String productUrl; //ไบงๅ“่ฏฆๆƒ…url private String companyName; //ๅนณๅฐๅ็งฐ public ProductEntity() { } protected ProductEntity(Parcel in) { productId = in.readString(); smallImage = in.readString(); productTitle = in.readString(); productIncome = in.readFloat(); product_income_in_limit = in.readFloat(); productCoin = in.readInt(); productLimit = in.readInt(); productWatch = in.readByte() != 0; serializedSize = in.readInt(); progress = in.readInt(); productUrl = in.readString(); companyName = in.readString(); } public static final Creator<ProductEntity> CREATOR = new Creator<ProductEntity>() { @Override public ProductEntity createFromParcel(Parcel in) { return new ProductEntity(in); } @Override public ProductEntity[] newArray(int size) { return new ProductEntity[size]; } }; public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public float getProduct_income_in_limit() { return product_income_in_limit; } public void setProduct_income_in_limit(float product_income_in_limit) { this.product_income_in_limit = product_income_in_limit; } public float getProgress() { return progress; } public void setProgress(float progress) { this.progress = progress; } public String getProductUrl() { return productUrl; } public void setProductUrl(String productUrl) { this.productUrl = productUrl; } public int getProductCoin() { return productCoin; } public void setProductCoin(int productCoin) { this.productCoin = productCoin; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public float getProductIncome() { return productIncome; } public void setProductIncome(float productIncome) { this.productIncome = productIncome; } public int getProductLimit() { return productLimit; } public void setProductLimit(int productLimit) { this.productLimit = productLimit; } public String getProductTitle() { return productTitle; } public void setProductTitle(String productTitle) { this.productTitle = productTitle; } public boolean isProductWatch() { return productWatch; } public void setProductWatch(boolean productWatch) { this.productWatch = productWatch; } public String getSmallImage() { return smallImage; } public void setSmallImage(String smallImage) { this.smallImage = smallImage; } public int getSerializedSize() { return serializedSize; } public void setSerializedSize(int serializedSize) { this.serializedSize = serializedSize; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(productId); dest.writeString(smallImage); dest.writeString(productTitle); dest.writeFloat(productIncome); dest.writeFloat(product_income_in_limit); dest.writeInt(productCoin); dest.writeInt(productLimit); dest.writeByte((byte) (productWatch ? 1 : 0)); dest.writeInt(serializedSize); dest.writeFloat(progress); dest.writeString(productUrl); dest.writeString(companyName); } @Override public String toString() { return "ProductEntity{" + "productId='" + productId + '\'' + ", smallImage='" + smallImage + '\'' + ", productTitle='" + productTitle + '\'' + ", productIncome=" + productIncome + ", product_income_in_limit=" + product_income_in_limit + ", productCoin=" + productCoin + ", productLimit=" + productLimit + ", productWatch=" + productWatch + ", serializedSize=" + serializedSize + ", progress=" + progress + ", productUrl=" + productUrl+ ", company_name=" + companyName+ '}'; } public ProductEntity(String productId, String smallImage, String productTitle, float productIncome, float product_income_in_limit,int productCoin, int productLimit, boolean productWatch,float progress,String productUrl,String companyName) { this.productId = productId; this.smallImage = smallImage; this.productTitle = productTitle; this.productIncome = productIncome; this.product_income_in_limit = product_income_in_limit; this.productCoin = productCoin; this.productLimit = productLimit; this.productWatch = productWatch; this.progress = progress; this.productUrl = productUrl; this.companyName = companyName; } }
package com.example.demo; import javax.persistence.*; @Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private String birthday; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name="passport_id") private Passport passport; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public Passport getPassport() { return passport; } public void setPassport(Passport passport) { this.passport = passport; } }
import org.apache.camel.CamelContext; import org.apache.camel.ProducerTemplate; import org.apache.camel.impl.DefaultProducerTemplate; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * User: i54327 * Date: 5/2/14 * Time: 12:54 PM */ public class Incubator { public static void main(String[] args) throws Exception{ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:META-INF/spring/camel-context.xml"); String[] parameters = new String[]{"HIGGINBOTHAMTEST", "234727646", "73 THIRD ST NW", "", "SLC", "UT", "84412", "REQUEST DOCUMENTATION TO SUPPORT THE SERVICES RENDERED. 8/14/08 DSL", "Humana", "H045", "0001", "0004", "0076", "0008", "0012", "WH2KT", "STPX", "WH2KT"}; CamelContext camelContext = applicationContext.getBean("webServiceCamelContext", CamelContext.class); camelContext.start(); ProducerTemplate producerTemplate = new DefaultProducerTemplate(camelContext); producerTemplate.start(); String response = producerTemplate.requestBody("cxf:bean:referralService", parameters, String.class); System.out.println("Response: " +response); Thread.sleep(60000); } }
package com.egame.app.uis; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import android.app.NotificationManager; import android.app.TabActivity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.test.PerformanceTestCase; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewTreeObserver.OnPreDrawListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TabHost; import android.widget.TabWidget; import com.egame.R; import com.egame.app.EgameApplication; import com.egame.app.receivers.CollectedGamesReceiver; import com.egame.app.receivers.EgameHomeReceiver; import com.egame.app.services.BackRunService; import com.egame.app.services.DBService; import com.egame.beans.PushMsg; import com.egame.config.Const; import com.egame.config.Urls; import com.egame.utils.common.L; import com.egame.utils.common.PreferenceUtil; import com.egame.utils.common.SourceUtils; import com.egame.utils.ui.BaseActivity; import com.egame.utils.ui.DialogUtil; import com.egame.utils.ui.EnterCommunity; import com.egame.utils.ui.UIUtils; import com.egame.utils.ui.Utils; import com.eshore.network.stat.NetStat; public class EgameHomeActivity extends TabActivity implements OnClickListener, BaseActivity { public static EgameHomeActivity INSTANCE; public static final String TAB_GAME = "game"; public static final String TAB_SEARCH = "search"; public static final String TAB_MANAGER = "manager"; public static final String TAB_COMMUNITY = "community"; public static final String TAB_MORE = "more"; private TabHost mTabHost; private View mGameView; private View mSearchView; private View mManagerView; private View mCommunityView; private View mMoreView; private View mDownloadIcon; // private View mMessageIcon; private ImageView downtip; private List<View> mViewList; private OnPreDrawListener mOnPreDrawListener; private EgameHomeReceiver mReceiver; private Timer timer; private String page = ""; private String exitTag = ""; private String homeExitTag; private SharedPreferences sharedPreferences = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); NetStat.onError(this); setContentView(R.layout.egame_home); INSTANCE = this; // initData(); sharedPreferences = getSharedPreferences(PreferenceUtil.SHARED_GAME, 0); exitTag = sharedPreferences.getString("exitTag", "game"); // homeExitTag = sharedPreferences.getString("homeexit", "normal"); initView(); setDownloadIcon(); initViewData(exitTag); initEvent(); sharedPreferences.edit().putBoolean("downexit", true).commit(); timer = new Timer(); timer.schedule(new RefreshTimeTask(), 0, 3000); EgameApplication.Instance().addActivity(this); } private void setDownloadIcon() { mDownloadIcon = findViewById(R.id.download_icon); int count = 0; DBService dbService = new DBService(this); dbService.open(); try { Cursor cursor = dbService.getNotInstalledGame(); count = cursor.getCount(); cursor.close(); } catch (Exception e) { e.printStackTrace(); } dbService.close(); mDownloadIcon.setVisibility(View.GONE); if (count > 0) { mDownloadIcon.setVisibility(View.VISIBLE); } } public void initData() { } public void initView() { mTabHost = getTabHost(); mGameView = findViewById(R.id.game); mSearchView = findViewById(R.id.search); mManagerView = findViewById(R.id.manager); mCommunityView = findViewById(R.id.community); downtip = (ImageView) findViewById(R.id.download_tip); mMoreView = (ImageButton) findViewById(R.id.more); // mMessageIcon = findViewById(R.id.message_icon); IntentFilter filter = new IntentFilter(); filter.addAction(Utils.RECEIVER_CHANGE_SEL_TAB); filter.addAction(Utils.RECEIVER_DOWNLOAD); filter.addAction(Utils.RECEIVER_MESSAGE); mReceiver = new EgameHomeReceiver(this); registerReceiver(mReceiver, filter); // ๅœๆญขๅŽๅฐService // stopService(new Intent(this, BackRunService.class)); } public void initViewData(String exitTag) { mViewList = new ArrayList<View>(); mViewList.add(mGameView); mViewList.add(mSearchView); mViewList.add(mManagerView); mViewList.add(mCommunityView); mViewList.add(mMoreView); /******************** modify for samsung 20130104 ****************/ if (exitTag.equals("game")) { mOnPreDrawListener = UIUtils.initButtonState(mGameView); } else if (exitTag.equals("search")) { mOnPreDrawListener = UIUtils.initButtonState(mSearchView); } else if (exitTag.equals("manager")) { mOnPreDrawListener = UIUtils.initButtonState(mManagerView); } else if (exitTag.equals("community")) { mOnPreDrawListener = UIUtils.initButtonState(mCommunityView); } else if (exitTag.equals("more")) { mOnPreDrawListener = UIUtils.initButtonState(mMoreView); } /******************************* end ***************************/ TabWidget tabWidget = mTabHost.getTabWidget(); for (int i = 0; i < tabWidget.getChildCount(); i++) { View view = tabWidget.getChildAt(i); view.setBackgroundColor(0); } Intent gameIntent = new Intent(); gameIntent.setClass(getApplicationContext(), GameHomeActivityGroup.class); final TabHost.TabSpec gameSpec = mTabHost.newTabSpec(TAB_GAME); gameSpec.setIndicator(""); gameSpec.setContent(gameIntent); mTabHost.addTab(gameSpec); Intent searchIntent = new Intent(); searchIntent.setClass(getApplicationContext(), SearchActivity.class); final TabHost.TabSpec searchSpec = mTabHost.newTabSpec(TAB_SEARCH); searchSpec.setIndicator(""); searchSpec.setContent(searchIntent); mTabHost.addTab(searchSpec); Intent managerIntent = new Intent(); managerIntent.setClass(getApplicationContext(), ManagerActivityGroup.class); final TabHost.TabSpec managerSpec = mTabHost.newTabSpec(TAB_MANAGER); managerSpec.setIndicator(""); managerSpec.setContent(managerIntent); mTabHost.addTab(managerSpec); Intent rankTopIntent = new Intent(); rankTopIntent.putExtra("isShowTitle", true); rankTopIntent.setClass(getApplicationContext(), GameRankActivity.class); final TabHost.TabSpec rankTopSpec = mTabHost.newTabSpec(TAB_COMMUNITY); rankTopSpec.setIndicator(""); rankTopSpec.setContent(rankTopIntent); mTabHost.addTab(rankTopSpec); Intent moreIntent = new Intent(); moreIntent.setClass(getApplicationContext(), MoreActivity.class); final TabHost.TabSpec moreSpec = mTabHost.newTabSpec(TAB_MORE); moreSpec.setIndicator(""); moreSpec.setContent(moreIntent); mTabHost.addTab(moreSpec); loadIntentData(getIntent()); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.cancelAll(); } private void loadIntentData(Intent intent) { int type = intent.getIntExtra("type", 0); String link = intent.getStringExtra("link"); if (type > 0) { System.out.println("link = " + link); System.out.println("type = " + type); switch (type) { case PushMsg.PUSH_GAME_UPGRADE: { // ๅˆฐ็ฎก็†๏ผŒๆธธๆˆๅ‡็บง็•Œ้ข setSelTab(TAB_MANAGER); // ๅ‘้€ๆถˆๆฏๅˆ‡ๆข้กตๅกๅˆฐๅ‡็บง็•Œ้ข sendBroadcast(new Intent(Utils.RECEIVER_UPGRADE)); } break; case PushMsg.PUSH_NEW_ACTIVITY: { enterCommunity("activity"); } break; case PushMsg.PUSH_NEW_GAME: { // ๅˆฐๆธธๆˆ่ฏฆๆƒ…็•Œ้ข try { Bundle bundle = GamesDetailActivity.makeIntentData( Integer.parseInt(link), SourceUtils.BACK_UP); Intent activityIntent = new Intent(this, GamesDetailActivity.class); activityIntent.putExtras(bundle); startActivity(activityIntent); } catch (Exception e) { } } break; case PushMsg.PUSH_MESSAGE: { enterCommunity("msg"); } break; case PushMsg.PUSH_SYSTEM: { if (!TextUtils.isEmpty(link)) { try { if (!link.startsWith("http://")) { link = "http://" + link; } if (link.indexOf("?") > 0) { link += "&" + Urls.getLogParams(this); } else { link += "?" + Urls.getLogParams(this); } Uri uri = Uri.parse(link); Intent it = new Intent(Intent.ACTION_VIEW); it.setData(uri); startActivity(it); } catch (Exception e) { e.printStackTrace(); } } } break; case PushMsg.SWITCH_SEARCH_LABEL: { // ๅˆ‡ๆขๅˆฐๆœ็ดข้กต้ข setSelTab(TAB_SEARCH); // ๅ‘้€ๆถˆๆฏ if (!TextUtils.isEmpty(link)) { Intent broadcast = new Intent(Utils.RECEIVER_SEARCH_KEY); broadcast.putExtra(Utils.KEY_SEARCH_KEY, link); broadcast.putExtra(Utils.KEY_SEARCH_TYPE, type); sendBroadcast(broadcast); } } break; case PushMsg.SWITCH_SEARCH_PROVIDER: { // ๅˆ‡ๆขๅˆฐๆœ็ดข้กต้ข setSelTab(TAB_SEARCH); // ๅ‘้€ๆถˆๆฏ if (!TextUtils.isEmpty(link)) { Intent broadcast = new Intent(Utils.RECEIVER_SEARCH_KEY); broadcast.putExtra(Utils.KEY_SEARCH_KEY, link); broadcast.putExtra(Utils.KEY_SEARCH_TYPE, type); sendBroadcast(broadcast); } } break; } } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); loadIntentData(intent); } public void initEvent() { mGameView.setOnClickListener(this); mSearchView.setOnClickListener(this); mManagerView.setOnClickListener(this); mCommunityView.setOnClickListener(this); mMoreView.setOnClickListener(this); downtip.setOnClickListener(this); } private final static int MENU_FEEDBACK = 1; private final static int MENU_SETTING = 2; private final static int MENU_ABOUT = 3; private final static int MENU_EXIT = 4; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_FEEDBACK: { Intent intent = new Intent(this, MyReplyActivity.class); startActivity(intent); } break; case MENU_SETTING: { Intent intent = new Intent(this, SystemSettingActivity.class); startActivity(intent); } break; case MENU_ABOUT: { Intent intent = new Intent(this, AboutActivity.class); startActivity(intent); } break; case MENU_EXIT: { DialogUtil.showExitDialog(this); } break; } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { // ๅŽปๆމmenuๆŒ‰้’ฎไธญ็š„ไฝฟ็”จๅ้ฆˆๅ’Œ็ณป็ปŸ่ฎพ็ฝฎ // menu.add(0, MENU_FEEDBACK, Menu.NONE, R.string.egame_menu_feedback); // menu.add(0, MENU_SETTING, Menu.NONE, R.string.egame_menu_setting); menu.add(0, MENU_ABOUT, Menu.NONE, R.string.egame_menu_about); menu.add(0, MENU_EXIT, Menu.NONE, R.string.egame_menu_exit); return super.onCreateOptionsMenu(menu); } @Override protected void onResume() { super.onResume(); NetStat.onResumePage(); } @Override protected void onPause() { super.onPause(); NetStat.onPausePage("EgameHomeActivity"); /******************** modify for samsung 20130104 ****************/ String exitActivity = this.getCurrentActivity().getLocalClassName() .toString(); String str = "game"; if (exitActivity.equals("app.uis.GameHomeActivityGroup")) { exitTag = "game"; } else if (exitActivity.equals("app.uis.GameRankActivity")) { exitTag = "community"; } else if (exitActivity.equals("app.uis.ManagerActivityGroup")) { exitTag = "manager"; } else if (exitActivity.equals("app.uis.SearchActivity")) { exitTag = "search"; } else if (exitActivity.equals("app.uis.MoreActivity")) { exitTag = "more"; } boolean flag = sharedPreferences.edit().putString("exitTag", exitTag) .commit(); /********************* end ************************************/ } @Override protected void onDestroy() { super.onDestroy(); NetStat.exit(); if (timer != null) { timer.cancel(); } PreferenceUtil.setBackRunCount(getApplicationContext(), 0); String str = sharedPreferences.getString("homeexit", "fail"); if (str.equals("normal")) { sharedPreferences.edit().putString("exitTag", "game").commit(); } else { sharedPreferences.edit().putString("exitTag", exitTag).commit(); } // sharedPreferences.edit().putString("homeexit", "fail").commit(); // ้ข„ๅˆถ็‰ˆๆœฌไธ้œ€่ฆๅŽๅฐ่ฟ่กŒ // startService(new Intent(this, BackRunService.class)); unregisterReceiver(mReceiver); EgameApplication application = (EgameApplication) getApplication(); application.initCache(); try { File file = new File(Const.NoSDCardDIRECTORY + "/temp.apk"); L.i(Const.NoSDCardDIRECTORY + "/temp.apk"); file.delete(); } catch (Exception e) { L.i("ๅ†…ๅญ˜ๆฒกๆœ‰ไธ‹่ฝฝๆ•ฐๆฎ"); } } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if (mTabHost.getCurrentTabTag().equals(TAB_SEARCH)) { return mTabHost.getCurrentView().dispatchKeyEvent(event); } else { DialogUtil.showExitDialog(this); return true; } } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT || event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) { return true; } return super.dispatchKeyEvent(event); } public void onClick(View v) { if (v == mGameView) { DialogUtil.closeSoft(this); setSelTab(TAB_GAME); } else if (v == mSearchView) { setSelTab(TAB_SEARCH); } else if (v == mManagerView) { DialogUtil.closeSoft(this); setSelTab(TAB_MANAGER); } else if (v == mCommunityView) { DialogUtil.closeSoft(this); setSelTab(TAB_COMMUNITY); } else if (v == mMoreView) { DialogUtil.closeSoft(this); setSelTab(TAB_MORE); } else if (v == downtip) { downtip.setVisibility(View.GONE); } } /** * ๅฎŒๆˆๆ–ฐๆ‰‹ไปปๅŠก่ฐƒ็”จ็š„ๆ–นๆณ• */ public void gotoGame() { setSelTab(TAB_GAME); } public void showDownloadIcon() { if (PreferenceUtil.isFristDown(this)) { downtip.setVisibility(View.VISIBLE); PreferenceUtil.setFristDown(this); } mDownloadIcon.setVisibility(View.VISIBLE); } public void showMessageIcon() { // ไธๆ˜พ็คบๆŽ’่กŒไธŠ็š„newๅ›พๆ ‡ // mMessageIcon.setVisibility(View.VISIBLE); } public void setSelTab(String tabName) { if (tabName.equals(TAB_GAME)) { mTabHost.setCurrentTabByTag(TAB_GAME); UIUtils.buttonStateChange(mViewList, mGameView, mOnPreDrawListener); GameHomeActivityGroup.INSTANCE.returnGameTab(); } else if (tabName.equals(TAB_SEARCH)) { mTabHost.setCurrentTabByTag(TAB_SEARCH); UIUtils.buttonStateChange(mViewList, mSearchView, mOnPreDrawListener); } else if (tabName.equals(TAB_MANAGER)) { mTabHost.setCurrentTabByTag(TAB_MANAGER); UIUtils.buttonStateChange(mViewList, mManagerView, mOnPreDrawListener); if (mDownloadIcon.getVisibility() == View.VISIBLE) { mDownloadIcon.setVisibility(View.GONE); sendBroadcast(new Intent(Utils.RECEIVER_DOWNTASK)); } } else if (tabName.equals(TAB_COMMUNITY)) { // if (mMessageIcon.getVisibility() == View.VISIBLE) { // mMessageIcon.setVisibility(View.GONE); // enterCommunity("msg"); // } else { // enterCommunity(""); // } mTabHost.setCurrentTabByTag(TAB_COMMUNITY); UIUtils.buttonStateChange(mViewList, mCommunityView, mOnPreDrawListener); } else if (tabName.equals(TAB_MORE)) { mTabHost.setCurrentTabByTag(TAB_MORE); UIUtils.buttonStateChange(mViewList, mMoreView, mOnPreDrawListener); } } class RefreshTimeTask extends TimerTask { @Override public void run() { // L.d("download", "send refresh"); Intent intent = new Intent(Const.ACTION_DOWNLOAD_STATE); intent.putExtra("msg", "refresh"); sendBroadcast(intent); } } /** * ่ฟ›ๅ…ฅ็คพๅŒบ็š„ๆต็จ‹ */ private void enterCommunity(String enterPage) { page = enterPage; EnterCommunity enterCommunity = new EnterCommunity( EgameHomeActivity.this, enterPage); enterCommunity.enter(); } private void enterCommunity() { EnterCommunity enterCommunity = new EnterCommunity( EgameHomeActivity.this, page); enterCommunity.enter(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == EnterCommunity.RCODE_ENTERCOMUNITY_LOGIN && resultCode == RESULT_OK) { enterCommunity(); } } @Override public void initViewData() { // TODO Auto-generated method stub } }
package com.driva.drivaapi.config; import io.swagger.v3.oas.models.security.SecurityScheme; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.ApiKey; import springfox.documentation.service.AuthorizationScope; import springfox.documentation.service.Contact; import springfox.documentation.service.SecurityReference; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger.web.DocExpansion; import springfox.documentation.swagger.web.ModelRendering; import springfox.documentation.swagger.web.OperationsSorter; import springfox.documentation.swagger.web.SecurityConfiguration; import springfox.documentation.swagger.web.SecurityConfigurationBuilder; import springfox.documentation.swagger.web.TagsSorter; import springfox.documentation.swagger.web.UiConfiguration; import springfox.documentation.swagger.web.UiConfigurationBuilder; import java.util.Collections; import java.util.List; import static com.driva.drivaapi.constant.SwaggerConstant.API_DESCRIPTION; import static com.driva.drivaapi.constant.SwaggerConstant.API_TITLE; import static com.driva.drivaapi.constant.SwaggerConstant.API_VERSION; import static com.driva.drivaapi.constant.SwaggerConstant.AUTHORIZATION_DESCRIPTION; import static com.driva.drivaapi.constant.SwaggerConstant.AUTHORIZATION_SCOPE; import static com.driva.drivaapi.constant.SwaggerConstant.CONTACT_EMAIL; import static com.driva.drivaapi.constant.SwaggerConstant.CONTACT_NAME; import static com.driva.drivaapi.constant.SwaggerConstant.CONTACT_URL; import static com.driva.drivaapi.constant.SwaggerConstant.LICENSE; import static com.driva.drivaapi.constant.SwaggerConstant.LICENSE_URL; import static com.driva.drivaapi.constant.SwaggerConstant.SECURE_PATH; import static com.driva.drivaapi.constant.SwaggerConstant.SECURITY_REFERENCE; import static com.driva.drivaapi.constant.SwaggerConstant.TERM_OF_SERVICE; import static java.util.Collections.singletonList; import static org.springframework.http.HttpHeaders.AUTHORIZATION; import static springfox.documentation.spi.DocumentationType.SWAGGER_2; @Configuration public class SwaggerConfig { @Bean public Docket apiDocket() { return new Docket(SWAGGER_2).apiInfo(apiInfo()) .forCodeGeneration(true) .securityContexts(singletonList(securityContext())) .securitySchemes(singletonList(apiKey())) .select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) .paths(PathSelectors.regex(SECURE_PATH)) .build(); } private ApiInfo apiInfo() { return new ApiInfo(API_TITLE, API_DESCRIPTION, API_VERSION, TERM_OF_SERVICE, contact(), LICENSE, LICENSE_URL, Collections.emptyList()); } private Contact contact() { return new Contact(CONTACT_NAME, CONTACT_URL, CONTACT_EMAIL); } private ApiKey apiKey() { return new ApiKey(SECURITY_REFERENCE, AUTHORIZATION, SecurityScheme.In.HEADER.name()); } private SecurityContext securityContext() { return SecurityContext.builder().securityReferences(securityReference()).build(); } private List<SecurityReference> securityReference() { AuthorizationScope[] authorizationScope = {new AuthorizationScope(AUTHORIZATION_SCOPE, AUTHORIZATION_DESCRIPTION)}; return singletonList(new SecurityReference(SECURITY_REFERENCE, authorizationScope)); } @Bean SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() .clientId("test-app-client-id") .clientSecret("test-app-client-secret") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(true) .enableCsrfSupport(false) .build(); } @Bean UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() .deepLinking(true) .displayOperationId(false) .defaultModelsExpandDepth(1) .defaultModelRendering(ModelRendering.EXAMPLE) .displayRequestDuration(true) .docExpansion(DocExpansion.LIST) .filter(false) .maxDisplayedTags(null) .operationsSorter(OperationsSorter.ALPHA) .showExtensions(false) .showCommonExtensions(true) .tagsSorter(TagsSorter.ALPHA) .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) .validatorUrl(null) .build(); } }
package twice.pbdtest; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.ImageView; import static android.content.Context.SENSOR_SERVICE; //Our class extending fragment public class Tab1 extends Fragment implements SensorEventListener { private ImageView image; private float currentDegree = 0f; private SensorManager mSensorManager; private Sensor sensor_acc; private Sensor sensor_mag; SharedPreferences sharedpreferences; public static final String MyPREFERENCES = "MyPrefs" ; //Overriden method onCreateView public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //Returning the layout file after inflating //Change R.layout.tab1 in you classes View view = inflater.inflate(R.layout.tab1, container, false); image = (ImageView) view.findViewById(R.id.imgCompass); mSensorManager = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE); sensor_acc = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensor_mag = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); return view; } float[] mGravity; float[] mGeomagnetic; public void onSensorChanged(SensorEvent event) { float degree; if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) mGravity = event.values; if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) mGeomagnetic = event.values; if (mGravity != null && mGeomagnetic != null) { float R[] = new float[9]; float I[] = new float[9]; boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic); if (success) { float orientation[] = new float[3]; SensorManager.getOrientation(R, orientation); float azimuthInRadians = orientation[0]; // orientation contains: azimut, pitch and roll degree = (float)(Math.toDegrees(azimuthInRadians)+360)%360; System.out.println(degree); RotateAnimation ra = new RotateAnimation( currentDegree, -degree, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f); ra.setDuration(210); ra.setFillAfter(true); image.startAnimation(ra); currentDegree = -degree; } } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } @Override public void onResume() { super.onResume(); mSensorManager.registerListener(this, sensor_acc, SensorManager.SENSOR_DELAY_NORMAL); mSensorManager.registerListener(this, sensor_mag, SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onPause() { super.onPause(); mSensorManager.unregisterListener(this); } }
public class SantaClaus { private final int NumberOfReindeers = 2; public final int NumberOfLaps = 5; private int reindeersHungry = NumberOfReindeers; private boolean raceStarted = false; private boolean raceOver = false; private int notYetReadyForGoingHome = NumberOfReindeers; protected Reindeer theReindeers[]; public SantaClaus() { theReindeers = new Reindeer[NumberOfReindeers]; for (int i = 0; i < NumberOfReindeers; ++i) { theReindeers[i] = new Reindeer(this, "Reindeer Rudolf Rednose #" + i); } } public void preChristmasReindeerRace() { feedAllReindeers(); waitForFeedingDone(); startRacing(); waitForFinishing(); waitForGoingHome(); letReindeerIntoStable(); } protected void feedAllReindeers() { System.out.println("Starting Feeding..."); for (int i = 0; i < NumberOfReindeers; ++i) { theReindeers[i].start(); } } protected void waitForFeedingDone() { System.out.println("Reindeer Race starts soon..."); synchronized (this) { try { while (reindeersHungry > 0) { wait(); } } catch (InterruptedException e) { } } } protected synchronized void startRacing() { System.out.println("HO HO HO"); raceStarted = true; notifyAll(); } protected synchronized void waitForFinishing() { try { while (!raceOver) { wait(); } } catch (InterruptedException e) { } } public synchronized void waitForGoingHome() { try { while (notYetReadyForGoingHome > 0) wait(); } catch (InterruptedException e) { } } protected void letReindeerIntoStable() { // hier wartet Santa Claus bis alle Rentiere da // und nicht eine Aktion wie im Text beschrieben for (int i = 0; i < NumberOfReindeers; ++i) { try { theReindeers[i].join(); } catch (InterruptedException e) { } } System.out.println("All reindeers are in the stable"); } public synchronized void readyForStart() { reindeersHungry--; if (reindeersHungry <= 0) notifyAll(); } public synchronized void waitForStart() { try { while (!raceStarted) wait(); } catch (InterruptedException e) { } } public synchronized boolean raceIsOver() { return raceOver; } public synchronized void passFinishLine() { raceOver = true; notYetReadyForGoingHome--; notifyAll(); } public int getNumberOfLaps() { return NumberOfLaps; } }
package com.corycharlton.bittrexapi.model; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") public class Ticker { @SerializedName("Ask") private double _ask; @SerializedName("Bid") private double _bid; @SerializedName("Last") private double _last; private Ticker() {} // Cannot be instantiated public double ask() { return _ask; } public double bid() { return _bid; } public double last() { return _last; } }
package com.lesports.albatross.activity.mine; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import com.google.gson.reflect.TypeToken; import com.handmark.pulltorefresh.library.ILoadingLayout; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.lesports.albatross.Constants; import com.lesports.albatross.R; import com.lesports.albatross.activity.SwipeBaseActivity; import com.lesports.albatross.adapter.mine.MineDynamicAdapter_bak; import com.lesports.albatross.custom.CircleImageView; import com.lesports.albatross.entity.HttpRespObjectEntity; import com.lesports.albatross.entity.user.DynamicPageEntity; import com.lesports.albatross.json.GsonHelper; import com.lesports.albatross.utils.DialogUtils; import com.lesports.albatross.utils.SpFileUtil; import com.lesports.albatross.utils.StringUtils; import org.json.JSONObject; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; /** * ๆˆ‘็š„ๅŠจๆ€ * Created by zhouchenbin on 16/5/30. */ public class MineDynamicActivity_bak extends SwipeBaseActivity implements OnClickListener, OnRefreshListener2 { private String TAG = getClass().getName(); private TextView nick_name_id; private CircleImageView header_image_id; private Context context; private PullToRefreshListView pullToRefreshListView; private int page = 0, size = 10, defaultPage = 0; //่ฏทๆฑ‚้กต้ข๏ผŒ่ฏทๆฑ‚ๅฎน้‡,้ป˜่ฎค้กต private String userId; //็”จๆˆทid private MineDynamicAdapter_bak mineDynamicAdapterBak; //ๆˆ‘็š„ๅŠจๆ€ private Dialog dialog; private boolean isMore = false; public final static String USER_ID = "userId"; @Override public void resourcesInit(Bundle savedInstanceState) { context = MineDynamicActivity_bak.this; if ((userId = getIntent().getStringExtra(USER_ID)) == null) { userId = SpFileUtil.getString(context, SpFileUtil.USER_PARAMS_DATA, SpFileUtil.KEY_USERID, ""); } mineDynamicAdapterBak = new MineDynamicAdapter_bak(context); } @Override public int viewBindLayout() { return R.layout.mine_dynamic_activity_layout; } @Override public void viewBindId() { header_image_id = (CircleImageView) findViewById(R.id.header_image_id); nick_name_id = (TextView) findViewById(R.id.nick_name_id); pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.mine_dynamic_list_layout); } @Override public void viewInit(LayoutInflater inflater) { setMiddleText(getString(R.string.mine_dynamic_title)); dialog = DialogUtils.createLodingDialog(context); dialog.show(); setSwipeAnyWhere(true); initIndicator(); pullToRefreshListView.setOnRefreshListener(this); pullToRefreshListView.setPullToRefreshOverScrollEnabled(false); if (SpFileUtil.getBoolean(context, SpFileUtil.USER_PARAMS_DATA, SpFileUtil.KEY_LOGIN, false)) { nick_name_id.setText(SpFileUtil.getString(context, SpFileUtil.USER_PARAMS_DATA, SpFileUtil.KEY_NICKNAME, "")); x.image().bind(header_image_id, SpFileUtil.getString(context, SpFileUtil.USER_PARAMS_DATA, SpFileUtil.KEY_HEADER_URL, "")); } pullToRefreshListView.setAdapter(mineDynamicAdapterBak); getDynamicData(); } /** * ่ฎพ็ฝฎไธ‹ๆ‹‰ๅˆทๆ–ฐๆ็คบ */ private void initIndicator() { pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH); ILoadingLayout startLabels = pullToRefreshListView .getLoadingLayoutProxy(true, false); startLabels.setPullLabel("ไธ‹ๆ‹‰ๅˆทๆ–ฐ");// ๅˆšไธ‹ๆ‹‰ๆ—ถ๏ผŒๆ˜พ็คบ็š„ๆ็คบ startLabels.setRefreshingLabel("ๆญฃๅœจๅˆทๆ–ฐ...");// ๅˆทๆ–ฐๆ—ถ startLabels.setReleaseLabel("้‡Šๆ”พๆ›ดๆ–ฐ");// ไธ‹ๆฅ่พพๅˆฐไธ€ๅฎš่ท็ฆปๆ—ถ๏ผŒๆ˜พ็คบ็š„ๆ็คบ ILoadingLayout endLabels = pullToRefreshListView.getLoadingLayoutProxy( false, true); endLabels.setPullLabel("ไธŠๆ‹‰ๅŠ ่ฝฝ"); endLabels.setRefreshingLabel("ๆญฃๅœจๅˆทๆ–ฐ...");// ๅˆทๆ–ฐๆ—ถ endLabels.setReleaseLabel("้‡Šๆ”พๅŠ ่ฝฝ");// ไธ‹ๆฅ่พพๅˆฐไธ€ๅฎš่ท็ฆปๆ—ถ๏ผŒๆ˜พ็คบ็š„ๆ็คบ } @Override public void viewBindListener() { header_image_id.setOnClickListener(this); nick_name_id.setOnClickListener(this); pullToRefreshListView.setOnRefreshListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.nick_name_id: break; case R.id.header_image_id: break; default: break; } } //่Žทๅพ—ๅŠจๆ€ๆ•ฐๆฎ private void getDynamicData() { final RequestParams params = new RequestParams(Constants.MINE_DYNAMIC_URL); params.setAsJsonContent(true); params.setCacheMaxAge(1000 * 300); params.addParameter("userid", userId); params.addParameter("page", page); params.addParameter("size", size); x.http().get(params, new Callback.CacheCallback<String>() { @Override public void onSuccess(String result) { page++; Log.i(TAG, getString(R.string.base_request_success_log)); showDynamicData(result); } @Override public void onError(Throwable ex, boolean isOnCallback) { Log.i(TAG, getString(R.string.base_request_fail_log)); } @Override public void onCancelled(CancelledException cex) { Log.i(TAG, getString(R.string.base_request_cancel_log)); } @Override public void onFinished() { Log.i(TAG, getString(R.string.base_request_finish_log)); dialog.dismiss(); } @Override public boolean onCache(String result) { Log.i(TAG, getString(R.string.base_request_cache_log)); return false; } }); } //ๆ˜พ็คบๆ•ฐๆฎ private void showDynamicData(String data) { if (StringUtils.isNotEmpty(data)) { try { JSONObject obj = new JSONObject(data); int status = obj.getInt("code"); if (status == Constants.STATUS_SUCCESS) { // ๆญฃ็กฎ HttpRespObjectEntity<DynamicPageEntity> httpRespObjectEntity = GsonHelper.fromJson(data, new TypeToken<HttpRespObjectEntity<DynamicPageEntity>>() { }.getType()); if (isMore) mineDynamicAdapterBak.add(httpRespObjectEntity.getData().getContent()); else mineDynamicAdapterBak.update(httpRespObjectEntity.getData().getContent()); Log.i(TAG, "ๆ•ฐๆฎ่งฃๆžๆˆๅŠŸ"); } } catch (Exception e) { e.printStackTrace(); } finally { pullToRefreshListView.postDelayed(new Runnable() { @Override public void run() { pullToRefreshListView.onRefreshComplete(); } }, 500); } } } //ไธ‹ๆ‹‰ๅˆทๆ–ฐ @Override public void onPullDownToRefresh(PullToRefreshBase refreshView) { String label = DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL); label = "ไธŠๆฌกๆ›ดๆ–ฐไบŽ" + label; refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); page = 0; isMore = false; getDynamicData(); } //ไธŠๆ‹‰ @Override public void onPullUpToRefresh(PullToRefreshBase refreshView) { isMore = true; page++; getDynamicData(); } }
package org.dreamer.expression.calc; /** * TypedToken class keeps token type, depending on token value. * It allows us to compare enum values instead of strings. */ public class TypedToken { public enum Type { VALUE, OPEN_BRACKET, CLOSE_BRACKET, OP_ADD, OP_SUB, OP_MUL, OP_DIV, FUNC, CONST } public TypedToken(Token token, Type type) { _type = type; _token = token; } public Type getType() { return _type; } public String getValue() { return _token.getValue(); } public int getPosition() { return _token.getPosition(); } public Token getTokenValue() { return _token; } public boolean isOperator() { return _type == Type.OP_ADD || _type == Type.OP_SUB || _type == Type.OP_MUL || _type == Type.OP_DIV; } // TODO: Move priority comparison to a higher level. public int comparePriority(TypedToken other) { if (isOperator() && other.isOperator()) { return getPriority(_type) - getPriority(other.getType()); } return 1; } private int getPriority(Type type) { if (type == Type.OP_MUL || type == Type.OP_DIV) return 2; return 1; } public boolean isFunction() { return _type == Type.FUNC; } public boolean isValue() { return _type == Type.VALUE || _type == Type.CONST; } private Type _type; Token _token; }
package com.xiaoniu.NetReptile; import java.io.IOException; import java.net.URL; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.junit.Before; import org.junit.Test; public class TestJsoup { static Document doc =null; public static void main(String[] args) { } @Test public void getContent(){ //<span class="list" height="18">็ฎ€</span> Elements select = doc.select("#resultList .el .t2 a"); for (Element element : select) { element.parent(); element.children(); element.nextSibling(); element.siblingElements(); element.previousElementSibling(); System.out.println(element.text()); System.out.println(element.attr("href")); System.out.println("**************************"); } } @Test public void getDocumentCh() throws Exception{ Element elementById = doc.getElementById("languagelist"); Elements elementsByClass = doc.getElementsByClass("el"); Elements elementsByTag = doc.getElementsByTag("body"); Element element = elementsByTag.get(0); Elements select = doc.select("body #languagelist .tle"); } @Before public void getDocument() throws IOException{ String jburl = "https://search.51job.com/list/010000,000000,0000,00,9,99,%25E5%25A4%25A7%25E6%2595%25B0%25E6%258D%25AE%25E5%25BC%2580%25E5%258F%2591%25E5%25B7%25A5%25E7%25A8%258B%25E5%25B8%2588,2,1.html?lang=c&amp;stype=&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;providesalary=99&amp;lonlat=0%2C0&amp;radius=-1&amp;ord_field=0&amp;confirmdate=9&amp;fromType=&amp;dibiaoid=0&amp;address=&amp;line=&amp;specialarea=00&amp;from=&amp;welfare="; URL url = new URL(jburl); doc = Jsoup.parse(url, 4000); System.out.println(doc); } }
package gromcode.main.lesson19.homework19_1; public class Controller { public File put(Storage storage, File file) throws Exception{ storage.checkPutFile(file); storage.addFile(file); return file; } public void delete(Storage storage, File file) throws Exception{ if(storage.getFileById(file.getId()) == null) throw new Exception("file not found. file id:"+file.getId()+" storage id:"+storage.getId()); storage.deleteFile(file); } public void transferAll(Storage storageFrom, Storage storageTo) throws Exception{ storageTo.checkTransfer(storageFrom.getFiles()); for (File file : storageFrom.getFiles()) if (file != null) { storageTo.addFile(file); delete(storageFrom, file); } } public void transferFile(Storage storageFrom, Storage storageTo, long id) throws Exception{ storageTo.checkPutFile(storageFrom.getFileById(id)); storageTo.addFile(storageFrom.getFileById(id)); storageFrom.deleteFile(storageFrom.getFileById(id)); } }
package threadtest; public class ThreadTestJoin { public static void main( String[] args ) throws InterruptedException { MyThread2 t = new MyThread2(); t.start(); t.interrupt();; System.out.println("Main thread end"); } } class MyThread extends Thread { public void run() { try{ for( int i = 0; i<10; i++ ) { System.out.println("I am lazy thread."); Thread.sleep(5000); } }catch( InterruptedException e) { System.out.println("I am interrupted"); } } } class MyThread2 extends Thread { public void run() { try{ for( int i = 1; i<=20000; i++ ) { System.out.println("I am lazy thread."+i); } System.out.println("I m going to sleep"); Thread.sleep(5000); }catch( InterruptedException e) { System.out.println("I am interrupted"); } } }
package com.yutianhao.movie.domain.query; /** * * @ClassName: MovieQuery * @Description: Movie่ง†ๅ›พ็ฑป๏ผŒVO็ฑป * @author thyu * @date 2020ๅนด3ๆœˆ23ๆ—ฅ * */ public class MovieQuery { private String name; private String director; private Integer legend; private String startTime; private String endTime; private Double lowerPrice; private Double upperPrice; private Integer lowerLength; private Integer upperLength; public MovieQuery() { super(); } public MovieQuery(String name, String director, Integer legend, String startTime, String endTime, Double lowerPrice, Double upperPrice, Integer lowerLength, Integer upperLength) { super(); this.name = name; this.director = director; this.legend = legend; this.startTime = startTime; this.endTime = endTime; this.lowerPrice = lowerPrice; this.upperPrice = upperPrice; this.lowerLength = lowerLength; this.upperLength = upperLength; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDirector() { return director; } public void setDirector(String director) { this.director = director; } public Integer getLegend() { return legend; } public void setLegend(Integer legend) { this.legend = legend; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public Double getLowerPrice() { return lowerPrice; } public void setLowerPrice(Double lowerPrice) { this.lowerPrice = lowerPrice; } public Double getUpperPrice() { return upperPrice; } public void setUpperPrice(Double upperPrice) { this.upperPrice = upperPrice; } public Integer getLowerLength() { return lowerLength; } public void setLowerLength(Integer lowerLength) { this.lowerLength = lowerLength; } public Integer getUpperLength() { return upperLength; } public void setUpperLength(Integer upperLength) { this.upperLength = upperLength; } @Override public String toString() { return "MovieQuery [name=" + name + ", director=" + director + ", legend=" + legend + ", startTime=" + startTime + ", endTime=" + endTime + ", lowerPrice=" + lowerPrice + ", upperPrice=" + upperPrice + ", lowerLength=" + lowerLength + ", upperLength=" + upperLength + "]"; } }
/** * Copyright (C) 2008 Atlassian * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.atlassian.theplugin.jira.cache; import com.atlassian.connector.cfg.ProjectCfgManager; import com.atlassian.connector.commons.jira.JiraUserNotFoundException; import com.atlassian.connector.commons.jira.beans.JIRAUserBean; import com.atlassian.connector.commons.jira.rss.JIRAException; import com.atlassian.theplugin.commons.cfg.ServerId; import com.atlassian.theplugin.commons.jira.IntelliJJiraServerFacade; import com.atlassian.theplugin.commons.jira.JiraServerData; import com.atlassian.theplugin.commons.jira.JiraServerFacade; import com.atlassian.theplugin.commons.jira.api.JiraIssueAdapter; import com.atlassian.theplugin.commons.remoteapi.jira.JiraCaptchaRequiredException; import com.atlassian.theplugin.configuration.IssueRecentlyOpenBean; import com.atlassian.theplugin.configuration.JiraWorkspaceConfiguration; import com.atlassian.theplugin.util.PluginUtil; import java.util.*; /** * User: pmaruszak */ public class RecentlyOpenIssuesCache { // ordered map private final LinkedHashMap<IssueRecentlyOpenBean, JiraIssueAdapter> items = new LinkedHashMap<IssueRecentlyOpenBean, JiraIssueAdapter>(); private final ProjectCfgManager projectCfgManager; private JiraWorkspaceConfiguration jiraWorkspaceConf; public RecentlyOpenIssuesCache(final ProjectCfgManager cfgManager, final JiraWorkspaceConfiguration jiraConf) { this.projectCfgManager = cfgManager; this.jiraWorkspaceConf = jiraConf; } /** * Loads recenlty viewed issues from the server into cache. * BLOCKING METHOD. SHOULD BE CALLED IN THE BACKGROUND. * This method should be called only if you want to init or refresh the cache. * * @return local (cached) list of recently viewed issues */ public List<JiraIssueAdapter> loadRecenltyOpenIssues() { if (jiraWorkspaceConf != null) { items.clear(); final List<IssueRecentlyOpenBean> recentlyOpen = new LinkedList<IssueRecentlyOpenBean>(jiraWorkspaceConf.getRecentlyOpenIssuess()); // we put elements in the map in reverse order (most fresh element is at the end) // this is because map.put (used when adding new element) place alement at the end // I don't know the way to put element at the top of the ordered map. Collections.reverse(recentlyOpen); for (IssueRecentlyOpenBean i : recentlyOpen) { try { JiraIssueAdapter loadedIssue = loadJiraIssue(i); if (loadedIssue != null) { items.put(i, loadedIssue); } } catch (JIRAException e) { if (e instanceof JiraCaptchaRequiredException) { PluginUtil.getLogger().warn("Due to multiple failed login attempts," + " you have been temporarily banned from using the remote API." + " To re-enable the remote API please log into your server via the web interface.\n" + e.getMessage()); } else { PluginUtil.getLogger().warn(e.getMessage()); } } } } return reverseList(new LinkedList<JiraIssueAdapter>(items.values())); } /** * It is non blocking method and can be called in the UI thread * * @return list of recenlty viewed issues from the local cache */ public List<JiraIssueAdapter> getLoadedRecenltyOpenIssues() { return reverseList(new LinkedList<JiraIssueAdapter>(items.values())); } /** * Returns recently viewed issue according to provided parameters * Non blocking method. Can be called in the UI thread. * * @param issueKey issue key to look for * @param serverId server to search * @param issueUrl * @return recently viewed issue from the local cache or null in case issue was not found in the cache */ public JiraIssueAdapter getLoadedRecenltyOpenIssue(final String issueKey, final ServerId serverId, String issueUrl) { return items.get(new IssueRecentlyOpenBean(serverId, issueKey, issueUrl)); } /** * Add issue to cache and configuration. * This is the only method user has to call to store recently viewed issue. * * @param issue Issue to add */ public void addIssue(final JiraIssueAdapter issue) { final IssueRecentlyOpenBean recenltyOpenIssueBean = new IssueRecentlyOpenBean(issue.getJiraServerData().getServerId(), issue.getKey(), issue.getIssueUrl()); items.remove(recenltyOpenIssueBean); items.put(recenltyOpenIssueBean, issue); // reduce map size (remove items from the beginning of the list - the eldest ones) while (items.size() > JiraWorkspaceConfiguration.RECENLTY_OPEN_ISSUES_LIMIT) { Iterator iter = items.values().iterator(); if (iter.hasNext()) { iter.next(); iter.remove(); } } if (jiraWorkspaceConf != null) { jiraWorkspaceConf.addRecentlyOpenIssue(issue); } } /** * Updates issue in the cache. Issue is updated only if it exists. * Issue is not added if it does not exist in the cache. * Issue position on the list is not changed when updating. * This is not blocking method and can be called in the UI thread * * @param issue issue to update */ public void updateIssue(final JiraIssueAdapter issue) { final IssueRecentlyOpenBean recentlyOpenIssueBean = new IssueRecentlyOpenBean(issue.getJiraServerData().getServerId(), issue.getKey(), issue.getIssueUrl()); if (items.containsKey(recentlyOpenIssueBean)) { // old value is replaced items.put(recentlyOpenIssueBean, issue); } } private List<JiraIssueAdapter> reverseList(final LinkedList<JiraIssueAdapter> jiraIssues) { Collections.reverse(jiraIssues); return jiraIssues; } private JiraIssueAdapter loadJiraIssue(final IssueRecentlyOpenBean recentlyOpen) throws JIRAException { final ServerId recentServer = recentlyOpen.getServerId(); if (recentServer == null) { return null; } final JiraServerData jiraServer = projectCfgManager.getEnabledJiraServerr(recentServer); if (jiraServer != null) { return IntelliJJiraServerFacade.getInstance().getIssue(jiraServer, recentlyOpen.getIssueKey()); } return null; } public static final class JIRAUserNameCache { private Map<JiraServerData, Map<String, JIRAUserBean>> serverMap = new HashMap<JiraServerData, Map<String, JIRAUserBean>>(); private JiraServerFacade facade; private JIRAUserNameCache() { facade = IntelliJJiraServerFacade.getInstance(); } private static JIRAUserNameCache instance = new JIRAUserNameCache(); public static JIRAUserNameCache getInstance() { return instance; } public JIRAUserBean getUser(final JiraServerData jiraServerData, final String userId) throws JIRAException, JiraUserNotFoundException { Map<String, JIRAUserBean> userMap = serverMap.get(jiraServerData); if (userMap == null) { userMap = new HashMap<String, JIRAUserBean>(); serverMap.put(jiraServerData, userMap); } JIRAUserBean user = userMap.get(userId); if (user == null) { user = facade.getUser(jiraServerData, userId); userMap.put(userId, user); } return user; } } }
// Name: Nanako Chung // Date: Feb 21st, 2017 // Description: this program eliminates duplicates in an array and returns the clean array to the user import java.util.Arrays; public class DupeEliminator { // main method public static void main(String[] args) { // input array int[] array = {4,5,5,5,2,3,1}; // calls the method below deleteDupes(array); } // method that takes in integers and returns an array without any dupes public static void deleteDupes(int[] array) { // creates a variable 'count' that goes down every time a duplicate is found int count=array.length; // outer for loop: iterates through every element in array for (int i=0; i<array.length; i++) { // inner for loop: iterates through every element before array[i] for (int j=0; j<i; j++) { // if there is an element that is equal to array[i], decrease the count by 1 because there is a dupe! if (array[i]==array[j]){ count-=1; // break prevents from counting the integer at array[i] twice (if found again) (e.g. array[3]=array[1]=array[2]. we don't want to count 5 twice!) break; } } } // creates a new array the size of the previous array without dupes int [] newArray = new int [count]; // first element can never be a dupe! int indexCount = 1; // outer for loop: iterates through every element in array for (int a=0; a<array.length; a++) { // excludes the first element in the array because it can never be a double if (a==0){ newArray[0]=array[a]; } // accumulator variable called 'total' to add the number of attempts until an index with the same element is found int total = 0; // inner for loop: iterates through every element before array[a] for (int b=0; b<a; b++) { // if array[b] is not a dupe of array[a], increase the number of attempts (total) by 1 if (array[a]!=array[b]){ total+=1; // if total==a, that means that there were no dupes found at any previous index and so the indexCount is the index of the non-dupe // we include this in our newArray! if (total==a){ newArray[indexCount] = array[a]; // the indexCount goes up by 1 every time the if statement is carried out to avoid putting a new element in the same position and essentially replacing the previous one indexCount+=1; } } } } // display the clean array without dupes to the user! System.out.println(Arrays.toString(newArray)); } }
package com.nfet.icare.util; public class GlobalConstants { public final static String ERROR_CODE_SUCCESS = "0"; public final static String ERROR_CODE_FAIL = "1"; public final static String ERROR_CODE_UNKNOWN = "2"; }
package com.pwc.brains.dictionary; import java.io.Serializable; public class Letter implements Serializable { private char name; public Letter(char name) { this.name = name; } public char name() { return name; } @Override public boolean equals(Object o) { if (o == null) { throw new NullPointerException(); } Letter l = null; if (o instanceof Letter) { l = (Letter) o; } else { throw new ClassCastException(); } return this.name == l.name(); } @Override public int hashCode() { return this.name; } }
package blackbird.core; /** * Enum indicating the reasons a connection has been closed for. */ public enum CloseReason { /** * Indicates the connection was closed by the other side. */ BY_OTHER_SIDE, /** * Indicates the connection was closed intentionally from this side. */ INTENTIONALLY, /** * Indicates the connection was closed due to a connection or communication error or corruption. */ FAILURE }
package com.edasaki.rpg.dungeons; import java.util.ArrayList; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.EnderCrystal; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import com.edasaki.core.utils.RMath; import com.edasaki.core.utils.RParticles; import com.edasaki.core.utils.RScheduler; import com.edasaki.core.utils.RTags; import com.edasaki.core.utils.RTicks; import com.edasaki.rpg.mobs.MobData; import com.edasaki.rpg.mobs.MobType; import de.slikey.effectlib.util.ParticleEffect; public class DungeonBoss { public MobType type; private Location loc; public MobData spawnedBoss; public EnderCrystal spawner; public ArmorStand as; public Dungeon dungeon; public boolean rewardsStage; public Location getLoc() { return loc.clone(); } public void setLoc(Location loc) { this.loc = loc; } public boolean spawnSpawner() { if (loc.getChunk().isLoaded() && !rewardsStage) { despawn(); if (spawner != null) { try { spawner.remove(); } catch (Exception e) { e.printStackTrace(); } } if (as != null) { try { as.remove(); } catch (Exception e) { e.printStackTrace(); } } ArrayList<Entity> ls = RMath.getNearbyEntities(loc, 3); for (Entity e : ls) { if (e instanceof EnderCrystal) { DungeonManager.spawners.remove(e.getUniqueId()); e.remove(); } else if (e instanceof ArmorStand) { ArmorStand temp = (ArmorStand) e; if (temp.getCustomName() != null && temp.getCustomName().contains("to spawn")) { DungeonManager.spawners.remove(temp.getUniqueId()); temp.remove(); } } } this.dungeon.clearRewarded(); spawner = (EnderCrystal) loc.getWorld().spawnEntity(getLoc().add(0, 0.2, 0), EntityType.ENDER_CRYSTAL); as = RTags.makeStand(ChatColor.GRAY + "[Hit to spawn dungeon boss]", getLoc().add(0, 1.75, 0), true); DungeonManager.registerSpawner(spawner, this); return true; } return false; } public void despawn() { this.dungeon.clearRewarded(); if (spawner != null) { spawner.remove(); spawner = null; } if (as != null) { as.remove(); as = null; } if (spawnedBoss != null) { spawnedBoss.despawn(); spawnedBoss = null; } } public void spawnBoss() { despawn(); RScheduler.schedule(DungeonManager.plugin, new Runnable() { int count = 0; @Override public void run() { if (count++ >= 3) { StringBuilder sb = new StringBuilder(); sb.append(ChatColor.GOLD); sb.append(ChatColor.BOLD); sb.append(type.name); String name = sb.toString(); spawnedBoss = type.spawn(loc, name); spawnedBoss.isBoss = true; spawnedBoss.dungeon = dungeon; RParticles.show(ParticleEffect.EXPLOSION_HUGE, getLoc().add(0, 1, 0)); } else { RParticles.showWithOffsetPositiveY(ParticleEffect.SMOKE_LARGE, loc, 2.0, 20); RParticles.showWithOffsetPositiveY(ParticleEffect.SPELL_MOB, loc, 2.0, 20); RScheduler.schedule(DungeonManager.plugin, this, RTicks.seconds(1)); } } }); } @Override public String toString() { return this.type.name + "-BOSS"; } /** * OK to spawn the spawner now? true if not (something is still spawned), false if ok to spawn */ public boolean isStillSpawned() { if (rewardsStage) return true; if (spawnedBoss != null) { if (spawnedBoss.dead || spawnedBoss.despawned) return false; if (!spawnedBoss.dead) return true; } return false; } }
package com.eomcs.basic.ex06; public class Exam0423 { public static void main(String[] args) { //String[] name = new String[4]; String name[] = {"๊ฐ€๋‚˜","๋‹ค๋ผ","๋งˆ๋ฐ”","์‚ฌ์•„","์ž"}; for (String ambles : name) { System.out.println(ambles); } } }
import java.io.*; import java.lang.*; import java.util.*; // #!/usr/bin/python -O // #include <stdio.h> // #include <stdlib.h> // #include <string.h> // #include<stdbool.h> // #include<limits.h> // #include<iostream> // #include<algorithm> // #include<string> // #include<vector> // using namespace std; /* # Author : @RAJ009F # Topic or Type : GFG/ARRAY # Problem Statement : lexicographically next string # Description : # Complexity : ======================= #sample output ---------------------- ======================= */ class NextGreater { public static void printNextString(String str) { int len = str.length(); char[] ch = str.toCharArray(); int i=len-1; while(i>0 && ch[i]>=ch[i-1]) i--; if(i<=0) { System.out.println("no string possible"); return; } int pivot = -1; for(int j=i; j<len; j++) { System.out.println(ch[i-1]+" "+ch[j]); if(ch[i-1]<ch[j]&&pivot==-1) { pivot=j; } if(ch[i-1]<ch[j]&&pivot!=-1&&ch[pivot]>ch[j]) pivot = j; } // char c = ch[pivot]; // ch[pivot] = ch[i-1]; // ch[i-1] = c; // Character[] temp = new Character[len-i+1]; // for(int j=i; j<len; j++) // temp[i-j] = ch[j]; // Arrays.sort(temp ); // for(int j=0; j<temp.length; j++) // ch[i+j] = temp[j]; System.out.println(ch.toString()); } public static void main(String args[]) { String str = "hdfc"; printNextString(str); } }
/* * File: Heater.java * Author: David Green DGreen@uab.edu * Assignment: Fall2018P1toP3 - EE333 Fall 2018 * Vers: 1.1.2 10/11/2018 alf - added default constructor * Vers: 1.1.1 09/25/2018 dgg - update documentation for toString * Vers: 1.1.0 09/02/2018 dgg - changes for P2 * Vers: 1.0.0 08/18/2018 dgg - initial coding */ /** * * @author David Green DGreen@uab.edu */ public class Heater implements Saveable{ private static long UIDSource = 20000; private long UID; // Unique ID private boolean state; // State of heater private Logger logger; // Logger object // Constructors public Heater(){ UID = UIDSource++; state = false; this.logger = new NullLogger(); } /** * Create a heater that needs to be configured * @param logger logger to use */ public Heater(Logger logger) { UID = UIDSource++; state = false; this.logger = (logger != null) ? logger : new NullLogger(); } // Queries /** * Get the Heater's UID * @return UID */ public long getUID() { return UID; } /** * Get the state of the header * @return true if heater is on otherwise false */ public boolean getState() { return this.state; } /** * returns the string โ€œHeater:{UID} = {state}โ€ * example: <code>Heater:20000 = ON</code> * @return formatted string */ @Override public String toString() { return "Heater:" + UID + " = " + (state ? "ON" : "OFF" ); } // Commands /** * Set heater's state * @param state true to turn heater ON, false for OFF */ public void setState(boolean state) { if ( this.state != state ) { logger.log(Logger.INFO, "" + this + ", turning " + ( (state) ? "on" : "off") ); } this.state = state; } }
package com.example.rihaf.diabetesdietexpert; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class DataListActivity extends AppCompatActivity { DatabaseHelper myDb; TextView TB, BB, IMT, KATEGORI, UMUR, JK, AKTIVITAS; ListView listView; Button button1; Double kalori; Double bobotusia; SQLiteDatabase sqLiteDatabase; DatabaseHelper userDBHelper; //userDBHelper ADALAH NAMA VARIABLE BARU DARI DatabaseHelper KHUSUS UNTUK MEMANGGIL DATA DARI DATABASE// Cursor cursor; //UNTUK MENJUNJUKKAN POSISI ROW TERBARU DARI DATABASE// ListDataAdapter listDataAdapter; //VARIABLE UNTUK MENGIMPLEMENTASIKAN METODE DARI CLASS ListDataAdapter.JAVA// @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.data_list_layout); myDb = new DatabaseHelper(this); listView = (ListView) findViewById(R.id.list_view); listDataAdapter = new ListDataAdapter(getApplicationContext(), R.layout.row_layout); listView.setAdapter(listDataAdapter); userDBHelper = new DatabaseHelper(getApplicationContext()); sqLiteDatabase = userDBHelper.getReadableDatabase(); cursor = userDBHelper.getInformation(sqLiteDatabase); if (cursor.moveToFirst()) { do { Double tb, bb, imt; Integer umur; String kategori, jk, aktivitas; tb = cursor.getDouble(0); bb = cursor.getDouble(1); imt = cursor.getDouble(2); kategori = cursor.getString(3); umur = cursor.getInt(4); jk = cursor.getString(5); aktivitas = cursor.getString(6); //MEMANGGIL DARI CLASS DataProvider.Java// DataProvider dataProvider = new DataProvider(tb, bb, imt, kategori, umur, jk, aktivitas); listDataAdapter.add(dataProvider); } while (cursor.moveToNext()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.main_activity_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.info_id: TextView idv = (TextView) findViewById(R.id.txt_idview); // TextView tbtxt = (TextView) findViewById(R.id.text_tb); TextView bbtxt = (TextView) findViewById(R.id.text_bb); // TextView imttxt = (TextView) findViewById(R.id.text_imt); TextView kategoritxt = (TextView) findViewById(R.id.text_kategori); TextView usiatxt = (TextView) findViewById(R.id.text_umur); TextView jktxt = (TextView) findViewById(R.id.text_jk); TextView aktivitastxt = (TextView) findViewById(R.id.text_aktv); TextView txt_ka = (TextView) findViewById(R.id.txt_ka); TextView txt_bu = (TextView) findViewById(R.id.txt_bobotusia); TextView txt_bak = (TextView) findViewById(R.id.txt_bobotaktvty); TextView txt_bktg = (TextView) findViewById(R.id.txt_bobotkateg); TextView txt_kal = (TextView) findViewById(R.id.txt_cal); double bb = Double.parseDouble(bbtxt.getText().toString()); String kategori = kategoritxt.getText().toString(); double usia = Double.parseDouble(usiatxt.getText().toString()); String jk = jktxt.getText().toString(); String aktifitas = aktivitastxt.getText().toString(); //------KALORI AWAL---------// if (jk.equals("Pria")) txt_ka.setText(Double.toString(bb*30)); if (jk.equals("Wanita")) txt_ka.setText(Double.toString(bb*25)); //----------BOBOT USIA--------// if (usia < 41) txt_bu.setText(Double.toString(0)); if (usia >= 41 && usia <= 59) txt_bu.setText(Double.toString(0.05)); if (usia >= 60 && usia <= 69) txt_bu.setText(Double.toString(0.1)); if (usia >= 70) txt_bu.setText(Double.toString(0.2)); //----------BOBOT AKTIVITAS--------// if (aktifitas.equals("Istirahat")) txt_bak.setText(Double.toString(0.1)); if (aktifitas.equals("Ringan")) txt_bak.setText(Double.toString(0.2)); if (aktifitas.equals("Sedang")) txt_bak.setText(Double.toString(0.3)); if (aktifitas.equals("Berat")) txt_bak.setText(Double.toString(0.5)); //----------BOBOT KATEGORI BB--------// if (kategori.equals("BB Kurang") && jk.equals("Pria")) txt_bktg.setText(Double.toString(+((bb * 30) * 0.2))); if (kategori.equals("BB Kurang") && jk.equals("Wanita")) txt_bktg.setText(Double.toString(+((bb * 25) * 0.2))); if (kategori.equals("BB Normal")) txt_bktg.setText(Double.toString(0)); if (kategori.equals("BB Lebih") && jk.equals("Pria")) txt_bktg.setText(Double.toString(-((bb * 30) * 0.2))); if (kategori.equals("BB Lebih") && jk.equals("Wanita")) txt_bktg.setText(Double.toString(-((bb * 25) * 0.2))); double bbt1 = Double.parseDouble(txt_ka.getText().toString()); double bbt2 = Double.parseDouble(txt_bu.getText().toString()); double bbt3 = Double.parseDouble(txt_bak.getText().toString()); double bbt4 = Double.parseDouble(txt_bktg.getText().toString()); double kalori = bbt1 - bbt2 + bbt3 + bbt4 ; txt_kal.setText(Double.toString(kalori)); // double finalkalori = Double.parseDouble(txt_kal.getText().toString()); String finalkalori = txt_kal.getText().toString(); String id16 = idv.getText().toString(); Cursor res = myDb.getDailyCalorieData(); if(res.getCount()==0){ boolean isInserted = myDb.insertDataDailyCalorie(finalkalori); if(isInserted =true) Toast.makeText(DataListActivity.this,"DATA TELAH DITAMBAH", Toast.LENGTH_LONG).show(); else Toast.makeText(DataListActivity.this,"DATA GAGAL DITAMBAH", Toast.LENGTH_LONG).show(); startActivity(new Intent(DataListActivity.this, DataListActivityGol.class));} else{ boolean isUpdate = myDb.updateDataDailyCalorie(id16, finalkalori); if(isUpdate =true) Toast.makeText(DataListActivity.this,"MENAMPILKAN SUSUNAN DIET", Toast.LENGTH_LONG).show(); else Toast.makeText(DataListActivity.this,"SYSTEM ERROR", Toast.LENGTH_LONG).show(); startActivity(new Intent(DataListActivity.this, DataListActivityGol.class));} return super.onOptionsItemSelected(item); case R.id.edit_id: startActivity(new Intent(DataListActivity.this, dietplanActivityedit.class)); default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(DataListActivity.this, MainActivity.class)); finish(); } }
package com.strings; public class MinWindow { public static void main(String[] args) { MinWindow mw = new MinWindow(); String s = "ADOBECODEBANC"; String t = "ABC"; System.out.println(mw.minWindow(s, t)); } /** * needs a map and two pointers left and right * compare the value and see if its greater than 0 then decrement the counter * check to see if the counter is 0 * if 0 then compare res length since we have to return the min window * if res is greater update the res value and update begin * increment left and also increment the counter * * return the string between res and res+begin * @param s * @param t * @return */ public String minWindow(String s,String t) { if(s.isEmpty() || t.isEmpty()|| s ==null || t ==null) return ""; int[] map = new int[256]; int res = Integer.MAX_VALUE; int left=0,right=0,begin=0, counter=t.length(); for(int i=0;i<t.length();i++) { map[t.charAt(i)-'A']++; } int sLength = s.length(); while(right < sLength) { if(map[s.charAt(right++) - 'A']-- > 0) counter--; while(counter ==0) { if(right-left <res) { res = right-left; begin = left; } if(map[s.charAt(left++) - 'A']++ == 0) counter++; } } return res==Integer.MAX_VALUE?"":s.substring(begin, begin+res); } }
package com.qx.wechat.comm.sdk.request.msg; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * ้Ÿณไนๆถˆๆฏ * @author Macky(liuyunsh@cn.ibm.com) * * @date: Apr 12, 2020 1:28:33 PM * * @since: 1.0.0 * */ public class PassiveMusicSendMsg extends PassiveMsg{ private static final long serialVersionUID = 3905563961902005931L; public PassiveMusicSendMsg() { super.setType(PassiveMsgType.MUSIC_MSG.getValue()); } @Override public PassiveMusicSendMsg setMsg(String msg) { try { super.setMsg(URLEncoder.encode(msg, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return this; } }
package com.ms.ms1; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class GuestProfileServiceImpl { @Autowired private MS2FeignClient client; public GuestProfileDTO getGuestProfile(String id) { GuestAddressDTO guestAddress = client.getGuestAddress(id); GuestProfileDTO dto = new GuestProfileDTO(); dto.setAddressDTO(guestAddress); dto.setName(id); dto.setOccupation("Software Employee"); return dto; } }
public class MergeSortedArray { public void merge(int[] nums1,int m ,int[] nums2, int n){ int i=m-1,j=n-1,z=m+n-1; while(i>=0 && j>=0){ if(nums1[i] > nums2[j]){ nums1[z] = nums1[i]; i--; z--; }else{ nums1[z] = nums2[j]; j--; z--; } } for(int k=i;k>=0;k--){ nums1[z] = nums1[k]; z--; } for(int k=j;k>=0;k--){ nums1[z] = nums2[k]; z--; } } }
import java.util.Vector; public class B3Vectortest { public static void main(String[] args) { Vector v=new Vector(); v.add("aaa"); v.add("bbb"); v.add("ccc"); v.add("ddd"); v.add("eeee"); for (int i = 0; i < v.size(); i++) { System.out.println(v.get(i));//๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ๊ฐ™์€ v์ฐธ์กฐ๋ณ€์ˆ˜์— ์ค‘๋ณต๊ฐ’์„ ๊ฐ€์ ธ์˜ค๋Š”๊ฑธ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. } v.remove(0);//remove๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•ด์„œ 0์ œ๊ฑฐ System.out.println(v.get(0));//0๋ฒˆ์งธ๋ฅผ ํ™•์ธํ•˜๋‹ˆ ๋‘๋ฒˆ์งธ๊ฐ€ ์•ž์œผ๋กœ ๊ฐ’์ด ์˜ฎ๊ฒจ์ง for (int i = 0; i < v.size(); i++) { System.out.println(v.get(i)); } //remove๋Š” ์ฒซ๋ฒˆ์งธ ๋งŒ๋‚˜๋Š” ์ •๋ณด๋งŒ ์‚ญ์ œ๋œ๋‹ค. } }
package live.citang.onema.service; import live.citang.onema.mbg.model.PmsBrand; import java.util.List; /** * @Author: citang * @Date: 2020-05-04 07:41 * @Description: description what the main function of this file */ public interface PmsBrandService { List<PmsBrand> listAllBrand(); int createBrand(PmsBrand brand); int updateBrand(Long id, PmsBrand brand); int deleteBrand(Long id); List<PmsBrand> listBrand(int pageNum, int pageSize); PmsBrand getBrand(Long id); }
package kr.or.ddit.service.adminmypage; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.List; import kr.or.ddit.dao.adminmypage.ImemberInfodao; import kr.or.ddit.dao.adminmypage.memberInfoDaoImpl; import kr.or.ddit.vo.MemberInfoVO; public class memberInfoServiceImpl extends UnicastRemoteObject implements ImemberInfoService { private static memberInfoServiceImpl service; private ImemberInfodao dao; public memberInfoServiceImpl() throws RemoteException{ dao = memberInfoDaoImpl.getInstance(); } public static ImemberInfoService getinstance() { try { if(service == null) service = new memberInfoServiceImpl(); } catch (RemoteException e) { e.printStackTrace(); } return service; } @Override public List <MemberInfoVO> getSearchMember(String mem_id) { return dao.getSearchMember(mem_id); } @Override public int updateMember(MemberInfoVO memVO) { return dao.updateMember(memVO); } @Override public int insertMember(MemberInfoVO memVO) { return dao.insertMember(memVO); } @Override public int deleteMember(String memId) { return dao.deleteMember(memId); } @Override public List<MemberInfoVO> tableview(String mem_id) { return dao.tableview(mem_id); } @Override public List<MemberInfoVO> getMymember() { return dao.getMymember(); } }
package com.hb.framework.system.service; import java.io.InputStream; import java.util.Collection; import java.util.List; import java.util.Map; import javax.servlet.ServletOutputStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.hb.framework.superhelp.base.BusinessException; import com.hb.framework.superhelp.util.ExcelHelp; import com.hb.framework.superhelp.util.PageView; import com.hb.framework.system.dao.UserLoginListDao; import com.hb.framework.system.entity.UserLoginList; @Transactional @Service("userLoginListService") public class UserLoginListService{ @Autowired private UserLoginListDao userLoginListDao; public List<Map<String, Object>> getMap( ){ return userLoginListDao.getMap(); } public PageView query(PageView pageView, UserLoginList userLoginList) { List<UserLoginList> list = userLoginListDao.query(pageView, userLoginList); pageView.setRecords(list); return pageView; } public void add(UserLoginList userLoginList) { userLoginListDao.add(userLoginList); } public void exportExcel(String fileName, ServletOutputStream outputStream,PageView pageView, UserLoginList userLoginList)throws BusinessException { List<UserLoginList> list = userLoginListDao.query(pageView, userLoginList); ExcelHelp<UserLoginList> ex = new ExcelHelp<UserLoginList>(UserLoginList.class); try { ex.exportExcel(fileName, list, outputStream); } catch (Exception e) { throw new BusinessException("ๆ–‡ไปถๆ ผๅผไธๅฏนๆˆ–ไธๅญ˜ๅœจ๏ผ"); } } public void readExcel(InputStream inputStream,String fileName) throws BusinessException { ExcelHelp<UserLoginList> ex = new ExcelHelp<UserLoginList>(UserLoginList.class); Collection<UserLoginList> list=null; try { list = ex.importExcel(inputStream,fileName,1,2); } catch (Exception e) { throw new BusinessException("ๆ–‡ไปถๆ ผๅผไธๅฏนๆˆ–ไธๅญ˜ๅœจ๏ผ"); } for (UserLoginList userLoginList : list) { userLoginListDao.add(userLoginList); } } }
package BatailleNavale; import java.awt.event.*; public class ControlButtonGame extends Control implements ActionListener { public ControlButtonGame(Model model, Vue vue) { super(model, vue); vue.setButtonsControlGame(this); } public void actionPerformed(ActionEvent e) { int x = 0; int y = 0; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (e.getSource().equals(vue.getButtonAt(i, j))) { y = i; x = j; } } } //System.out.println("x = "+x+", y = "+y); if (model.isCoupValide(new Coordonnee(y, x)) && model.getaJoue()==false) { System.out.println("a jouรฉ"); model.setaJoue(true); if (model.getJoueurEnCours()==Model.JOUEUR_1) { model.getTir1()[model.getIndiceDernierCoupJoueur1()]=new Coordonnee(y, x); model.setIndiceDernierCoupJoueur1(model.getIndiceDernierCoupJoueur1()+1); } else { model.getTir2()[model.getIndiceDernierCoupJoueur2()]=new Coordonnee(y, x); model.setIndiceDernierCoupJoueur2(model.getIndiceDernierCoupJoueur2()+1); } vue.refresh(); if (model.isBateauAt(new Coordonnee(y, x))) { vue.getButtonAt(y, x).setIcon(vue.getExplosion()); } return; } System.out.println("Ne peut plus jouer"); } }
/* * @lc app=leetcode.cn id=75 lang=java * * [75] ้ขœ่‰ฒๅˆ†็ฑป */ // @lc code=start class Solution { public void sortColors(int[] nums) { int[] count = new int[3]; for (int i = 0; i < nums.length; i++) { switch (nums[i]) { case 0: count[0]++; break; case 1: count[1]++; break; case 2: count[2]++; break; default: break; } } int index = 0; for (int j = 0; j < count[0]; j++) { nums[index++] = 0; } for (int j = 0; j < count[1]; j++) { nums[index++] = 1; } for (int j = 0; j < count[2]; j++) { nums[index++] = 2; } } } // @lc code=end
package me.jcomo.slimtwitter.models; import android.os.Parcel; import android.os.Parcelable; import com.activeandroid.ActiveAndroid; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import com.activeandroid.query.Delete; import com.activeandroid.query.Select; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import me.jcomo.slimtwitter.utils.TwitterUtils; @Table(name = "Tweets") public class Tweet extends Model implements Parcelable { @Column(name = "RemoteId", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) private long uid; @Column(name = "Body") private String body; @Column(name = "User", index = true, onUpdate = Column.ForeignKeyAction.CASCADE, onDelete = Column.ForeignKeyAction.CASCADE) private User user; @Column(name = "CreatedAt") private long createdAt; @Column(name = "RetweetCount") private int retweetCount; @Column(name = "Retweeted") private boolean retweeted; @Column(name = "FavoriteCount") private int favoriteCount; @Column(name = "Favorited") private boolean favorited; private List<String> mediaUrls = new ArrayList<>(); public static final Parcelable.Creator<Tweet> CREATOR = new Parcelable.Creator<Tweet>() { @Override public Tweet createFromParcel(Parcel source) { return new Tweet(source); } @Override public Tweet[] newArray(int size) { return new Tweet[size]; } }; public Tweet() { } public Tweet(Parcel in) { uid = in.readLong(); body = in.readString(); user = in.readParcelable(User.class.getClassLoader()); createdAt = in.readLong(); retweetCount = in.readInt(); retweeted = in.readInt() != 0; favoriteCount = in.readInt(); favorited = in.readInt() != 0; in.readStringList(mediaUrls); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(uid); dest.writeString(body); dest.writeParcelable(user, flags); dest.writeLong(createdAt); dest.writeInt(retweetCount); dest.writeInt(retweeted ? 1 : 0); dest.writeInt(favoriteCount); dest.writeInt(favorited ? 1 : 0); dest.writeStringList(mediaUrls); } @Override public int describeContents() { return 0; } public long getUid() { return uid; } public String getBody() { return body; } public User getUser() { return user; } public long getCreatedAt() { return createdAt; } public String getFriendlyCreatedAt() { return TwitterUtils.friendlyTime(createdAt); } public String getFriendlyRetweetCount() { return TwitterUtils.friendlyNumber(retweetCount); } public boolean hasRetweets() { return retweetCount > 0; } public boolean isRetweeted() { return retweeted; } public boolean retweet() { if (retweeted) { return false; } else { retweeted = true; retweetCount += 1; return true; } } public String getFriendlyFavoriteCount() { return TwitterUtils.friendlyNumber(favoriteCount); } public boolean hasFavorites() { return favoriteCount > 0; } public boolean isFavorited() { return favorited; } public void toggleFavorite() { if (!favorited) { favorited = true; favoriteCount++; } else { favorited = false; favoriteCount--; } } public List<String> getMediaUrls() { return mediaUrls; } public static Tweet fromJSON(JSONObject tweetJson) { try { Tweet tweet = new Tweet(); tweet.uid = tweetJson.getLong("id"); tweet.body = tweetJson.getString("text"); tweet.user = User.fromJson(tweetJson.getJSONObject("user")); tweet.createdAt = TwitterUtils.timeFromString(tweetJson.getString("created_at")); tweet.retweetCount = tweetJson.optInt("retweet_count", 0); tweet.retweeted = tweetJson.optBoolean("retweeted", false); tweet.favoriteCount = tweetJson.optInt("favorite_count", 0); tweet.favorited = tweetJson.optBoolean("favorited", false); loadMediaUrls(tweet, tweetJson); return tweet; } catch (JSONException e) { e.printStackTrace(); return null; } } private static void loadMediaUrls(Tweet tweet, JSONObject tweetJson) { try { JSONArray mediaEntities = tweetJson.getJSONObject("entities").getJSONArray("media"); for (int i = 0; i < mediaEntities.length(); i++) { JSONObject media = mediaEntities.getJSONObject(i); loadMediaUrl(tweet, media); } } catch (JSONException e) { // Do nothing (just ignore this one) } } private static void loadMediaUrl(Tweet tweet, JSONObject media) { try { String mediaType = media.getString("type"); if ("photo".equals(mediaType)) { tweet.mediaUrls.add(media.getString("media_url")); } } catch (JSONException e) { // Do nothing (not a photo or no url) } } public static List<Tweet> fromJSONArray(JSONArray tweetsJson) { List<Tweet> tweets = new ArrayList<>(); for (int i = 0; i < tweetsJson.length(); i++) { Tweet tweet; try { JSONObject tweetJson = tweetsJson.getJSONObject(i); tweet = Tweet.fromJSON(tweetJson); } catch (JSONException e) { e.printStackTrace(); continue; } if (tweet != null) tweets.add(tweet); } return tweets; } public static List<Tweet> getRecentlyCached(int limit) { return new Select() .from(Tweet.class) .orderBy("CreatedAt DESC") .limit(limit) .execute(); } public static void saveMany(List<Tweet> tweets) { // NOTE: there is a bug here. Users will never be updated (unless they are cleared out // of the db). The better way to do this would be to map the users to their tweets and // then save each user and then his/her tweets. The reason for this that when you replace // in SQLite, it will cause a delete (Which will delete all associated tweets in this case). // Not a huge deal in this case because we are only keeping a limited amount at one time. ActiveAndroid.beginTransaction(); try { for (Tweet tweet : tweets) { tweet.saveWithUser(); } ActiveAndroid.setTransactionSuccessful(); } finally { ActiveAndroid.endTransaction(); } } private void saveWithUser() { User existingUser = User.loadRemoteId(user.getUid()); if (existingUser != null) { user = existingUser; } else { user.save(); } save(); } public static void deleteAll() { new Delete().from(Tweet.class).execute(); } }
package Provedor_Consumidor; /** * * @author Garcia Garcia Jose Angel */ public class Principal { public static void main(String[] args) { Drop drop = new Drop();; new Thread(new Produccer(drop)).start(); new Thread(new Consumer(drop)).start(); } }
package com.example.stepdefinitions; import com.example.pageobjects.*; import com.example.utils.Constants; import io.cucumber.java.en.And; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.testng.Assert; public class UserHomeStepDefinitions { private final UserHomePage userHomePage = new UserHomePage(); private final HomePage homePage = new HomePage(); private final CarModelPage carModelPage = new CarModelPage(); private final PopularMakePage popularMakePage = new PopularMakePage(); private final OverallRatingPage overallRatingPage = new OverallRatingPage(); public String popularMakeDetails = null; @Given("^User is on the Home Page$") public void userIsOnTheHomePage() { Assert.assertTrue(userHomePage.verifyUserHomePageIsDisplayed()); } @When("^All the links and details are displayed correctly$") public void allTheLinksAndDetailsAreDisplayedCorrectly() { Assert.assertTrue(homePage.verifyLinksDisplayedWithDetails()); popularMakeDetails = homePage.getDetailsOfPopularMake(); } @Then("^User clicks on \"([^\"]*)\"$") public void userClicksOn(String link) { homePage.clickOnLinkGivenByUser(link); } @And("Verifies the {string} page is loaded correctly") public void verifiesThePageIsLoadedCorrectly(String link) { switch (link.toUpperCase().replace(" ", "_")) { case Constants.POPULAR_MAKE_LINk: Assert.assertTrue(popularMakePage.verifyPopularMakePageIsDisplayed(popularMakeDetails)); break; case Constants.POPULAR_MODEL_LINk: Assert.assertTrue(carModelPage.verifyPopularModelPageIsDisplayed()); break; case Constants.OVERALL_RATING_LINK: Assert.assertTrue(overallRatingPage.verifyOverallRatingsPageIsDisplayed()); break; } } }
package com.lasform.core.model.dto; import com.lasform.core.C; import lombok.Data; import java.util.List; @Data public class GeoAreaDto { private long id; private String name; private String description; private C.GEO_AREA_TYPE type; private String areaString; private List<LatLng> areaList; private LatLng areaNortheast; private LatLng areaSouthwest; }
package solution; import java.util.Scanner; public class LoopQ2 { public static void main(String[] args) { int sum=0,r,s=0,n; System.out.println("enter a no:"); Scanner scanner = new Scanner(System.in); n=scanner.nextInt(); do{ r=n%10; s=s+r; n=n/10; } while(n>0); System.out.println(" all digit sum:"+s); } }
import org.junit.*; import play.test.*; import play.mvc.*; import play.mvc.Http.*; import models.*; public class HomePageTests extends FunctionalTest { @Test public void testThatIndexPageWorks() { Response response = GET("/"); assertIsOk(response); assertContentType("text/html", response); assertContentMatch("instaRomeo | Just Add Us",response); assertContentMatch("Enter your Girlfriend's name",response); assertContentMatch("When's your next anniversary?",response); assertContentMatch("When's her next birthday?",response); assertContentMatch("Want some brownie points?",response); assertContentMatch("She'll get flowers on the following days",response); assertContentMatch("Where should we send the flowers?",response); assertContentMatch("Billing Information",response); assertContentMatch("Awesome",response); } @Test public void testThat404PageWorks() { Response response = GET("/idontexist"); assertIsOk(response); assertContentType("text/html", response); assertContentMatch("<title>404</title", response); assertContentMatch("tb_sign1.png",response); } }
package com.web.common.user; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.Vector; import cis.internal.util.EncryptUtil; import com.web.framework.configuration.Configuration; import com.web.framework.configuration.ConfigurationFactory; import com.web.framework.data.DataSet; import com.web.framework.persist.AbstractDAO; import com.web.framework.persist.DAOException; import com.web.framework.persist.ListDTO; import com.web.framework.persist.QueryStatement; import com.web.framework.util.DateTimeUtil; import com.web.framework.util.StringUtil; import com.web.common.config.GroupDTO; import com.web.common.util.Base64Util; import com.web.common.user.UserDTO; import cis.internal.util.EncryptUtil; public class UserDAO extends AbstractDAO { /** * ๊ณ„์ • ๋ฆฌ์ŠคํŠธ. * @param userDto ์‚ฌ์šฉ์ž ์ •๋ณด * @return ListDTO * @throws DAOException */ public ListDTO userPageList(UserDTO userDto) throws DAOException { ListDTO retVal = null; String procedure = " { CALL hp_mgUserInquiry ( ? , ? , ? , ? , ? , ?, ?, ? ,?, ? ) } "; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getChUserID()); //์„ธ์…˜ ์•„์ด๋”” sql.setString(userDto.getvSearchType()); //๊ฒ€์ƒ‰๊ตฌ๋ถ„ sql.setString(userDto.getvSearch()); //๊ฒ€์ƒ‰์–ด sql.setInteger(userDto.getnRow()); //๋ฆฌ์ŠคํŠธ ๊ฐฏ์ˆ˜ sql.setInteger(userDto.getnPage()); //ํ˜„์ œ ํŽ˜์ด์ง€ sql.setString("PAGE"); //sp ๊ตฌ๋ถ„ sql.setString(userDto.getUseYN()); //์‚ฌ์šฉ์—ฌ๋ถ€ sql.setString(userDto.getvGroupID()); sql.setString(userDto.getvInitYN());//์ดˆ๊ธฐ์˜ต์…˜ sql.setInteger(userDto.getSearchTab());//๊ฒ€์ƒ‰ ํƒญ try{ retVal=broker.executePageProcedure(sql,userDto.getnPage(),userDto.getnRow()); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); } return retVal; } /** * ๊ณ„์ • ๋ฆฌ์ŠคํŠธ. * @param userDto ์กฐ์ง ์ •๋ณด * @return ListDTO * @throws DAOException */ public ListDTO groupPageList(UserDTO userDto) throws DAOException { ListDTO retVal = null; String procedure = " { CALL hp10_mgGroupFaxNumberInquiry ( ? , ? , ? , ? , ? , ? , ?, ?, ?) } "; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getChUserID()); //์„ธ์…˜ ์•„์ด๋”” sql.setString(userDto.getvSearchType()); //๊ฒ€์ƒ‰๊ตฌ๋ถ„ sql.setString(userDto.getvSearch()); //๊ฒ€์ƒ‰์–ด sql.setInteger(userDto.getnRow()); //๋ฆฌ์ŠคํŠธ ๊ฐฏ์ˆ˜ sql.setInteger(userDto.getnPage()); //ํ˜„์ œ ํŽ˜์ด์ง€ sql.setString("PAGE"); //sp ๊ตฌ๋ถ„ sql.setString(userDto.getvInitYN()); sql.setString(""); sql.setString(userDto.getvGroupID()); try{ retVal=broker.executePageProcedure(sql,userDto.getnPage(),userDto.getnRow()); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); } return retVal; } /** * ์‚ฌ์šฉ์ž๊ณ„์ • ๋“ฑ๋ก * @param userDto ์‚ฌ์šฉ์ž์ •๋ณด * @return retVal int * @throws DAOException */ public int userRegist(UserDTO userDto) throws Exception{ int retVal = -1; String procedure = " { CALL hp_mgUserRegist ( ?, ? , ? , ? , ? , ? , ?) } "; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getChUserID()); //์„ธ์…˜ ์•„์ด๋”” sql.setString(userDto.getUserID()); //์‚ฌ์šฉ์ž ์•„์ด๋”” sql.setString(userDto.getUserName()); //์‚ฌ์šฉ์ž ๋ช… sql.setString(userDto.getGroupID()); //๊ทธ๋ฃน์•„์ด๋”” sql.setString(userDto.getPassword()); //ํŒจ์Šค์›Œ๋“œ sql.setString(userDto.getOfficePhone()); //์‚ฌ๋ฌด์‹ค ์ „ํ™”๋ฒˆํ˜ธ sql.setString(userDto.getUseYN()); //์‚ฌ์šฉ์—ฌ๋ถ€ try{ retVal=broker.executeProcedureUpdate(sql); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); }finally { return retVal; } } /** * ์‚ฌ์šฉ์ž๊ณ„์ • Back * @param userDto ์‚ฌ์šฉ์ž์ •๋ณด * @return retVal int * @throws DAOException */ public int userBackRegist(UserDTO userDto) throws Exception{ int retVal = -1; String procedure = " { CALL hp_mgUserRegist ( ? , ? , ? , ? , ? , ?, ? , ? , ? , ?) } "; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getChUserID()); //์„ธ์…˜ ์•„์ด๋”” sql.setString(userDto.getUserID()); //์‚ฌ์šฉ์ž ์•„์ด๋”” sql.setString(userDto.getUserName()); //์‚ฌ์šฉ์ž ๋ช… sql.setString(userDto.getGroupID()); //๊ทธ๋ฃน์•„์ด๋”” sql.setString(userDto.getAuthID()); //๊ถŒํ•œ์•„์ด๋”” sql.setString(userDto.getPassword()); //ํŒจ์Šค์›Œ๋“œ sql.setString(userDto.getOfficePhone()); //์‚ฌ๋ฌด์‹ค ์ „ํ™”๋ฒˆํ˜ธ //sql.setString(userDto.getMobliePhone()); //๋ชจ๋ฐ”์ผ ์ „ํ™”๋ฒˆํ˜ธ //sql.setString(userDto.getEmail()); //์ด๋ฉ”์ผ //sql.setString(userDto.getIP()); //IP //sql.setString(userDto.getHostName()); //HOSTNAME sql.setString(userDto.getUseYN()); //์‚ฌ์šฉ์—ฌ๋ถ€ sql.setString(userDto.getAlarmYN()); //์•Œ๋žŒ์—ฌ๋ถ€ sql.setString(userDto.getDID()); //ํŒฉ์Šค๋ฒˆํ˜ธ try{ retVal=broker.executeBackProcedureUpdate(sql); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); }finally { return retVal; } } /** * ๊ณ„์ • ์ •๋ณด * @param userid * @return userDto ์‚ฌ์šฉ์ž ์ •๋ณด * @throws DAOException */ public UserDTO userView(UserDTO userDto) throws DAOException{ String procedure = "{ CALL hp_mgUserSelect ( ? ,? ,? ) }"; DataSet ds = null; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getChUserID()); // ์„ธ์…˜ ์•„์ด๋”” sql.setString("SELECT"); // sp๊ตฌ๋ถ„ sql.setString(userDto.getUserID()); //์‚ฌ์šฉ์ž ์•„์ด๋”” try{ ds = broker.executeProcedure(sql); userDto = new UserDTO(); while(ds.next()){ userDto.setUserID(ds.getString("UserID")); userDto.setUserName(ds.getString("UserName")); userDto.setPassword(ds.getString("Password")); userDto.setGroupID(ds.getString("GroupID")); userDto.setGroupName(ds.getString("GroupName")); userDto.setAuthID(ds.getString("AuthID")); userDto.setAuthName(ds.getString("AuthName")); userDto.setDID(ds.getString("DID")); userDto.setDIDFormat(ds.getString("DIDFormat")); userDto.setGroupFaxView(ds.getString("GroupFaxView")); userDto.setOfficePhone(ds.getString("OfficePhone")); userDto.setOfficePhoneFormat(ds.getString("OfficePhoneFormat")); userDto.setMobliePhone(ds.getString("MobliePhone")); userDto.setMobliePhoneFormat(ds.getString("MobliePhoneFormat")); userDto.setEmail(ds.getString("Email")); userDto.setIP(ds.getString("IP")); userDto.setHostName(ds.getString("HostName")); userDto.setExcelAuth(ds.getString("ExcelAuth")); userDto.setAlarmYN(ds.getString("AlarmYN")); userDto.setUseYN(ds.getString("UseYN")); userDto.setEchoYN(ds.getString("CallBackYN")); userDto.setViewFlag(ds.getString("ViewFlag")); } }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); }finally { try { if (ds != null) { ds.close(); ds = null; } } catch (Exception ignore) { log.error(ignore.getMessage()); } } return userDto; } /** * ์‚ฌ์šฉ์ž๊ณ„์ • ์ˆ˜์ • * @param userDto ์‚ฌ์šฉ์ž์ •๋ณด * @return retVal int * @throws DAOException */ public int userModify(UserDTO userDto) throws Exception{ int retVal = -1; String procedure = " { CALL hp_mgUserModify (?, ?, ?, ? , ? , ? , ?) } "; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getChUserID()); //์„ธ์…˜ ์•„์ด๋”” sql.setString(userDto.getUserID()); //์‚ฌ์šฉ์ž ์•„์ด๋”” sql.setString(userDto.getUserName()); //์‚ฌ์šฉ์ž ๋ช… sql.setString(userDto.getGroupID()); //๊ทธ๋ฃน์•„์ด๋”” sql.setString(userDto.getPassword()); //ํŒจ์Šค์›Œ๋“œ sql.setString(userDto.getOfficePhone()); //์‚ฌ๋ฌด์‹ค ์ „ํ™”๋ฒˆํ˜ธ sql.setString(userDto.getUseYN()); //์‚ฌ์šฉ์—ฌ๋ถ€ try{ retVal=broker.executeProcedureUpdate(sql); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); }finally { return retVal; } } /** * ๊ณ„์ • ์ •๋ณด๋ฅผ ์‚ญ์ œํ•œ๋‹ค.(๋‹ค๊ฑด์ฒ˜๋ฆฌ) * @param logid ๋กœ๊ทธ์•„์ด๋”” * @param users ID(check) ๋ฐฐ์—ด * @return int * @throws DAOException */ public int userDeletes(String logid,String[] users, String USERID) throws DAOException{ String procedure = " { CALL hp_mgUserDelete ( ? , ? ) } "; String[] r_data=null; int retVal = -1; int[] resultVal=null; QueryStatement sql = new QueryStatement(); sql.setBatchMode(true); sql.setSql(procedure); List batchList=new Vector(); try{ for(int i=0; users != null && i<users.length; i++){ List batch=new Vector(); r_data = StringUtil.getTokens(users[i], "|"); if(r_data[1].equals("Y")){ batch.add(USERID); //์„ธ์…˜ ์•„์ด๋”” batch.add(StringUtil.nvl(r_data[0],"")); //์‚ฌ์šฉ์ž ์•„์ด๋”” batchList.add(batch); } } sql.setBatch(batchList); resultVal=broker.executeProcedureBatch(sql); for(int i=0;i<resultVal.length;i++){ if(resultVal[i]==-1){ retVal=-1; break; }else{ retVal=resultVal[i]; } } }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); }finally{ return retVal; } } /** * ์‚ฌ์šฉ์ž EXCEL ๋ฆฌ์ŠคํŠธ * @param userDto * @return ListDTO * @throws DAOException */ public ListDTO userExcelList(UserDTO userDto) throws DAOException{ String procedure = " { CALL hp_mgUserInquiry ( ? , ? , ? , ? , ? , ?, ?, ? ,? ) } "; ListDTO retVal = null; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getChUserID()); //์„ธ์…˜ ์•„์ด๋”” sql.setString(userDto.getvSearchType()); //๊ฒ€์ƒ‰๊ตฌ๋ถ„ sql.setString(userDto.getvSearch()); //๊ฒ€์ƒ‰์–ด sql.setInteger(userDto.getnRow()); //๋ฆฌ์ŠคํŠธ ๊ฐฏ์ˆ˜ sql.setInteger(userDto.getnPage()); //ํ˜„์ œ ํŽ˜์ด์ง€ sql.setString("LIST"); //sp ๊ตฌ๋ถ„ sql.setString(userDto.getUseYN()); //์‚ฌ์šฉ์—ฌ๋ถ€ sql.setString(userDto.getvGroupID()); sql.setString(userDto.getvInitYN());//์ดˆ๊ธฐ์˜ต์…˜ sql.setSql(procedure); try{ retVal=broker.executeListProcedure(sql); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); } return retVal; } /** * ์‚ฌ์šฉ์ž Count ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค * @param userDto ์‚ฌ์šฉ์ž ์ •๋ณด * @return userDto * @throws DAOException */ public UserDTO userTotCount(UserDTO userDto) throws DAOException { String procedure = " { CALL hp_mgUserSelect ( ? , ? , ? ) } "; DataSet ds = null; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setString(userDto.getChUserID()); //์„ธ์…˜์•„์ด๋”” sql.setString("COUNT"); //SP๊ตฌ๋ถ„ sql.setString(""); //์‚ฌ์šฉ์ž ์•„์ด๋”” sql.setSql(procedure); try{ ds=broker.executeProcedure(sql); if(ds.next()) { userDto = new UserDTO(); userDto.setTotCount(ds.getString("TotCount")); userDto.setUseYN_NCount(ds.getString("UseYN_NCount")); userDto.setUseYN_YCount(ds.getString("UseYN_YCount")); } }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); }finally{ try{ if (ds != null) { ds.close(); ds = null; } }catch (Exception ignore){ log.error(ignore.getMessage()); } } return userDto; } /** * ์‚ฌ์šฉ์ž ์ค‘๋ณต ์ฒดํฌ * @return formCodeDto * @return result * @throws DAOException */ public String userDupCheck(UserDTO userDto, String jobGb) throws DAOException{ String procedure = " { CALL hp_mgUserSelect ( ? , ? , ? ) } "; DataSet ds = null; String result=""; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setString(userDto.getChUserID()); //์„ธ์…˜์•„์ด๋”” sql.setString(jobGb); //SP๊ตฌ๋ถ„ sql.setString(userDto.getUserID()); //์‚ฌ์šฉ์ž ์•„์ด๋”” sql.setSql(procedure); try{ ds=broker.executeProcedure(sql); if(ds.next()) { result=ds.getString("Result"); } }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); }finally{ try{ if (ds != null) { ds.close(); ds = null; } }catch (Exception ignore){ log.error(ignore.getMessage()); } } return result; } /** * ํŒจ์Šค์›Œ๋“œ๋ฅผ ์ธ์ฝ”๋”ฉํ•œ๋‹ค. * @param userid * @return * @throws DAOException */ public String setPasswdEncode(String passwd) throws DAOException{ String result = ""; try{ // Base64Util b64=new Base64Util(); // result=b64.encode(passwd.getBytes()); result=EncryptUtil.encrypt(passwd); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); } return result; } /** * ํŒจ์Šค์›Œ๋“œ๋ฅผ ๋””์ฝ”๋”ฉํ•œ๋‹ค. * @param userid * @return * @throws DAOException */ public String setPasswdDecode(String passwd) throws DAOException{ byte[] result = null; try{ Base64Util b64=new Base64Util(); result=b64.decode(passwd); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); } return result.toString(); } public ListDTO userFaxNumList(UserDTO userDto) throws DAOException { String procedure = " { CALL hp_mgUserFaxNumberList ( ? , ? , ? , ? , ? , ? ) } "; ListDTO retVal = null; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getGroupID()); //์‚ฌ์šฉ์ž ์•„์ด๋”” sql.setString(userDto.getSearchGb()); //๊ฒ€์ƒ‰๊ตฌ๋ถ„ sql.setString(userDto.getSearchTxt()); //๊ฒ€์ƒ‰์–ด sql.setInteger(userDto.getnRow()); //๋ฆฌ์ŠคํŠธ ๊ฐฏ์ˆ˜ sql.setInteger(userDto.getnPage()); //ํ˜„์ œ ํŽ˜์ด์ง€ sql.setString("PAGE"); //sp ๊ตฌ๋ถ„ sql.setSql(procedure); try{ retVal=broker.executePageProcedure(sql,userDto.getnPage(),userDto.getnRow()); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); } return retVal; } protected static Configuration config = ConfigurationFactory.getInstance().getConfiguration(); public static String LOG_PATH = config.getString("framework.importlog.path"); /** * ์‚ฌ์šฉ์ž EXCEL import * @param recordDto * @return URL * @throws Exception */ public String userListImport(ArrayList<UserDTO> users,String filename){ String importResult=""; int successcnt=0; int failcnt=0; String log_userid=""; String log_username=""; String log_officephone=""; String log_groupid=""; String log_useryn=""; String log_password=""; String log_result=""; String log_userchk=""; String log_groupidchk=""; String password=""; BufferedWriter out = null; int retVal = -1; try { //logํŒŒ์ผ ์ƒ์„ฑ out = new BufferedWriter(new FileWriter( LOG_PATH+File.separator+filename+".log")); for(int i=0;i<users.size();i++){ UserDTO userDto = users.get(i); log_userid = userDto.getUserID(); log_username = userDto.getUserName(); log_groupid = userDto.getGroupID(); password=userDto.getPassword().trim(); log_userchk=userDupCheck(userDto, "DUPLICATE");//userid ์ค‘๋ณต์ฒดํฌ if("1".equals(log_userchk)){ log_result="๋“ฑ๋ก์‹คํŒจ-์ค‘๋ณต๋œ ์‚ฌ์šฉ์ž ID์ž…๋‹ˆ๋‹ค."; failcnt++; }else if("2".equals(log_userchk)){ log_result="๋“ฑ๋ก์‹คํŒจ-์‚ญ์ œ๋˜์—ˆ๋˜ ์‚ฌ์šฉ์ž ID์ž…๋‹ˆ๋‹ค."; failcnt++; }else{ userDto.setUserID(log_groupid); log_groupidchk=userDupCheck(userDto,"G_CHECK");//group์ฒดํฌ if(!"1".equals(log_groupidchk)){ log_result="๋“ฑ๋ก์‹คํŒจ-๋“ฑ๋ก๋˜์ง€ ์•Š์€ ์†Œ์†์ฝ”๋“œ์ž…๋‹ˆ๋‹ค."; failcnt++; }else{ userDto.setUserID(log_userid); userDto.setPassword(setPasswdEncode(password)); //๋“ฑ๋ก spํ˜ธ์ถœ๋ถ€๋ถ„ retVal = userRegist(userDto); if(retVal == -1){ log_result = "๋“ฑ๋ก ์˜ค๋ฅ˜ - SQL Error!!"; failcnt++; }else if(retVal ==0){ log_result = "๋“ฑ๋ก ์‹คํŒจ - ๋“ฑ๋ก ์•ˆ๋จ"; failcnt++; }else{ log_result = "๋“ฑ๋ก ์„ฑ๊ณต - ID : "+userDto.getUserID(); successcnt++; } } } if(i==0){ out.write("["+i+"][DATE : "+DateTimeUtil.getDate()+"]"+"[TIME : "+DateTimeUtil.getTime()+"]"+"[USERID : "+log_userid+"]"+"[RESULT : "+log_result+"]"); }else{ out.write("\n["+i+"][DATE : "+DateTimeUtil.getDate()+"]"+"[TIME : "+DateTimeUtil.getTime()+"]"+"[USERID : "+log_userid+"]"+"[RESULT : "+log_result+"]"); } } importResult="์ด : "+users.size()+"๊ฑด ์ค‘ ์„ฑ๊ณต๊ฑด์ˆ˜ : "+successcnt+"๊ฑด ์‹คํŒจ๊ฑด์ˆ˜ : "+failcnt+"๊ฑด \\n๊ฒฐ๊ณผ๋กœ๊ทธ๋Š” WAS๊ฒฝ๋กœ["+LOG_PATH+"] ์˜ "+filename+".log ํŒŒ์ผ์—์„œ ํ™•์ธ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค."; out.close(); }catch (Exception e) { System.err.println(e); importResult="์—…๋กœ๋“œ๋ฅผ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.\\n์—…๋กœ๋“œ ์–‘์‹์— ๋งž๋Š” ๋ฐ์ดํƒ€์ธ์ง€ ํ™•์ธํ•˜์„ธ์š”!![SQL Error]"; }finally{ try{ if(out != null) out.close(); } catch(Exception e){} } return importResult; } /** * ์‚ฌ์šฉ์ž EXCEL import (Backup DB) * @param recordDto * @return URL * @throws Exception */ public String userListBackImport(ArrayList<UserDTO> users,String filename){ String importResult=""; int successcnt=0; int failcnt=0; String log_userid=""; String log_username=""; String log_officephone=""; String log_groupid=""; String log_did=""; String log_authid=""; String log_alarmyn=""; String log_useryn=""; String log_password=""; String log_result=""; String log_userchk=""; String log_didchk=""; String log_groupidchk=""; String log_authidchk=""; String log_extensionnochk=""; String password=""; String serverID=""; String hostName=""; BufferedWriter out = null; int retVal = -1; try { //logํŒŒ์ผ ์ƒ์„ฑ out = new BufferedWriter(new FileWriter( LOG_PATH+File.separator+filename+".log")); for(int i=0;i<users.size();i++){ UserDTO userDto = users.get(i); log_userid = userDto.getUserID(); log_username = userDto.getUserName(); log_did = userDto.getDID(); log_groupid = userDto.getGroupID(); log_authid = userDto.getAuthID(); password=userDto.getPassword().trim(); log_userchk=userDupCheck(userDto, "DUPLICATE");//userid ์ค‘๋ณต์ฒดํฌ if("1".equals(log_userchk)){ log_result="๋“ฑ๋ก์‹คํŒจ-์‚ฌ์šฉ์ž ID๊ฐ€ ์ค‘๋ณต์ž…๋‹ˆ๋‹ค."; failcnt++; }else if("2".equals(log_userchk)){ log_result="๋“ฑ๋ก์‹คํŒจ-์‚ญ์ œ๋˜์—ˆ๋˜ ์‚ฌ์šฉ์ž ID์ž…๋‹ˆ๋‹ค."; failcnt++; }else{ userDto.setUserID(log_did); //userDto.setDID(log_did); log_didchk = userDupCheck(userDto,"DID_CHECK"); if("1".equals(log_didchk)){ log_result="๋“ฑ๋ก์‹คํŒจ-๋“ฑ๋ก๋˜์ง€ ์•Š์€ FAX ๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค."; failcnt++; }else{ userDto.setUserID(log_groupid); log_groupidchk=userDupCheck(userDto,"GROUP_CHECK");//phoneip ์ค‘๋ณต์ฒดํฌ if(!"1".equals(log_groupidchk)){ log_result="๋“ฑ๋ก์‹คํŒจ-๋“ฑ๋ก๋˜์ง€ ์•Š์€ ์†Œ์†์ฝ”๋“œ์ž…๋‹ˆ๋‹ค."; failcnt++; }else{ userDto.setUserID(log_authid); log_authidchk=userDupCheck(userDto,"GROUP_CHECK");//phoneip ์ค‘๋ณต์ฒดํฌ if(!"1".equals(log_authidchk)){ log_result="๋“ฑ๋ก์‹คํŒจ-๋“ฑ๋ก๋˜์ง€ ์•Š์€ ์กฐํšŒ๊ถŒํ•œ ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค."; failcnt++; }else{ userDto.setUserID(log_userid); userDto.setPassword(setPasswdEncode(password)); //๋“ฑ๋ก spํ˜ธ์ถœ๋ถ€๋ถ„ retVal = userBackRegist(userDto); //serverID=userDto.getServerID(); hostName=StringUtil.nvl(userDto.getHostName(),""); if(retVal == -1){ log_result = "๋“ฑ๋ก ์˜ค๋ฅ˜ - SQL Error!!"; failcnt++; }else if(retVal ==0){ log_result = "๋“ฑ๋ก ์‹คํŒจ - ๋“ฑ๋ก ์•ˆ๋จ"; failcnt++; }else{ log_result = "๋“ฑ๋ก ์„ฑ๊ณต - ID : "+userDto.getUserID(); successcnt++; } /*if("".equals(hostName)){ log_result="๋“ฑ๋ก์‹คํŒจ-SQL Error!!"; failcnt++; }else if("N".equals(hostName)){ log_result="๋“ฑ๋ก์‹คํŒจ-๋…น์ทจ์„œ๋ฒ„์— ์‚ฌ์šฉ์ž ํ• ๋‹น์ด ๋ถˆ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.(๋“ฑ๋ก ์‚ฌ์šฉ์ž์ˆ˜ ์ดˆ๊ณผ)"; failcnt++; }else{ log_result="์„œ๋ฒ„ID : ("+serverID+") HostName : ("+hostName+") ๋“ฑ๋ก์„ฑ๊ณต"; successcnt++; }*/ } } } } if(i==0){ out.write("["+i+"][DATE : "+DateTimeUtil.getDate()+"]"+"[TIME : "+DateTimeUtil.getTime()+"]"+"[USERID : "+log_userid+"]"+"[DID : "+log_did+"]"+"[RESULT : "+log_result+"]"); }else{ out.write("\n["+i+"][DATE : "+DateTimeUtil.getDate()+"]"+"[TIME : "+DateTimeUtil.getTime()+"]"+"[USERID : "+log_userid+"]"+"[DID : "+log_did+"]"+"[RESULT : "+log_result+"]"); } } importResult="์ด : "+users.size()+"๊ฑด ์ค‘ ์„ฑ๊ณต๊ฑด์ˆ˜ : "+successcnt+"๊ฑด ์‹คํŒจ๊ฑด์ˆ˜ : "+failcnt+"๊ฑด \\n๊ฒฐ๊ณผ๋กœ๊ทธ๋Š” WAS๊ฒฝ๋กœ["+LOG_PATH+"] ์˜ "+filename+".log ํŒŒ์ผ์—์„œ ํ™•์ธ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค."; out.close(); }catch (Exception e) { System.err.println(e); }finally{ importResult="์—…๋กœ๋“œ๋ฅผ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.\\n์—…๋กœ๋“œ ์–‘์‹์— ๋งž๋Š” ๋ฐ์ดํƒ€์ธ์ง€ ํ™•์ธํ•˜์„ธ์š”!![SQL Error]"; try{ if(out != null) out.close(); } catch(Exception e){} } return importResult; } public ListDTO userFaxNumInfo(UserDTO userDto) throws DAOException { String procedure = " { CALL hp_mgUserFaxNumInfo ( ? ) } "; ListDTO retVal = null; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getUserID()); //๊ทธ๋ฃน ์•„์ด๋”” //sql.setString(userDto.getSearchGb()); //๊ฒ€์ƒ‰๊ตฌ๋ถ„ //sql.setString(userDto.getSearchTxt()); //๊ฒ€์ƒ‰์–ด //sql.setInteger(userDto.getnRow()); //๋ฆฌ์ŠคํŠธ ๊ฐฏ์ˆ˜ ///sql.setInteger(userDto.getnPage()); //ํ˜„์ œ ํŽ˜์ด์ง€ //sql.setString("PAGE"); //sp ๊ตฌ๋ถ„ sql.setSql(procedure); try{ retVal=broker.executeListProcedure(sql); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); } return retVal; } public int userDeleteFaxNum(UserDTO userDto) { int retVal = -1; String procedure = " { CALL hp_mgUserDeleteFaxNum ( ? , ? , ? ) } "; QueryStatement sql = new QueryStatement(); sql.setKey(userDto.getLogid()); //๋กœ๊ทธ์•„์ด๋”” sql.setSql(procedure); //ํ”„๋กœ์‹œ์ ธ ๋ช… sql.setString(userDto.getChUserID()); //์„ธ์…˜ ์•„์ด๋”” sql.setString(userDto.getUserID()); //user ์•„์ด๋”” sql.setString(userDto.getDID()); //ํŒฉ์Šค๋ฒˆํ˜ธ try{ retVal=broker.executeProcedureUpdate(sql); }catch(Exception e){ e.printStackTrace(); log.error(e.getMessage()); throw new DAOException(e.getMessage()); }finally { return retVal; } } public int userRegistFaxNum(UserDTO userDto) { int retVal = -1; return retVal; } public int changeDIDInfo(UserDTO userDto) { int retVal = -1; return retVal; } }
package Section2; public class Code17 { public static void main(String[] args) { // TODO Auto-generated method stub for (int n=2; n<=100000; n++){ if(isPrime(n) == true){ System.out.println(n); } } } static boolean isPrime(int k){ if(k<2){ return false; } for(int i=2; i*i<=k; i++){ if(k%i ==0){ return false; } } return true; } }
package io.jrevolt.sysmon.model; /** * @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a> */ public enum EndpointStatus { UNKNOWN, OK, UNAVAILABLE, ERROR, }
package com.stackroute; import com.mongodb.*; import java.net.UnknownHostException; public class MongodbDemo { public static void main(String[] args) { try { MongoOperations mongoOperations = new MongoOperations(); mongoOperations.createDocument(); mongoOperations.updateDocument(); mongoOperations.deleteDocument(); } catch (MongoException | UnknownHostException e) { e.printStackTrace(); } } }
package com.example.demo.moduls.redis.config; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; @Configuration @EnableCaching public class RedisConfig { @Bean public LettuceConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(new RedisStandaloneConfiguration()); } }
package com.ipincloud.iotbj.srv.domain; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Time; import java.sql.Date; import java.sql.Timestamp; import com.alibaba.fastjson.annotation.JSONField; //(AlgorithmPush)็ฎ—ๆณ•ๆŽจ้€ไบบๅ‘˜ //generate by redcloud,2020-07-24 19:59:20 public class AlgorithmPush implements Serializable { private static final long serialVersionUID = 7L; // ไธป้”ฎid private Long id ; // ็ฎ—ๆณ•id @JSONField(name = "algorithm_id") private Long algorithmId ; // ไบบๅ‘˜id @JSONField(name = "person_id") private Long personId ; // ๅˆ›ๅปบๆ—ถ้—ด private Long created ; // ไฟฎๆ”นๆ—ถ้—ด private Long updated ; public Long getId() { return id ; } public void setId(Long id) { this.id = id; } public Long getAlgorithmId() { return algorithmId ; } public void setAlgorithmId(Long algorithmId) { this.algorithmId = algorithmId; } public Long getPersonId() { return personId ; } public void setPersonId(Long personId) { this.personId = personId; } public Long getCreated() { return created ; } public void setCreated(Long created) { this.created = created; } public Long getUpdated() { return updated ; } public void setUpdated(Long updated) { this.updated = updated; } }
package oops; import java.util.Scanner; public class Operators { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); System.out.println("Enter 2 numbers"); int a = s.nextInt(); int b = s.nextInt(); System.out.printf("1)add\n2)sub\n3)mul\n4)div\n5)mod\n"); int n = s.nextInt(); Opera op = new Opera(); switch(n) { case 1: Opera.add(a,b); break; case 2: Opera.sub(a,b); break; case 3: Opera.mul(a,b); break; case 4: Opera.div(a,b); break; case 5: Opera.mod(a,b); break; default : System.out.println("Invalid Input"); } } } class Opera{ public static void add(int a,int b) { System.out.printf("Add->%d",a+b); } public static void sub(int a,int b) { System.out.printf("Sub->%d", a-b); } public static void mul(int a,int b) { System.out.printf("Mul->%d", a*b); } public static void div(int a,int b) { System.out.printf("Div->%d", a/b); } public static void mod(int a,int b) { System.out.printf("Mod->%d",a%b); } }