text
stringlengths
10
2.72M
package com.ak.texasholdem.player; public class User { private String nickname; private String userName; private String password; private int id; private int cash; public User() { } public User(String nickname, String userName, String password, int cash) { super(); this.nickname = nickname; this.userName = userName; this.password = password; this.cash = cash; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } protected String getUserName() { return userName; } protected void setUserName(String userName) { this.userName = userName; } protected String getPassword() { return password; } protected void setPassword(String password) { this.password = password; } public int getCash() { return cash; } public void setCash(int cash) { this.cash = cash; } public int getId() { return id; } }
package com.example.dialogueapp; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.drawerlayout.widget.DrawerLayout; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.NavigationUI; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.widget.Toast; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class MainActivity extends AppCompatActivity { private FirebaseAuth mAuth; NavController navController; DrawerLayout drawerLayout; ActionBarDrawerToggle mToggle; private FirebaseUser user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BottomNavigationView bottomNav = findViewById(R.id.bottom_nav); Intent intent = getIntent(); if (intent != null) { //Authentication // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance(); user = mAuth.getCurrentUser(); } Toast.makeText(this, "Connected as "+user.getEmail()+" Successfully.", Toast.LENGTH_SHORT ).show(); navController = Navigation.findNavController(this, R.id.nav_host_fragment); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); //Bottom Navigation Controller NavigationUI.setupWithNavController(bottomNav, navController); // //Drawer Navigation Controller mToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close); drawerLayout.addDrawerListener(mToggle); mToggle.syncState(); //getSupportActionBar().setDisplayHomeAsUpEnabled(true); // navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // Intent intent; // if(item.getItemId()==R.id.fragment_home) // Log.d("MsgAlert","This is home clicking"); // switch (item.getItemId()) { // case R.id.fragment_home : // Log.d("Checking","--------------------------------------------------------"); // intent = new Intent(MainActivity.this,fragment_home.class); // break; // case R.id.fragment_schedule_student : // intent = new Intent(MainActivity.this,fragment_home.class); // break; // case R.id.fragment_history : // intent = new Intent(MainActivity.this,fragment_home.class); // break; // } // return true; // } // }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mToggle.onOptionsItemSelected(item)) return true; return super.onOptionsItemSelected(item); } }
/** * 湖北安式软件有限公司 * Hubei Anssy Software Co., Ltd. * FILENAME : SiteTypeCacheServer.java * PACKAGE : com.anssy.venturebar.base.server * CREATE DATE : 2016-8-24 * AUTHOR : make it * MODIFIED BY : * DESCRIPTION : */ package com.anssy.venturebar.base.server; import com.anssy.venturebar.base.dao.SiteTypeDao; import com.anssy.venturebar.base.entity.SiteTypeEntity; import com.anssy.webcore.core.cache.CacheOperator; import com.anssy.webcore.core.cache.CacheServer; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * @author make it * @version SVN #V1# #2016-8-24# * 场地类型缓存 */ @Service("siteTypeCacheServer") public class SiteTypeCacheServer extends CacheServer<SiteTypeEntity> implements CacheOperator { /** * 缓存名称 */ private final String cacheName = "SiteType"; @Resource private SiteTypeDao siteTypeDao; public void load() { try { List<SiteTypeEntity> sts = siteTypeDao.findSiteTypeAll(); for (SiteTypeEntity st : sts) { super.put(cacheName, st.getId().toString(), st); } } catch (Exception e) { e.printStackTrace(); } } /** * 获取场地类型 * * @param typeId id */ public String findSiteType(String typeId) { String typeName = ""; SiteTypeEntity siteType; try { siteType = super.getValue(cacheName, typeId); if (siteType != null && siteType.getId() > 0) { typeName = siteType.getSiteName(); } else { siteType = siteTypeDao.findSiteTypeById(Long.parseLong(typeId)); if (siteType != null && siteType.getId() > 0) { typeName = siteType.getSiteName(); } } } catch (Exception e) { try { siteType = siteTypeDao.findSiteTypeById(Long.parseLong(typeId)); if (siteType != null && siteType.getId() > 0) { typeName = siteType.getSiteName(); } } catch (NumberFormatException e1) { typeName = ""; } } return typeName; } public String getCacheName() { return cacheName; } }
package net.imglib2.trainable_segmention.pixel_feature.calculator; import ij.ImagePlus; import net.imglib2.RandomAccessibleInterval; import net.imglib2.img.Img; import net.imglib2.img.display.imagej.ImageJFunctions; import net.imglib2.trainable_segmention.RevampUtils; import net.imglib2.trainable_segmention.Utils; import net.imglib2.trainable_segmention.pixel_feature.filter.SingleFeatures; import net.imglib2.trainable_segmention.pixel_feature.settings.ChannelSetting; import net.imglib2.trainable_segmention.pixel_feature.settings.FeatureSettings; import net.imglib2.trainable_segmention.pixel_feature.settings.GlobalSettings; import net.imglib2.type.numeric.ARGBType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.view.Views; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; /** * @author Matthias Arzt */ public class ColorFeatureGroupTest { private final GlobalSettings colorSettings = GlobalSettings.default2d() .channels(ChannelSetting.RGB) .build(); private final GlobalSettings graySettings = GlobalSettings.default2d() .channels(ChannelSetting.SINGLE) .build(); private final FeatureCalculator colorGroup = new FeatureCalculator(Utils.ops(), new FeatureSettings(colorSettings, SingleFeatures.gauss(8.0))); private final FeatureCalculator grayGroup = new FeatureCalculator(Utils.ops(), new FeatureSettings(graySettings, SingleFeatures.gauss(8.0))); private final Img<ARGBType> image = ImageJFunctions.wrapRGBA(new ImagePlus( "https://imagej.nih.gov/ij/images/clown.png")); @Test public void testAttributes() { List<String> expected = Arrays.asList( "red_gaussian blur sigma=8.0", "green_gaussian blur sigma=8.0", "blue_gaussian blur sigma=8.0"); assertEquals(expected, colorGroup.attributeLabels()); } @Test public void testImage() { RandomAccessibleInterval<FloatType> result = colorGroup.apply(image); List<RandomAccessibleInterval<FloatType>> results = RevampUtils.slices(result); List<RandomAccessibleInterval<FloatType>> channels = RevampUtils.splitChannels(image); for (int i = 0; i < 3; i++) { RandomAccessibleInterval<FloatType> expected = RevampUtils.slices(grayGroup.apply(channels .get(i))).get(0); Utils.assertImagesEqual(35, expected, results.get(i)); } } @Test public void testSplittedColorImage() { RandomAccessibleInterval<FloatType> asFloat = Views.stack(RevampUtils.splitChannels(image)); RandomAccessibleInterval<FloatType> expected = colorGroup.apply(asFloat); RandomAccessibleInterval<FloatType> actual = colorGroup.apply(image); Utils.assertImagesEqual(actual, expected); } }
package com.wen.test.model; import lombok.Data; import java.io.Serializable; import java.util.Date; import java.util.List; @Data public class Users implements Serializable { private String username; private Integer age; private Date birthday; }
package me.draimgoose.draimmenu.commandtags.tags.other; import me.draimgoose.draimmenu.DraimMenu; import me.draimgoose.draimmenu.api.GUI; import me.draimgoose.draimmenu.commandtags.CommandTagEvent; import me.draimgoose.draimmenu.openguimanager.GUIPosition; import org.apache.commons.lang.ArrayUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.scheduler.BukkitRunnable; public class SpecialTags implements Listener { DraimMenu plugin; public SpecialTags(DraimMenu pl) { this.plugin = pl; } @EventHandler public void commandTag(CommandTagEvent e){ if(e.name.equalsIgnoreCase("open=")) { e.commandTagUsed(); String guiName = e.args[0]; String cmd = String.join(" ",e.args).replace(e.args[0] + " ","").trim(); GUI openGUIs = null; GUIPosition openPosition = e.pos; for(GUI pane : plugin.guiList){ if(pane.getName().equals(guiName)){ openGUIs = pane.copy(); } } if(openGUIs == null){ return; } Character[] cm = ArrayUtils.toObject(cmd.toCharArray()); for(int i = 0; i < cm.length; i++){ if(cm[i].equals('[')){ String contents = cmd.substring(i+1, i+cmd.substring(i).indexOf(']')); String placeholder = contents.substring(0,contents.indexOf(':')); String value = plugin.tex.placeholders(e.gui,e.pos,e.p,contents.substring(contents.indexOf(':')+1)); openGUIs.placeholders.addPlaceholder(placeholder,value); i = i+contents.length()-1; }else if(cm[i].equals('{')){ String contents = cmd.substring(i+1, i+cmd.substring(i).indexOf('}')); openPosition = GUIPosition.valueOf(contents); i = i+contents.length()-1; } } openGUIs.open(e.p,openPosition); return; } if(e.name.equalsIgnoreCase("close=")) { e.commandTagUsed(); GUIPosition position = GUIPosition.valueOf(e.args[0]); if(position == GUIPosition.Middle && plugin.openGUIs.hasGUIOpen(e.p.getName(),position)){ plugin.openGUIs.closeGUIForLoader(e.p.getName(),GUIPosition.Middle); }else if(position == GUIPosition.Bottom && plugin.openGUIs.hasGUIOpen(e.p.getName(),position)){ plugin.openGUIs.closeGUIForLoader(e.p.getName(),GUIPosition.Bottom); }else if(position == GUIPosition.Top && plugin.openGUIs.hasGUIOpen(e.p.getName(),position)){ e.p.closeInventory(); } return; } if(e.name.equalsIgnoreCase("teleport=")) { e.commandTagUsed(); if (e.args.length == 5) { float x, y, z, yaw, pitch; x = Float.parseFloat(e.args[0]); y = Float.parseFloat(e.args[1]); z = Float.parseFloat(e.args[2]); yaw = Float.parseFloat(e.args[3]); pitch = Float.parseFloat(e.args[4]); e.p.teleport(new Location(e.p.getWorld(), x, y, z, yaw, pitch)); } else if (e.args.length <= 3) { float x, y, z; x = Float.parseFloat(e.args[0]); y = Float.parseFloat(e.args[1]); z = Float.parseFloat(e.args[2]); e.p.teleport(new Location(e.p.getWorld(), x, y, z)); } else { try { Player otherplayer = Bukkit.getPlayer(e.args[3]); float x, y, z; x = Float.parseFloat(e.args[0]); y = Float.parseFloat(e.args[1]); z = Float.parseFloat(e.args[2]); assert otherplayer != null; otherplayer.teleport(new Location(otherplayer.getWorld(), x, y, z)); } catch (Exception tpe) { plugin.tex.sendMessage(e.p,plugin.config.getString("config.format.notitem")); } } return; } if(e.name.equalsIgnoreCase("delay=")) { e.commandTagUsed(); final int delayTicks = Integer.parseInt(e.args[0]); String finalCommand = String.join(" ",e.args).replace(e.args[0],"").trim(); new BukkitRunnable() { @Override public void run() { try { plugin.commandTags.runCommand(e.gui,e.pos, e.p, finalCommand); } catch (Exception ex) { plugin.debug(ex, e.p); this.cancel(); } this.cancel(); } }.runTaskTimer(plugin, delayTicks, 1); } } }
package encapsule; /** * @file_name : Pay.java * @author : dingo44kr@gmail.com * @date : 2015. 9. 23. * @story : 월급에 따른 세금 구하기 */ public class PayMain { //멤버 필드 private final double TAX_RATE = 0.097; // 상수 private int salary; // 인스턴스 (의) 변수 private String name; private int tax; //멤버 메소드 public PayMain(int salary, String name) { this.name = name; this.salary = salary; this.tax = (int) (salary * 0.097); // // public PayMain(); // // } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getTax() { return tax; } public void setTax(int tax) { this.tax = tax; } }
package com.wxt.designpattern.iterator.test01.withdp; /** * @Author: weixiaotao * @ClassName Iterator * @Date: 2018/12/3 19:22 * @Description: 迭代器接口,定义访问和遍历元素的操作 */ public interface Iterator { /** * 移动到聚合对象的第一个位置 */ void first(); /** * 移动到聚合对象的下一个位置 */ void next(); /** * 判断是否已经移动聚合对象的最后一个位置 * @return true表示已经移动到聚合对象的最后一个位置, * false表示还没有移动到聚合对象的最后一个位置 */ boolean isDone(); /** * 获取迭代的当前元素 * @return 迭代的当前元素 */ Object currentItem(); }
package com.spring.minjun.board.service; import java.util.List; import com.spring.minjun.board.model.BoardVO; import com.spring.minjun.board.model.SearchVO; public interface IBoardService { void insert(BoardVO article); //r BoardVO getArticle(Integer boardNo); //u void update(BoardVO article); //d void delete(Integer boardNo); List<BoardVO> getArticleList(SearchVO search); Integer countArticles(SearchVO search); }
package com.services; import com.dao.UserDao; import com.dao.UserDaoImpl; import com.model.User; import java.util.List; public class UserService { public boolean validateDetails(User user) { String username = user.getUsername(); String password = user.getPassword(); if (username != null && password != null) { UserDaoImpl userDao = new UserDaoImpl(); userDao.register(user); return true; } else { return false; } } public boolean isValidUser(Login login) { String username=login.getUsername(); String password=login.getPassword(); if(username!=null && password!=null) { UserDaoImpl userDao=new UserDaoImpl(); List<User> userList=userDao.getUser(login); int flag=0; for(User u:userList) { if(u.getUsername().equals(login.getUsername()) && u.getPassword().equals(login.getPassword())) { flag=1; break; } } if(flag==0) return true; else return false; } return false; } }
/** * Created with IntelliJ IDEA. * User: daixing * Date: 12-12-29 * Time: 下午8:35 * To change this template use File | Settings | File Templates. */ public class DenseGraphPrimMST { private EdgeWeightedGraph G; private Edge[] edgeTo; private double[] disTo; private Queue<Edge> mst; private boolean[] marked; private double weight; public DenseGraphPrimMST(EdgeWeightedGraph G) { this.G = G; disTo = new double[G.V()]; edgeTo = new Edge[G.V()]; mst = new Queue<Edge>(); marked = new boolean[G.V()]; for(int i = 0; i < G.V(); ++i) disTo[i] = Double.POSITIVE_INFINITY; disTo[0] = 0; visit(0); for(int i =1 ;i < G.V(); ++i) { int v = 0; double min = Double.POSITIVE_INFINITY; for(int j = 0; j < G.V(); ++j) { if(!marked[j] && disTo[j] < min) { min = disTo[j]; v = j; } } mst.enqueue(edgeTo[v]); weight += disTo[v]; visit(v); } } private void visit(int v) { marked[v] = true; for(Edge e: G.adj(v)) { int w = e.other(v); if(!marked[w] && disTo[w] > e.weight()) { disTo[w] = e.weight(); edgeTo[w] = e; } } } public Iterable<Edge> mst() { return mst; } public double weight() { return weight; } }
package com.studentalert.cses6; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class ParentsActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_parents); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(" Parents Corner "); getSupportActionBar().setDisplayHomeAsUpEnabled(true); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setVisibility(View.INVISIBLE); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts( "mailto","Rahul", null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "REGARDING CONTENT OF CSE BETA App"); startActivity(Intent.createChooser(emailIntent, "Send email...")); } }); setupCollapsingToolbar(); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); WebView myWebView = (WebView) findViewById(R.id.web_view); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); myWebView.loadUrl("http://www.rajagiritech.ac.in/stud/parent/Index.asp"); myWebView.setWebViewClient(new WebViewClient()); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } private void setupCollapsingToolbar() { final CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById( R.id.collapse_toolbar); collapsingToolbar.setTitleEnabled(true); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_maths) { Global.subject = "Design and Analysis of algorithms"; Global.subjectCode = "daa"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); } else if (id == R.id.nav_pom) { Global.subject = "Internet Computing"; Global.subjectCode = "IC"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); } else if (id == R.id.nav_amp) { Global.subject = "Elective"; Global.subjectCode = "el"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); } else if (id == R.id.nav_dms) { Global.subject = "System Software"; Global.subjectCode = "ss"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); } else if (id == R.id.nav_dsp) { Global.subject = "Computer Networks"; Global.subjectCode = "cn"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); } else if (id == R.id.nav_os) { Global.subject = "Software Engineering"; Global.subjectCode = "se"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); } else if (id == R.id.nav_notif) { Intent notif = new Intent(getApplicationContext(), MainActivity.class); startActivity(notif); finish(); } else if (id == R.id.nav_databaselab) { Global.subject = "OS Lab"; Global.subjectCode = "oslab"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); }else if (id == R.id.nav_parent) { Intent parent = new Intent(getApplicationContext(), ParentsActivity.class); startActivity(parent); finish(); } else if (id == R.id.nav_mplab) { Global.subject = "miniproject lab"; Global.subjectCode = "mplab"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); }else if (id == R.id.nav_exam) { Global.subject = "Question Papers"; Global.subjectCode = "qp"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); }else if (id == R.id.nav_misc) { Global.subject = "Miscellaneous"; Global.subjectCode = "misc"; Intent subject = new Intent(getApplicationContext(), OopActivity.class); startActivity(subject); finish(); } else if (id == R.id.nav_share) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.AppShare)); startActivity(Intent.createChooser(sharingIntent, "Share via")); } else if (id == R.id.nav_send) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(Intent.EXTRA_TEXT, Global.AppShare); startActivity(Intent.createChooser(sharingIntent, "Share via")); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
package me.msce; import com.sun.org.apache.xpath.internal.operations.Bool; import org.bukkit.Material; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public enum ItemToEnchant { WOOD_PICKAXE, WOOD_AXE, WOOD_HOE, WOOD_SPADE, STONE_PICKAXE, STONE_AXE, STONE_HOE, STONE_SPADE, IRON_PICKAXE, IRON_AXE, IRON_HOE, IRON_SPADE, GOLD_PICKAXE, GOLD_AXE, GOLD_HOE, GOLD_SPADE, DIAMOND_PICKAXE, DIAMOND_AXE, DIAMOND_HOE, DIAMOND_SPADE, WOOD_SWORD, STONE_SWORD, IRON_SWORD, GOLD_SWORD, DIAMOND_SWORD, LEATHER_HELMET, LEATHER_CHESTPLATE, LEATHER_LEGGINS, LEATHER_BOOTS, CHAINMAIL_HELMET, CHAINMAIL_CHESTPLATE, CHAINMAIL_LEGGINS, CHAINMAIL_BOOTS, IRON_HELMET, IRON_CHESTPLATE, IRON_LEGGINS, IRON_BOOTS, GOLD_HELMET, GOLD_CHESTPLATE, GOLD_LEGGINS, GOLD_BOOTS, DIAMOND_HELMET, DIAMOND_CHESTPLATE, DIAMOND_LEGGINS, DIAMOND_BOOTS; static List<ItemToEnchant> tools = Arrays.asList(WOOD_PICKAXE, WOOD_AXE, WOOD_HOE, WOOD_SPADE, STONE_PICKAXE, STONE_AXE, STONE_HOE, STONE_SPADE, IRON_PICKAXE, IRON_AXE, IRON_HOE, IRON_SPADE, GOLD_PICKAXE, GOLD_AXE, GOLD_HOE, GOLD_SPADE, DIAMOND_PICKAXE, DIAMOND_AXE, DIAMOND_HOE, DIAMOND_SPADE, WOOD_SWORD, STONE_SWORD, IRON_SWORD, GOLD_SWORD, DIAMOND_SWORD); static List<ItemToEnchant> armor = Arrays.asList(LEATHER_HELMET, LEATHER_CHESTPLATE, LEATHER_LEGGINS, LEATHER_BOOTS, CHAINMAIL_HELMET, CHAINMAIL_CHESTPLATE, CHAINMAIL_LEGGINS, CHAINMAIL_BOOTS, IRON_HELMET, IRON_CHESTPLATE, IRON_LEGGINS, IRON_BOOTS, GOLD_HELMET, GOLD_CHESTPLATE, GOLD_LEGGINS, GOLD_BOOTS, DIAMOND_HELMET, DIAMOND_CHESTPLATE, DIAMOND_LEGGINS, DIAMOND_BOOTS); public static Material ItemToMaterial (ItemToEnchant i) { return Material.valueOf(i.name()); } public static ItemToEnchant MaterialToItem (Material m) { return ItemToEnchant.valueOf(m.name()); } public static Boolean isTool(ItemToEnchant i) { if(tools.contains(i)) { return true; } else if (!tools.contains(i)) { return false; } return false; } public static Boolean isArmor(ItemToEnchant i) { if(armor.contains(i)) { return true; } else if (!armor.contains(i)) { return false; } return false; } }
package enums; public enum ServiceOptions { SUPPORT("Support"), DATES("Dates"), COMPLEX_TABLE("Complex Table"), SIMPLE_TABLE("Simple Table"), TABLE_WITH_PAGES("Table with pages"), DIFFERENT_ELEMENTS("Different elements"); public String option; ServiceOptions(String option) { this.option = option; } }
package com.junzhao.shanfen.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.PopupWindow; import com.junzhao.base.base.APPCache; import com.junzhao.base.base.BaseAct; import com.junzhao.base.http.IHttpResultSuccess; import com.junzhao.base.http.MLHttpRequestMessage; import com.junzhao.base.http.MLHttpType; import com.junzhao.base.http.MLRequestParams; import com.junzhao.base.utils.MyLogger; import com.junzhao.shanfen.R; import com.junzhao.shanfen.model.PHRaffleResultData; import com.junzhao.shanfen.model.PHUserData; import com.junzhao.shanfen.service.LotteryService; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.event.OnClick; import org.json.JSONException; import org.json.JSONObject; /** * Created by Administrator on 2018/3/19 0019. * 抽奖首页 */ public class LotteryAct extends BaseAct { private PHRaffleResultData resultData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_lottery); ViewUtils.inject(this); initPopwindows(); } PopupWindow scopeinsupw; private void initPopwindows() { scopeinsupw = new PopupWindow(this); scopeinsupw.setBackgroundDrawable(null); View view = View.inflate(this,R.layout.dialog_scope_insu,null); view.findViewById(R.id.tv_textqueren).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { scopeinsupw.dismiss(); } }); view.findViewById(R.id.tv_scope).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startAct(LotteryAct.this,AnswerScopeListActivity.class); scopeinsupw.dismiss(); } }); scopeinsupw.setContentView(view); } @OnClick({R.id.tv_begin_result,R.id.tv_lottery_rule}) public void onClick(View view){ switch (view.getId()){ case R.id.tv_lottery_rule: startAct(this,LotteryRuleAct.class); break; case R.id.tv_begin_result: //开始抽奖 raffle(); break; } } @OnClick(R.id.titlebar_tv_left) public void leftClick(View view) { finish(); } public void setBackgroundAlpha(float bgAlpha) { WindowManager.LayoutParams lp = getWindow() .getAttributes(); lp.alpha = bgAlpha; getWindow().setAttributes(lp); } private void raffle() { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("userId",((PHUserData) APPCache.getUseData()).userId); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.LOTTERY, mlHttpParam, String.class, LotteryService.getInstance(), true); loadData(LotteryAct.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { MyLogger.kLog().e(obj.toString()); try { JSONObject jsonObject = new JSONObject(obj.toString()); int status = jsonObject.getInt("status"); String message = jsonObject.getString("message"); String showMessage = jsonObject.getString("showMessage"); if (status == 100) { if(!jsonObject.isNull("result")){ JSONObject data = jsonObject.getJSONObject("result"); resultData = new PHRaffleResultData(); resultData.awardName = data.getString("awardName"); resultData.awardImg = data.getString("awardImg"); resultData.awardId = data.getString("awardId"); resultData.awardValue = data.getDouble("awardValue"); Intent intent = new Intent(LotteryAct.this,LotteryBeginAct.class); intent.putExtra(LotteryBeginAct.Result,resultData); startActivity(intent); } else { showMessage(getApplicationContext(),showMessage); } }else { showMessage(getApplicationContext(),showMessage); } } catch (JSONException e) { e.printStackTrace(); } } }); } }
/** * Copyright (c) 2012 Vasile Popescu (elisescu@gmail.com) * * This source file CANNOT be distributed and/or modified without prior written * consent of the author. **/ package com.hmc.project.hmc.ui.hmcserver; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.util.StringUtils; import com.hmc.project.hmc.HMCApplication; import com.hmc.project.hmc.R; import com.hmc.project.hmc.aidl.IDeviceDescriptor; import com.hmc.project.hmc.aidl.IHMCConnection; import com.hmc.project.hmc.aidl.IHMCManager; import com.hmc.project.hmc.aidl.IHMCServerHndl; import com.hmc.project.hmc.aidl.IUserRequestsListener; import com.hmc.project.hmc.devices.implementations.HMCServerImplementation; import com.hmc.project.hmc.service.HMCService; import com.hmc.project.hmc.ui.Login; import com.hmc.project.hmc.utils.HMCUserNotifications; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.os.AsyncTask; import android.os.Bundle; import android.os.IBinder; import android.os.Looper; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; // TODO: Auto-generated Javadoc /** * The Class HMCInterconnectionWizzard. */ public class HMCInterconnectionWizzard extends Activity { /** The Constant TAG. */ protected static final String TAG = "DeviceMainScreen"; /** The m is bound. */ private boolean mIsBound; /** The m bound service. */ private HMCService mBoundService; /** The m hmc connection. */ private IHMCConnection mHMCConnection; /** The m hmc application. */ private HMCApplication mHMCApplication; /** The m info text view. */ private TextView mInfoTextView; /** The m jid text view. */ private EditText mJidTextView; /** The m context. */ private Context mContext; /** The m user requests listener. */ private UserRequestsListener mUserRequestsListener = new UserRequestsListener(); /** The m interconnect progress dialog. */ private ProgressDialog mInterconnectProgressDialog; /** The m external hmc server. */ private IDeviceDescriptor mExternalHMCServer; /** The m valid jid. */ private boolean mValidJid; /** The m user confirmed. */ private Boolean mUserConfirmed = new Boolean(false);; /** The m user confirmed notif. */ private Object mUserConfirmedNotif = new Object(); /** The m external hmc name. */ private String mExternalHMCName; /** The m buttons listener. */ private OnClickListener mButtonsListener = new OnClickListener() { public void onClick(View v) { switch (v.getId()) { case R.id.interconnect_hmc_butt_interc: { if (checkUsername(mJidTextView.getText().toString())) { try { interconnectToHMC(mJidTextView.getText().toString()); } catch (Exception e) { HMCUserNotifications.normalToast(mContext, "Internal error"); e.printStackTrace(); } } else { HMCUserNotifications.normalToast(mContext, "invalid JID"); } } default: break; } } }; /** * Interconnect to hmc. * * @param newDevFullJid * the new dev full jid * @throws Exception * the exception */ private void interconnectToHMC(String newDevFullJid) throws Exception { if (mHMCConnection == null) { throw new Exception(); } else { IHMCManager hmcMng = mHMCConnection.getHMCManager(); IHMCServerHndl hmcServerHmdl = hmcMng.implHMCServer(); hmcServerHmdl.registerUserRequestsListener(mUserRequestsListener); mInterconnectProgressDialog = ProgressDialog.show(this, "Interconnecting", "Getting information from external HMC server.\nPlease wait...", true, false); new HMCInterconnectionAsyncTask().execute(hmcServerHmdl, newDevFullJid); } } /** The m connection. */ private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mHMCConnection = IHMCConnection.Stub.asInterface(service); if (mHMCConnection != null) { } } public void onServiceDisconnected(ComponentName className) { mBoundService = null; Toast.makeText(HMCInterconnectionWizzard.this, R.string.local_service_disconnected, Toast.LENGTH_SHORT).show(); } }; /** * Do bind service. */ void doBindService() { bindService(new Intent(HMCInterconnectionWizzard.this, HMCService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBound = true; } /** * Do unbind service. */ void doUnbindService() { if (mIsBound) { unbindService(mConnection); mIsBound = false; } } /* * (non-Javadoc) * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { super.onDestroy(); doUnbindService(); } /* * (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); doBindService(); mHMCApplication = (HMCApplication)getApplication(); mContext = this; setContentView(R.layout.interconnect_hmc_wizzard); mJidTextView = (EditText) findViewById(R.id.add_new_dev_text_jid); // Watch for button clicks. Button button = (Button) findViewById(R.id.interconnect_hmc_butt_interc); button.setOnClickListener(mButtonsListener); // make sure we ended up in this activity with the app connected to XMPP // server if (!mHMCApplication.isConnected()) { doUnbindService(); finish(); } } /** * Check username. * * @param username * the username * @return true, if successful */ private boolean checkUsername(String username) { String name = StringUtils.parseName(username); String server = StringUtils.parseServer(username); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(server)) { mValidJid = false; } else { mValidJid = true; } return mValidJid; } /** * The listener interface for receiving userRequests events. The class that * is interested in processing a userRequests event implements this * interface, and the object created with that class is registered with a * component using the component's * <code>addUserRequestsListener<code> method. When * the userRequests event occurs, that object's appropriate * method is invoked. * * @see UserRequestsEvent */ class UserRequestsListener extends IUserRequestsListener.Stub { /* * (non-Javadoc) * @see * com.hmc.project.hmc.aidl.IUserRequestsListener#confirmDeviceAddition * (com.hmc.project.hmc.aidl.IDeviceDescriptor) */ @Override public boolean confirmDeviceAddition(IDeviceDescriptor newDevice) throws RemoteException { return false; } /* * (non-Javadoc) * @see * com.hmc.project.hmc.aidl.IUserRequestsListener#verifyFingerprint( * java.lang.String, java.lang.String, java.lang.String) */ @Override public boolean verifyFingerprint(String localFingerprint, String remoteFingerprint, String deviceName) throws RemoteException { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * @see * com.hmc.project.hmc.aidl.IUserRequestsListener#confirmHMCInterconnection * (com.hmc.project.hmc.aidl.IDeviceDescriptor, java.lang.String) */ @Override public boolean confirmHMCInterconnection(IDeviceDescriptor remoteHMCServer, String remoteHMCName) throws RemoteException { mExternalHMCServer = remoteHMCServer; mExternalHMCName = remoteHMCName; // mInfoTextView.setText(newDevice.toString()); mInterconnectProgressDialog.dismiss(); // ask the user to confirm the device description return askUserConfirmation(); } } /** * Ask user confirmation. * * @return true, if successful * @throws RemoteException * the remote exception */ private boolean askUserConfirmation() throws RemoteException { Log.d(TAG, "Showing the dialog to ask user for confirmation"); askUserConfirmationUITh(); synchronized (mUserConfirmedNotif) { try { mUserConfirmedNotif.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // finish the rest of adding new device protocol HMCInterconnectionWizzard.this.runOnUiThread(new Runnable() { public void run() { mInterconnectProgressDialog = ProgressDialog.show(HMCInterconnectionWizzard.this, "Add new device", "Sending HMC information.\nPlease wait...", true, false); } }); return mUserConfirmed; } /** * Ask user confirmation ui th. */ private void askUserConfirmationUITh() { HMCInterconnectionWizzard.this.runOnUiThread(new Runnable() { public void run() { try { new AlertDialog.Builder(HMCInterconnectionWizzard.this) .setTitle("Please confirm interconnection to " + mExternalHMCName) .setMessage("Name: " + mExternalHMCServer.getDeviceName() + "\nFingerprint: "+ mExternalHMCServer.getFingerprint()+ "\n\n\nMy fingerprint:\n" + mHMCConnection.getHMCManager().getLocalDevDescriptor() .getFingerprint()) .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { synchronized (mUserConfirmedNotif) { mUserConfirmed = Boolean.valueOf(true); mUserConfirmedNotif.notify(); } } }).setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { synchronized (mUserConfirmedNotif) { mUserConfirmed = Boolean.valueOf(false); mUserConfirmedNotif.notify(); } } }).show(); } catch (RemoteException e) { Log.e(TAG, "Error retrieving descriptor attributes"); e.printStackTrace(); } } }); } /** * The Class HMCInterconnectionAsyncTask. */ private class HMCInterconnectionAsyncTask extends AsyncTask<Object, Void, Boolean> { /* * (non-Javadoc) * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected Boolean doInBackground(Object... param) { IHMCServerHndl hmcServerHndl = (IHMCServerHndl) param[0]; String fullJID = (String) param[1]; boolean interconnectionSuccess = true; try { interconnectionSuccess = hmcServerHndl.interconnectTo(fullJID); } catch (RemoteException e) { Log.e(TAG, "Problem calling remote method in HMCService: addNewDevice on HMCServerHandler"); e.printStackTrace(); interconnectionSuccess = false; } return new Boolean(interconnectionSuccess); } /* * (non-Javadoc) * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(Boolean result) { // mConnectionRemoteException = result; Log.d(TAG, "Interconnection finished with success = " + result.booleanValue()); mInterconnectProgressDialog.dismiss(); if (result == true) { doUnbindService(); finish(); } else { // show user notification HMCInterconnectionWizzard.this.runOnUiThread(new Runnable() { public void run() { HMCUserNotifications.normalToast(HMCInterconnectionWizzard.this, "The interconnection failed"); } }); } } } }
package carnero.movement.common.model; public class Movement { public MovementEnum type; public long timestamp; // ms public long startElapsed; // ns public long endElapsed; // ns public Movement() { // empty } public Movement(MovementEnum type, long timestamp, long startElapsed) { this.type = type; this.timestamp = timestamp; this.startElapsed = startElapsed; } }
package com.healthyteam.android.healthylifers; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.google.firebase.database.DatabaseError; import com.healthyteam.android.healthylifers.Domain.DomainController; import com.healthyteam.android.healthylifers.Domain.UserLocation; import com.healthyteam.android.healthylifers.Domain.OnGetListListener; import com.healthyteam.android.healthylifers.Domain.User; import com.squareup.picasso.Picasso; import java.util.List; public class FriendProfileFragment extends Fragment { private User friend; private View fragment_layout; private TextView txtFriendNameSurname; private TextView txtFriendUsername; private TextView txtFriendPoints; private ImageView imgFriendPic; private ListView lvPosts; private ImageButton btnExit; private Fragment perent; PlaceItemAdapter placeAdapter; private OnGetListListener getPostListener; public void setPerent(Fragment perent){ this.perent=perent; } public void setFriend(User u){ this.friend=u; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { fragment_layout = inflater.inflate(R.layout.fragment_friend_profile,container,false); txtFriendNameSurname=fragment_layout.findViewById(R.id.TextView_FriendNameSurnameFP); txtFriendUsername = fragment_layout.findViewById(R.id.TextView_FriendUsernameFP); txtFriendPoints = fragment_layout.findViewById(R.id.TextView_FriendPointsFP); imgFriendPic= fragment_layout.findViewById(R.id.imageView_ProfilePicFP); btnExit=fragment_layout.findViewById(R.id.btnExitFP); lvPosts = (ListView) fragment_layout.findViewById(R.id.ListView_PostFP); if(friend.getImageUrl()!=null) { Picasso.get().load(friend.getImageUrl()).into(imgFriendPic); } else imgFriendPic.setImageResource(R.drawable.profile_picture); String NameSurname= friend.getName() + " " + friend.getSurname(); txtFriendNameSurname.setText(NameSurname); txtFriendUsername.setText(friend.getUsername()); txtFriendPoints.setText(friend.getPointsStirng()); btnExit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MainActivity) getContext()).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,perent).commit(); } }); placeAdapter = new FriendProfileFragment.PlaceItemAdapter(); //TODO: check if adapter posts list is the same list as user's post list getPostListener =new OnGetListListener() { @Override public void onChildAdded(List<?> list, int index) { if(lvPosts.getAdapter()==null) { placeAdapter.setPosts((List<UserLocation>) list); lvPosts.setAdapter(placeAdapter); } placeAdapter.notifyDataSetChanged(); } @Override public void onChildChange(List<?> list, int index) { placeAdapter.notifyDataSetChanged(); } @Override public void onChildRemove(List<?> list, int index,Object removedObject) { placeAdapter.notifyDataSetChanged(); } @Override public void onChildMoved(List<?> list, int index) { placeAdapter.notifyDataSetChanged(); } @Override public void onListLoaded(List<?> list) { if(lvPosts.getAdapter()==null) { placeAdapter.setPosts((List<UserLocation>) list); lvPosts.setAdapter(placeAdapter); } } @Override public void onCanclled(DatabaseError error) { }}; friend.addGetPostsListener(getPostListener); return fragment_layout; } public class PlaceItemAdapter extends BaseAdapter { private List<UserLocation> Posts; public void setPosts(List<UserLocation> post){ Posts=post; } @Override public int getCount() { return Posts.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { final LayoutInflater inflater = getLayoutInflater(); view = inflater.inflate(R.layout.layout_place_item, null); TextView txtPlaceName = (TextView) view.findViewById(R.id.textView_PlaceNamePI); TextView txtDate = (TextView) view.findViewById(R.id.textView_DatePI); TextView txtCommentsCount = (TextView) view.findViewById(R.id.TextView_commentFI); final TextView txtLikeCount = (TextView) view.findViewById(R.id.TextView_likeNumFI); final TextView txtDislikeCount = (TextView) view.findViewById(R.id.TextView_dislikeNumFI); final ImageView likeImgView =view.findViewById(R.id.imageView_LikePicFI); final ImageView dislikeImgView = view.findViewById(R.id.imageView_dislikePicFI); ImageView imageProfile = (ImageView) view.findViewById(R.id.imageView_PlacePicPI); final UserLocation currlocation = Posts.get(i); //TODO: set location picture from db. With piccaso imageProfile.setImageResource(R.drawable.location_clipart); txtPlaceName.setText(currlocation.getName()); String dateString = getString(R.string.dateLabel)+" "+currlocation.getDateAdded(); txtDate.setText(dateString); String commentsCountString = getString(R.string.CommentLabel) + getString(R.string.leftpar) + currlocation.getCommentCount()+getString(R.string.rightpar); txtCommentsCount.setText(commentsCountString); checkLikeImg(likeImgView,currlocation.isLiked()); txtLikeCount.setText(currlocation.getLikeCountString()); checkDislikeImg(dislikeImgView,currlocation.isDisliked()); txtDislikeCount.setText(currlocation.getDislikeCountString()); //TODO: check like dislike function. Check db behavior likeImgView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currlocation.likeThis(DomainController.getUser().getUID()); checkLikeImg(likeImgView,currlocation.isLiked()); checkDislikeImg(dislikeImgView,currlocation.isDisliked()); txtLikeCount.setText(currlocation.getLikeCountString()); txtDislikeCount.setText(currlocation.getDislikeCountString()); } }); dislikeImgView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currlocation.dislikeThis(DomainController.getUser().getUID()); checkDislikeImg(dislikeImgView,currlocation.isDisliked()); checkLikeImg(likeImgView,currlocation.isLiked()); txtLikeCount.setText(currlocation.getLikeCountString()); txtDislikeCount.setText(currlocation.getDislikeCountString()); } }); //TODO: open initialized viewLocation view /* view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //initialize and start Location dialog box } });*/ return view; } private void checkLikeImg(ImageView imgLike,boolean isLiked){ if(isLiked) imgLike.setImageResource(R.drawable.baseline_thumb_up_24_green); else imgLike.setImageResource(R.drawable.baseline_thumb_up_24); } private void checkDislikeImg(ImageView imgDislike,boolean isDisliked){ if(isDisliked) imgDislike.setImageResource(R.drawable.baseline_thumb_down_24_red); else imgDislike.setImageResource(R.drawable.baseline_thumb_down_24); } } }
package oopCourses.doctor; import static oopCourses.doctor.Specialization.CARDIOLOGIST; import static oopCourses.doctor.Specialization.DERMATOLOGIST; public class DoctorRunner { public static void main(String[] args) { Doctors allDoctors=new Doctors(); CityDistrict pechersky = new CityDistrict("Pechersky"); CityDistrict goloseevsky = new CityDistrict("Goloseevsky"); CityDistrict solomensky = new CityDistrict("Solomensky"); Clinic clinic1 = new Clinic("Doctor#1", new Address("Mechnikova", 2, pechersky)); Clinic clinic2 = new Clinic("Ne boleite",new Address("Vasilkovskaya", 15, goloseevsky)); Clinic clinic3 = new Clinic("Doctor lor", new Address("Lomonosova", 56, goloseevsky)); Doctor doctor1 = new Doctor("Ekaterina", "Belaya", DERMATOLOGIST); Doctor doctor2 = new Doctor("Elena", "Seraya", DERMATOLOGIST); clinic1.addDoctor(new Doctor("Irina", "Zelyonaya", CARDIOLOGIST)); clinic1.addDoctors(doctor1, doctor2); allDoctors.addToAllDoctors(doctor1, doctor2); //System.out.println(clinic1.getDoctors()); // clinic1.print(); clinic1.print(clinic1.filter(DERMATOLOGIST )); // allDoctors.print(); //allDoctors.print(allDoctors.filter(pechersky)); } }
/* * Tigase XMPP Client Library * Copyright (C) 2006-2012 "Bartosz Małkowski" <bartosz.malkowski@tigase.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. Look for COPYING file in the top folder. * If not, see http://www.gnu.org/licenses/. */ package tigase.jaxmpp.core.client.xmpp.modules.roster; import java.util.Collection; import tigase.jaxmpp.core.client.SessionObject; /** * Interface for implement co.jijichat.roster cache. For example to store co.jijichat.roster on clients * machine. */ public interface RosterCacheProvider { /** * Returns version of cached co.jijichat.roster. * * @param sessionObject * session object * @return version id */ String getCachedVersion(SessionObject sessionObject); /** * Loads cached co.jijichat.roster. * * @param sessionObject * * @return collection of loaded co.jijichat.roster items. */ Collection<RosterItem> loadCachedRoster(SessionObject sessionObject); /** * Update co.jijichat.roster cache. {@linkplain RosterStore} should be get from session * object. * * @param sessionObject * session object. * @param ver * version of co.jijichat.roster. */ void updateReceivedVersion(SessionObject sessionObject, String ver); }
package com.example.dbdemo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.example.bean.Person; import com.example.db.DatabaseUtil; import com.example.db.MyHelper; public class QueryActivity extends Activity { private EditText input; //查找关键字 private Button query; //查询按钮 private ListView mList; //显示查询结果 private DatabaseUtil mUtil; private List<Person> list = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.query); //初始化 initview(); } private void initview() { input = (EditText)findViewById(R.id.query_input); query = (Button)findViewById(R.id.query_btn); mList = (ListView)findViewById(R.id.mlist); //获取数据库 mUtil = new DatabaseUtil(QueryActivity.this); //监听查询按钮 query.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //每次查询时把界面清空 // mlayout.removeAllViews(); String name = input.getText().toString().trim(); //查询所有数据 // list = mUtil.queryAll(); list = mUtil.queryByname(name); Log.e("listsize", list.size()+""); if(list.size() != 0){ List<Map<String, Object>> templist = new ArrayList<Map<String,Object>>(); for(Person person:list){ Map<String,Object> map = new HashMap<String, Object>(); map.put("_id", person.getId()); map.put("name", person.getName()); map.put("sex", person.getSex()); templist.add(map); } //添加到ListView mList.setAdapter(new SimpleAdapter(QueryActivity.this, templist, R.layout.item, new String[]{"_id","name","sex"}, new int[]{R.id.id_item,R.id.name_item,R.id.sex_item})); mList.setOnItemClickListener(new myOnItemClickListener()); }else{ Toast.makeText(getApplicationContext(), "无相关记录", Toast.LENGTH_SHORT).show(); } } }); } //监听ListView,进入修改和删除界面 private class myOnItemClickListener implements OnItemClickListener{ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Map<String ,Object> map = (Map<String, Object>)parent.getItemAtPosition(position); int id_person = (Integer) map.get("_id"); // Toast.makeText(getApplicationContext(), id_person+"", Toast.LENGTH_SHORT).show(); Intent toDel_Update = new Intent(QueryActivity.this,DelAndUpdate.class); toDel_Update.putExtra("id", id_person+""); startActivity(toDel_Update); } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } }
package gui.comp; import java.awt.Font; import javax.swing.JProgressBar; import javax.swing.SwingUtilities; /** A thread-safe extension of JProgressBar. */ public class ProgressBar extends JProgressBar { public ProgressBar() { super (0, 100); setFont (new Font ("Arial", Font.BOLD, 12)); setStringPainted (true); } @Override public void setString (final String text) { SwingUtilities.invokeLater (new Runnable() { @Override public void run() { ProgressBar.super.setString (text); if (text != null) System.out.println (text); } }); } @Override public void setIndeterminate (final boolean newValue) { SwingUtilities.invokeLater (new Runnable() { @Override public void run() { ProgressBar.super.setIndeterminate (newValue); } }); } @Override public void setValue (final int n) { SwingUtilities.invokeLater (new Runnable() { @Override public void run() { ProgressBar.super.setValue (n); } }); } public void reset (final String text) { SwingUtilities.invokeLater (new Runnable() { @Override public void run() { ProgressBar.super.setIndeterminate (false); ProgressBar.super.setString (text != null ? text : ""); ProgressBar.super.setValue (0); } }); } }
package com.example.android.projectserver007; import android.annotation.TargetApi; import android.app.IntentService; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Process; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.util.Log; import android.widget.Toast; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class ClientConnectService extends Service { MulticastthreadRun multicastthreadRun = new MulticastthreadRun(); BroadCastUDPServer broadCastServer; private Looper mServiceLooper; private ServiceHandler mServiceHandler; public static final String MSG_DATA = "msgdata"; private Handler mMainHandler = null; // Handler that receives messages from the thread private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. Bundle data = msg.getData(); switch (msg.what) { case serverInterface.Server_starting: Toast.makeText(getApplicationContext(), getString(R.string.SERVER_STARTING) + data.getString(MSG_DATA), Toast.LENGTH_LONG).show(); break; case serverInterface.Server_MessageRead: Toast.makeText(getApplicationContext(), getString(R.string.SERVER_EVENT_MESSAGE) + data.getString(MSG_DATA), Toast.LENGTH_LONG).show(); break; case serverInterface.Server_CRQ: String msgCRQ = getString(R.string.SERVER_CRQ) + data.getString(MSG_DATA); Toast.makeText(getApplicationContext(), msgCRQ, Toast.LENGTH_LONG).show(); mMainHandler = new Handler(Looper.getMainLooper()); if (mMainHandler != null) { mMainHandler.post(new MainActivity.AddClient(getApplicationContext(),msgCRQ)); } else postNotification(getString(R.string.SERVER_CRQ), msgCRQ); break; default: super.handleMessage(msg); } } } @Override public void onCreate() { // Start up the thread running the service. Note that we create a // separate thread because the service normally runs in the process's // main thread, which we don't want to block. We also make it // background priority so CPU-intensive work will not disrupt our UI. HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); // Get the HandlerThread's Looper and use it for our Handler mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Override public int onStartCommand(@Nullable Intent intent, int flags, int startId) { //Toast.makeText(getApplicationContext(), "Service Starting", Toast.LENGTH_SHORT).show(); broadCastServer = new BroadCastUDPServer(); broadCastServer.start(); // If we get killed, after returning from here, restart return START_STICKY; } @Override public IBinder onBind(Intent intent) { // We don't provide binding, so return null return null; } @Override public void onDestroy() { super.onDestroy(); if(broadCastServer.isAlive()) broadCastServer.interrupt(); Toast.makeText(getApplicationContext(), "Service stopped", Toast.LENGTH_SHORT).show(); } public void postNotification(String title, String message) { Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_alert_notification) .setContentTitle(title) .setContentText(message) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) .setAutoCancel(true); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); // notificationId is a unique int for each notification that you must define notificationManager.notify(111, mBuilder.build()); } public void postNotification(String title, String message, int id) { Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_alert_notification) .setContentTitle(title) .setContentText(message) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) .setAutoCancel(true); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); // notificationId is a unique int for each notification that you must define notificationManager.notify(id, mBuilder.build()); } /////notification part private static final String CHANNEL_ID = "channel1"; // private void createNotificationChannel() { // // Create the NotificationChannel, but only on API 26+ because // // the NotificationChannel class is new and not in the support library // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // CharSequence name = getString(R.string.NOTIFICATION_CHANNEL_NAME); // String description = getString(R.string.NOTIFICATION_CHANNEL_DESCRIPTION); // int importance = NotificationManagerCompat.IMPORTANCE_DEFAULT; // NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); // channel.setDescription(description); // // Register the channel with the system; you can't change the importance // // or other notification behaviors after this // NotificationManager notificationManager = getSystemService(NotificationManager.class); // notificationManager.createNotificationChannel(channel); // } // } // @RequiresApi(api = Build.VERSION_CODES.O) // public Notification.Builder getChannelNotification(String title, String body){ // // return new Notification.Builder(getApplicationContext(),CHANNEL_ID) // .setContentText(body) // .setContentTitle(title) // .setSmallIcon(R.drawable.ic_launcher_foreground) // .setAutoCancel(true) // .setWhen(System.currentTimeMillis()); // } public void sendMessage(int type, String text) { Message msg = mServiceHandler.obtainMessage(); msg.what = type; Bundle data = new Bundle(); data.putString(MSG_DATA, text); msg.setData(data); mServiceHandler.sendMessage(msg); } public class BroadCastUDPServer extends Thread implements Runnable, serverInterface { public static final int SERVICE_UNICAST_PORT = 9000; public static final int SERVICE_BROADCAST_PORT = 9999;// receiving port public ArrayList<String> ClientsSoundState = new ArrayList<String>(); public ArrayList<Client> ClientIpArrayList = new ArrayList<Client>();//Array List For Saving The IPs of the Clients int serverstate;//flag String oldstate = "SD2"; DatagramSocket datagramSocketBroadcast; DatagramSocket datagramSocketUnicast; String soundStateMessage; @Override public void run() { // For each start request, send a message to start a job and deliver the // start ID so we know which request we're stopping when we finish the job try { datagramSocketUnicast = new DatagramSocket(SERVICE_UNICAST_PORT); datagramSocketBroadcast = new DatagramSocket(SERVICE_BROADCAST_PORT); sendMessage(serverInterface.Server_starting, "OK"); } catch (SocketException e) { e.printStackTrace(); } while (!isInterrupted() && !isRestricted()) { try { //Receiving the "CRQ" message from the Client by a Multicast datagram object byte[] byteBroadCast = new byte[3]; DatagramPacket datagramPacketBroadCast = new DatagramPacket(byteBroadCast, byteBroadCast.length); datagramSocketBroadcast.receive(datagramPacketBroadCast); String multiMessage = new String(byteBroadCast); //System.out.println(multiMessage); InetAddress clientIP = datagramPacketBroadCast.getAddress(); int clientPort = datagramPacketBroadCast.getPort(); Log.d("UDPServer> msg from", clientIP.toString() + ":" + clientPort); setclientIP(clientIP);//Getting the IP of the the received message setclientPort(clientPort);//Getting the Port of the the received message sendMessage(serverInterface.Server_CRQ, "IP=" + clientIP.toString() + ":" + clientPort); String clientIPString = clientIP.getHostAddress();//converting the IP from Bytes format to String format to access the client IPs Array list String clientPortString = String.valueOf(clientPort);//converting the Port from integer format to String format to access the client IPs Array list System.out.println(multiMessage.equals("CRQ")); //the end of the broadcast System.out.println("after receiving the CRQ"); //Sending the log In message to the whole group by a unicast datagram object send(loginMessage, clientIP, clientPort, datagramSocketUnicast); //passing the ClientIP and the Client Port to the client class to use them in the unicast thread later Client clnt = new Client(clientIPString, clientPortString); //check before adding in the Arraylist if (addClient(clnt) > -1) { if (multiMessage.equals("CRQ")) { System.out.println("hello from if condition------------------"); clnt.setStatus("1");//the server is ready to receive //thread to start the unicast sending and receiving messages // Thread uniCastThread = new Thread(new UniCastThreadRun(clnt)); // uniCastThread.start(); } } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }//the end of the infinite while ,to be able to wait for many clients datagramSocketUnicast.close(); datagramSocketBroadcast.close(); } private int addClient(Client c) { //TODO check if the client already exists prior to insert it in the list if (!ClientIpArrayList.contains(c)) {//checking if the array list contains that IP address or not,if not we will add it to it ClientIpArrayList.add(c); return ClientIpArrayList.size(); } else return -1; } //TODO The UniCast Class class UniCastThreadRun implements Runnable, serverInterface {//client Client client = null; UniCastThreadRun(Client c) { client = c; } //Constructing the date DateFormat dateformat = new SimpleDateFormat("dd/MM/yy HH:mm a");//To Set the Format of the Date Date currentdate = new Date();//To Get the Current Date //handler message preperation @TargetApi(Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public void run() { /* //creating a log file for the receiver side File file=new File(Environment.getExternalStorageDirectory() +"logserver.txt"); if(!file.exists()){ file.mkdirs(); } */ System.out.println(client.getStatus()); String state = client.getStatus(); System.out.println(state.length()); System.out.println(state.equals("1")); while (state.equals("1") && !isInterrupted()) { //Receiving the Sound States String soundStateMessageRecieved = recievemessage(datagramSocketUnicast); System.out.println(datagramSocketUnicast.getPort() + " " + soundStateMessageRecieved); //Sending Acknowledgment to the client to let him know that the server received the Sound State Message send(acknowledgementSoundState, clientIP, getclientPort(), datagramSocketUnicast);//16-7-2018 //Identifying the received message String soundState = ""; if (soundStateMessageRecieved.equals("SD0")) { soundState = "Speech";//Speech=SD0 } else if (soundStateMessageRecieved.equals("SD1")) { soundState = "Alarm";//Alarm=SD1 //Notification.Builder builder=BroadCastServer.getChannelNotification("Project Notification",soundState+"-"+getCurrentTimeStapwithTimeOnly()); //BroadCastServer.getManager().notify(new Random().nextInt(),builder.build()); } else if (soundStateMessageRecieved.equals("SD2")) { soundState = "Silence";//Silence==SD2 } else if (soundStateMessageRecieved.equals("DQR")) { //Receiving "DQR" from the client means that he will disconnect //close and disconnect the datagramSocketForUniCast //datagramSocketunicast.close(); //datagramSocketunicast.disconnect(); //===================check this step with juan carlos ClientIpArrayList.remove(client);//removing the client IP from the ArrayList client.setStatus("0");//setting the flag 0 to not access the if condition again } else { //if the client sends something else rather than the sound states or the disconnect message we will send him "500" message,(-->datagramPacketUnicastunknownCommandMessage6) System.out.println("UnKnown Command !!!"); send(unknownCommandMessage, clientIP, clientPort, datagramSocketUnicast); } //String Contains the received sound state,the date, time of receiving it and the IP of the client String currentState = dateformat.format(currentdate) + " " + clientIP + " " + soundState; //creating an string to pass the ip with the sound state to them main activity System.out.println(clientIP.toString() + ":" + soundState); soundStateMessage = clientIP.toString() + ":" + soundState; ClientsSoundState.add(soundStateMessage + "-" + getCurrentTimeStapwithTimeOnly()); ////////////////////////////////////////////////////////////////////////////////notificationCall(soundStateMessage); //bundle.putString("data",soundStateMessage); //mHandler.sendMessage(msg); if (!oldstate.equals(soundStateMessageRecieved)) { oldstate = soundStateMessageRecieved; /* //Write the received state in The Log File Of The Server try { FileWriter fileWriterSoundStates=new FileWriter(file,true); fileWriterSoundStates.write(currentState + "\r\n"); fileWriterSoundStates.flush(); fileWriterSoundStates.close(); } catch (IOException e) { e.printStackTrace(); } */ } }//the end of the attention loop it finishes when the client status goes to 0 }//the end of the run loop }//the end of the UniCastThreadRun class /***************************************** The Methods ******************************************************/ /** * Sending Packets Method * * @param message-the message we want to send to the client side * @param IP-in InetAddress format * @param Port-in integer format * @return Null */ public void send(String message, InetAddress IP, int Port, DatagramSocket datagramSocketsending) { byte[] buffer = message.getBytes(); DatagramPacket datagrampacket = new DatagramPacket(buffer, buffer.length, IP, SERVICE_UNICAST_PORT); //datagrampacket.setPort(); try { datagramSocketsending.send(datagrampacket); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * message we will receive from the client side * * @param datagramSocketrecieving of the socket in SocketAddress format * @return message received from the client side in string format */ public String recievemessage(DatagramSocket datagramSocketrecieving) { byte[] buffer = new byte[3]; DatagramPacket datagrampacket = new DatagramPacket(buffer, buffer.length); try { datagramSocketrecieving.receive(datagrampacket); broadCastServer.setclientPort(datagrampacket.getPort()); System.out.println("IP: " + datagrampacket.getAddress().toString() + " PORT:" + datagrampacket.getPort()); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String message = new String(buffer); InetAddress clientIP = datagrampacket.getAddress(); setclientIP(clientIP); int port = datagrampacket.getPort(); setclientPort(port); return message; } private InetAddress clientIP; private int clientPort; private SocketAddress socket; /** * Getter and Setter IP,Port "for the receiving method" and Socket **/ public void setclientIP(InetAddress clientIP) { clientIP = clientIP; } public InetAddress getclientIP() { return clientIP; } public void setclientPort(int clientIPort) { clientPort = clientIPort; } public int getclientPort() { return clientPort; } public String getCurrentTimeStapwithTimeOnly() { return new SimpleDateFormat("HH:mm a").format(new Date()); } }//// end broadcast }
package com.gbase.streamql.hive; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; public class StreamRelation { private ArrayList<String> begin = new ArrayList<String>(); private ArrayList<String> end = new ArrayList<String>(); private ArrayList<String> type = new ArrayList<String>(); // runtime-type private ArrayList<String> sql = new ArrayList<String>(); private HashMap<String,Integer> id = new HashMap<String,Integer>(); // name->int private int count = 0; private boolean isInited = false; private void init() throws Exception { try{ Connection conn = HiveService.getConn(); Statement stmt = HiveService.getStmt(conn); String query = "select source,dest,runtimeType,sql from " + Conf.SYS_DB + ".relation"; ResultSet res = stmt.executeQuery(query); while(res.next()){ this.count ++; this.begin.add(res.getString(1)); this.type.add(res.getString(3)); this.sql.add(res.getString(4)); String name = res.getString(2); this.end.add(name); this.id.put(name,new Integer(this.count-1)); } HiveService.closeStmt(stmt); HiveService.closeConn(conn); if(this.isInited = false){this.isInited = true;} } catch(Exception e){ throw new Exception("Failed to init StreamReltaion. " + e.getMessage()); } } public String[] getPrev(String name) throws Exception{ if(!this.isInited){ init(); } String[] prevs = this.begin.get(this.id.get(name)).split(","); return prevs; } public String getSql(String name) throws Exception{ if(!this.isInited){ init(); } return this.sql.get(this.id.get(name)); } public boolean hasSql(String name) throws Exception{ boolean has = false; String sql = new String(); try{ if(!this.isInited){ init(); } if(this.id.containsKey(name)){ sql = this.sql.get(this.id.get(name)) ; if(!sql.isEmpty()){ has = true; } } } catch(Exception e){ throw new Exception("Failed to execute \"hasSql\". "+e.getMessage()); } return has; } public boolean hasPrev(String name) throws Exception{ boolean has = false; String prevs = new String(); try{ if(!this.isInited){ init(); } if(this.id.containsKey(name)){ prevs = this.begin.get(this.id.get(name)) ; if(!prevs.isEmpty()){ has = true; } } } catch(Exception e){ throw new Exception("Failed to execute \"hasPrev\". "+e.getMessage()); } return has; } public boolean isOutput(String name) throws Exception{ boolean is = false; String type = new String(); try{ if(!this.isInited){ init(); } if(this.id.containsKey(name)){ type = this.type.get(this.id.get(name)) ; if(type.equals("output")){ is = true; } } } catch(Exception e){ throw new Exception("Failed to execute \"isOutput\". "+e.getMessage()); } return is; } }
package kredivation.mrchai.activity; import android.graphics.drawable.LayerDrawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import kredivation.mrchai.R; /** * Created by Narayan Semwal on 03-08-2017. */ public class SearchActivity extends AppCompatActivity { private LayerDrawable mCartMenuIcon; private MenuItem mSearchMenu, cart; private Button search; private EditText searchtext; RecyclerView searchrecycle; public static long countproductoncart = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); searchrecycle = (RecyclerView) findViewById(R.id.searchrecycle); LinearLayoutManager verticalLayoutmanager = new LinearLayoutManager(SearchActivity.this, LinearLayoutManager.VERTICAL, false); searchrecycle.setLayoutManager(verticalLayoutmanager); search = (Button) findViewById(R.id.search); searchtext = (EditText) findViewById(R.id.searchtext); } @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.cart, menu); mCartMenuIcon = (LayerDrawable) menu.findItem(R.id.action_cart).getIcon(); mSearchMenu = (MenuItem) menu.findItem(R.id.action_search); mSearchMenu.setVisible(false); return super.onCreateOptionsMenu(menu); } }
package com.dinh.customdate.ui.categorydetail; import androidx.recyclerview.widget.RecyclerView; public interface CategoryDetailViewCallback { int computeVerticalScrollRange(RecyclerView.State state); }
package datastructures.graphs; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Stack; public class TopologicalSort { public static List<GraphNode> topologicalSort(GraphNode[] nodes) { int no_of_nodes = nodes.length - 1; HashSet<Integer> visitedMap = new HashSet<>(); Stack<GraphNode> stack = new Stack<>(); for (int i = 1; i <= no_of_nodes; i++) { if (!visitedMap.contains(nodes[i].getData())) { topologicalSortUtil(nodes[i], visitedMap, stack); } } List<GraphNode> topologicalOrder = new LinkedList<>(); while (!stack.empty()) { topologicalOrder.add(stack.pop()); } return topologicalOrder; } private static void topologicalSortUtil(GraphNode node, HashSet<Integer> visitedMap, Stack<GraphNode> stack) { visitedMap.add(node.getData()); List<GraphNode> nodeNeighbours = node.getNeighbours(); for (GraphNode nodeNeighbour : nodeNeighbours) { if (!visitedMap.contains(nodeNeighbour.getData())) { topologicalSortUtil(nodeNeighbour, visitedMap, stack); } } stack.push(node); } }
package com.fun.driven.development.fun.unified.payments.gateway.util; import io.github.jhipster.config.JHipsterConstants; import org.apache.commons.validator.routines.checkdigit.CheckDigitException; import org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import org.springframework.stereotype.Service; import java.time.Instant; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * Generates unique numeric references with the following format: * * x xxxx xxxxxxxxxx xxxx x * | | | | \ * | | | | Luhn check digit * | | | \ * | | | counter (0000-9999 sequential) * | | \ * | | timestamp (seconds since 1-1-1970) * | \ * | system id (1xx = development, 2xx = test, 3xx = production) * \ * version of the reference * * Spring defines the default scope as SINGLETON so as long as all clients use DI to inject this service * there won't be any problems of duplicated references */ @Service public class ReferenceGenerator { private static final Logger LOG = LoggerFactory.getLogger(ReferenceGenerator.class); private static final String DEFAULT_VERSION = "1"; private static final LuhnCheckDigit luhnCheck = new LuhnCheckDigit(); private AtomicLong second; private AtomicInteger counter; @Autowired private Environment env; public ReferenceGenerator() { second = new AtomicLong(Instant.now().getEpochSecond()); counter = new AtomicInteger(-1); // Initiate to -1 so that we can use 0 as first value } public synchronized String generate() { increaseSequence(Instant.now().getEpochSecond()); String baseRef = DEFAULT_VERSION + fetchSystemReference() + Instant.now().getEpochSecond() + fetchSequence(); String checksum = "X"; try { checksum = luhnCheck.calculate(baseRef); } catch (CheckDigitException e) { LOG.error("Couldn't generate Luhn checksum for reference {}", baseRef, e); } return baseRef + checksum; } /** * Combines the current second with a counter to provide a sequence of integers in a particular second. * When called several times within the same second, atomically increments the counter. * The highest value within the current second is 9999. * * if second == currentSecond and current value == 10000, 0 * if second != currentSecond, 0 * otherwise counter++ * * @param currentSecond moment in which are trying to increment the counter */ private void increaseSequence(long currentSecond) { if (second.get() == currentSecond) { counter.set(counter.incrementAndGet()); if (counter.compareAndSet(10000, 0)) { waitUntilNextSecond(); second.set(Instant.now().getEpochSecond()); counter.set(0); } } else { second.set(currentSecond); counter.set(0); } } private String fetchSequence() { return String.format ("%04d", counter.get()); } private void waitUntilNextSecond() { int sleepCounter = 0; int sleepTime = 5; do { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { // We can safely ignore the IE as we will just wait for a split of a second } sleepCounter++; } while (second.get() == Instant.now().getEpochSecond()); LOG.warn("Reached max of 10000 increments per second and waited {} ms.", (sleepCounter * sleepTime)); } private String fetchSystemReference() { if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { return "1000"; } if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_TEST))) { return "2000"; } if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_PRODUCTION))) { return "3000"; } return "9999"; } }
package cn.chay.filters.pre; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; import javax.servlet.http.HttpServletRequest; public class PreRequestLogFilter extends ZuulFilter { private static final Logger LOGGER = LoggerFactory.getLogger(PreRequestLogFilter.class); @Override public String filterType() { //pre类型过滤器 return FilterConstants.PRE_TYPE; } /** * 返回int值来指定过滤器的执行顺序,不同的过滤器允许相同的数字 * * @return */ @Override public int filterOrder() { // 在org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilter之前执行 return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1; } /** * 返回一个boolean判断该过滤器是否要执行,true表示执行,false表示不执行 * * @return */ @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); PreRequestLogFilter.LOGGER.info(String.format("send %s request to %s", request.getMethod(), request.getRequestURL().toString())); return null; } }
package de.niklaskiefer.bnclCore.parser; import de.niklaskiefer.bnclCore.BPMNModelBuilder; import org.camunda.bpm.model.bpmn.instance.EventBasedGateway; import org.camunda.bpm.model.bpmn.instance.ExclusiveGateway; import org.camunda.bpm.model.bpmn.instance.Gateway; import org.camunda.bpm.model.bpmn.instance.InclusiveGateway; import org.camunda.bpm.model.bpmn.instance.ParallelGateway; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Niklas Kiefer */ public class BnclGatewayParser extends BnclElementParser { private List<GatewayType> gatewayTypes = new ArrayList<>(); public BnclGatewayParser(BPMNModelBuilder builder) { super(builder); initGatewayTypes(); } public BnclGatewayParser() { initGatewayTypes(); } public Gateway parseGateway(String elementString) throws Exception { List<String> withoutSpaces = BnclParser.getWordsWithoutSpaces(elementString); if (!BnclParser.checkWords(withoutSpaces)) { return null; } String first = withoutSpaces.get(0).toLowerCase(); for (GatewayType gatewayType : gatewayTypes) { if (first.equals(gatewayType.getKeyword())) { Map<String, String> attributes = parseAttributes(withoutSpaces); return builder.createGateway(builder.getProcess(), attributes, gatewayType.getType()); } } return null; } private void initGatewayTypes() { gatewayTypes.add(new GatewayType("parallelgateway", ParallelGateway.class)); gatewayTypes.add(new GatewayType("exclusivegateway", ExclusiveGateway.class)); gatewayTypes.add(new GatewayType("inclusivegateway", InclusiveGateway.class)); gatewayTypes.add(new GatewayType("eventbasedgateway", EventBasedGateway.class)); } public List<GatewayType> getGatewayTypes() { return gatewayTypes; } public static class GatewayType { private String keyword; private Class type; private GatewayType(String keyword, Class type) { this.keyword = keyword; this.type = type; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public Class getType() { return type; } public void setType(Class type) { this.type = type; } } }
package com.cit360projectmark4.controller; import com.cit360projectmark4.dao.BaseDao; import com.cit360projectmark4.dao.BaseDaoImpl; import com.cit360projectmark4.pojo.UsersEntity; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RegistrationController extends HttpServlet { private static final long serialVersionUID = 1L; public RegistrationController() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("userRegistration.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("RegistrationController: doPost: starting. SID: " + request.getSession().getId()); String msg = "Password and confirm passwords must be same"; String page = "userRegistration.jsp"; if(request.getParameter("password").equals(request.getParameter("confPassword"))){ System.out.println("RegistrationController: doPost: passwords match"); UsersEntity user = new UsersEntity(); user.setUsername(request.getParameter("username")); user.setPassword(request.getParameter("password")); System.out.println("RegistrationController: doPost: creating user " + user.toString()); BaseDao baseDao = new BaseDaoImpl(); msg = baseDao.register(user); page = "login.jsp"; System.out.println("RegistrationController: doPost: user created"); } request.setAttribute("msg2", msg); System.out.println("RegistrationController: doPost: sending request dispatcher"); request.getRequestDispatcher(page).include(request, response); } }
package com.turios.settings.modules; import javax.inject.Inject; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceManager; import com.turios.R; import com.turios.dagger.DaggerPreferenceFragment; import com.turios.dagger.quialifiers.ForActivity; import com.turios.modules.extend.DirectionsModule; import com.turios.modules.extend.GoogleMapsModule; import com.turios.persistence.Preferences; import com.turios.settings.modules.status.StatusCheck; public class DirectionsSettings extends DaggerPreferenceFragment implements OnSharedPreferenceChangeListener { private static final String TAG = "DirectionsSettings"; @Inject @ForActivity Context context; @Inject Preferences preferences; @Inject GoogleMapsModule googleMapsModule; @Inject DirectionsModule directionsModule; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.settings_module_directions); } @Override public void onStart() { updateAllSummaries(); statusCheck = new StatusCheck(context, directionsModule, this); statusCheck.runCheck(); super.onStart(); } private StatusCheck statusCheck; @Override public void onResume() { PreferenceManager.getDefaultSharedPreferences(context) .registerOnSharedPreferenceChangeListener(this); super.onResume(); } private void updateAllSummaries() { updateMaptypeSummary(); } @Override public void onPause() { PreferenceManager.getDefaultSharedPreferences(context) .unregisterOnSharedPreferenceChangeListener(this); super.onPause(); } @Override public void onSharedPreferenceChanged(SharedPreferences arg0, String key) { if (key.equals(getString(R.string.key_module_activated_directions))) { statusCheck.runCheck(); } updateAllSummaries(); } private void updateMaptypeSummary() { Preference preference = (Preference) findPreference(getString(R.string.key_directions_maptype)); if (preference != null) { int maptype = preferences .getStringInt(R.string.key_directions_maptype); preference.setSummary(googleMapsModule.mapType(maptype)); } } }
package nxpense.helper.serialization; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.joda.time.LocalDate; import java.io.IOException; public class CustomLocalDateSerializer extends JsonSerializer<LocalDate>{ @Override public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException { String localDateString = value.toString(ExpenseDateFormat.BELGIAN.getDatePattern()); jgen.writeString(localDateString); } }
package com.example.zyadzakaria.wev; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by zyadzakaria on 12/4/16. */ public class MyCustomAdapter extends BaseAdapter { private ArrayList<Chat> chats; private LayoutInflater mInflater; public Context mContext; public MyCustomAdapter(Context mContext , ArrayList<Chat> chats) { this.mContext = mContext; mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.chats = chats; } public int getItemViewType(boolean sender) { if(sender==true) return 1; else return 0; } @Override public int getCount() { return chats.size(); } @Override public Object getItem(int i) { return chats.get(i); } @Override public long getItemId(int i) { return 0; } public View getView(int i,View view, ViewGroup viewGroup) { textHolder holder; int type = getItemViewType(((Chat)getItem(i)).isSender()); holder = new textHolder(); switch(type) { case 1: view = mInflater.inflate(R.layout.list_row_layout_even, null); holder.textView = (TextView)view.findViewById(R.id.text1); break; case 0: view = mInflater.inflate(R.layout.list_row_layout_odd, null); holder.textView = (TextView)view.findViewById(R.id.text2); break; } view.setTag(holder); holder.textView.setText(((Chat) getItem(i)).getMessage()); return view; } public static class textHolder { public TextView textView; } }
package eyeq.broiler.entity.passive; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIFollowParent; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIPanic; import net.minecraft.entity.ai.EntityAISwimming; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.Item; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; public class EntityBroiler extends EntityAnimal { public EntityBroiler(World world) { super(world); this.setSize(0.4F, 0.7F); } @Override protected void initEntityAI() { this.tasks.addTask(0, new EntityAISwimming(this)); this.tasks.addTask(1, new EntityAIPanic(this, 1.4)); this.tasks.addTask(4, new EntityAIFollowParent(this, 1.1)); this.tasks.addTask(5, new EntityAIWander(this, 1.0)); this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); this.tasks.addTask(7, new EntityAILookIdle(this)); } @Override public float getEyeHeight() { return this.height; } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(4.0); this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.25); } @Override protected float getSoundPitch() { return 6.0F; } @Override protected SoundEvent getAmbientSound() { return SoundEvents.ENTITY_CHICKEN_AMBIENT; } @Override protected SoundEvent getHurtSound() { return SoundEvents.ENTITY_CHICKEN_HURT; } @Override protected SoundEvent getDeathSound() { return SoundEvents.ENTITY_CHICKEN_DEATH; } @Override protected Item getDropItem() { return Items.COOKED_CHICKEN; } @Override public void updatePassenger(Entity passenger) { super.updatePassenger(passenger); float r = this.renderYawOffset * (float) Math.PI / 180; float sin = MathHelper.sin(r); float cos = MathHelper.cos(r); float xz = 0.1F; float y = 0.0F; passenger.setPosition(this.posX + xz * sin, this.posY + this.height * 0.5 + passenger.getYOffset() + y, this.posZ - xz * cos); if(passenger instanceof EntityLivingBase) { ((EntityLivingBase) passenger).renderYawOffset = this.renderYawOffset; } } @Override public EntityAgeable createChild(EntityAgeable ageable) { return new EntityBroiler(this.world); } }
package model; import javax.persistence.*; import javax.validation.constraints.NotNull; /** * Created by greenlucky on 6/3/17. */ @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @NotNull private String name; private String description; private String author; @ManyToOne private BookType bookType; public Book() { } public Book(String name, String description, String author, BookType bookType) { this.name = name; this.description = description; this.author = author; this.bookType = bookType; } public Book(long id, String name, String description, String author, BookType bookType) { this.id = id; this.name = name; this.description = description; this.author = author; this.bookType = bookType; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public BookType getBookType() { return bookType; } public void setBookType(BookType bookType) { this.bookType = bookType; } public static class BookBuilder { private long id; private String name; private String description; private String author; private BookType bookType; public BookBuilder() { } public BookBuilder(String name, String description, String author, BookType bookType) { this.name = name; this.description = description; this.author = author; this.bookType = bookType; } public BookBuilder setId(long id) { this.id = id; return this; } public BookBuilder setName(String name) { this.name = name; return this; } public BookBuilder setDescription(String description) { this.description = description; return this; } public BookBuilder setAuthor(String author) { this.author = author; return this; } public BookBuilder setBookType(BookType bookType) { this.bookType = bookType; return this; } public Book createBuilder() {return new Book(name, description, author, bookType);} } @Override public String toString() { return "Book{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", author='" + author + '\'' + ", bookType=" + bookType + '}'; } }
package com.staniul.util; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Test; public class TimesTests { @Test public void test () throws Exception { System.out.println(System.currentTimeMillis()); } @Test public void test1 () throws Exception { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); LocalDate dateTime = formatter.parseLocalDate("2017-07-10"); LocalDate date1 = formatter.parseLocalDate("2017-07-10"); System.out.println(dateTime); System.out.println(dateTime.isBefore(date1)); } @Test public void test3 () throws Exception { System.out.println(LocalDate.now().monthOfYear().get()); } }
package com.example.service; import com.example.entity.StudentEntity; import com.example.model.StudentModel; /** * This class is StudentService interface * @author bhupalp * */ public interface StudentService { public StudentEntity insertStudentDetails(StudentModel student); public String updateStudentDetailsByRollNo(StudentModel student,Integer studentId) throws Exception; public String deleteStudentByRollNo(Integer studentId) throws Exception; public StudentEntity getAllDetailsById(Integer sid) throws Exception; }
package com.pinyougou.pojo.group; import com.pinyougou.pojo.TbAddress; import com.pinyougou.pojo.TbAreas; import com.pinyougou.pojo.TbCities; import com.pinyougou.pojo.TbProvinces; import java.io.Serializable; import java.util.List; /** * @program: pinyougou-parent * @description:地址与城市的组合实体类 * @author: Mr.Cai * @create: 2019-07-25 19:27 */ public class AddressList implements Serializable { private TbAddress address;//地址对象 private TbProvinces provinces;//省 private TbCities cities;//城市 private TbAreas areas;//区域 public TbAddress getAddress() { return address; } public void setAddress(TbAddress address) { this.address = address; } public TbProvinces getProvinces() { return provinces; } public void setProvinces(TbProvinces provinces) { this.provinces = provinces; } public TbCities getCities() { return cities; } public void setCities(TbCities cities) { this.cities = cities; } public TbAreas getAreas() { return areas; } public void setAreas(TbAreas areas) { this.areas = areas; } }
package com.jushu.video; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import com.jushu.video.service.IMenuRecommendService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.ArrayList; import java.util.List; @SpringBootTest class VideoServerApplicationTests { @Autowired private IMenuRecommendService iMenuRecommendService; @Test void contextTest(){ Thread t = new Thread() { public void run() { pong(); } }; t.run(); System.out.println("ping"); } static void pong(){ System.out.println("pong"); } @Test void contextLoads() { //代码生成器 AutoGenerator mpg = new AutoGenerator(); //全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("chen"); gc.setOpen(false); mpg.setGlobalConfig(gc); //数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://rm-wz9184d1t788ka987mo.mysql.rds.aliyuncs.com:3306/video_db?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("video"); dsc.setPassword("1qaz@WSX"); dsc.setTypeConvert(new MySqlTypeConvert() { @Override public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) { if(fieldType.toLowerCase().contains("datetime")) { return DbColumnType.DATE; } return (DbColumnType) super.processTypeConvert(globalConfig, fieldType); } }); mpg.setDataSource(dsc); //包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("video"); pc.setParent("com.jushu"); mpg.setPackageInfo(pc); //自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap(){ } }; //如果模板引擎是freemarker String templatePath = "/templates/mapper.xml.ftl"; //自定义输出配置 List<FileOutConfig> focList = new ArrayList<>(); //自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名, 如果你的Entity设置了前后缀、此处注意xml的名称会跟着发生变化 return projectPath + "/src/main/java/com/jushu/video/mapper" + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // //自定义 ListHtml生成 // focList.add(new FileOutConfig(templatePath) { // @Override // public String outputFile(TableInfo tableInfo) { // // 自定义输入文件名称 // return projectPath + "/src/main/resources/templates/" + tableInfo.getEntityName() + "/" +tableInfo.getEntityName() + "List.html"; // } // }); // cfg.setFileOutConfigList(focList); // mpg.setCfg(cfg); // // //自定义 AddHtml生成 // focList.add(new FileOutConfig(templatePath) { // @Override // public String outputFile(TableInfo tableInfo) { // // 自定义输入文件名称 // return projectPath + "/src/main/resources/templates/" + tableInfo.getEntityName() + "/" +tableInfo.getEntityName() + "Add.html"; // } // }); // cfg.setFileOutConfigList(focList); // mpg.setCfg(cfg); // // //自定义 updateHtml生成 // focList.add(new FileOutConfig(templatePath) { // @Override // public String outputFile(TableInfo tableInfo) { // // 自定义输入文件名称 // return projectPath + "/src/main/resources/templates/" + tableInfo.getEntityName() + "/" +tableInfo.getEntityName() + "Update.html"; // } // }); // cfg.setFileOutConfigList(focList); // mpg.setCfg(cfg); //配置模板 TemplateConfig templateConfig = new TemplateConfig(); //配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.vm,会根据使用的模板引擎自动识别 templateConfig.setXml(null); mpg.setTemplate(templateConfig); //策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); //写于父类中的公共字段 // strategy.setSuperEntityColumns(""); String tableNames = "click_record"; strategy.setInclude(tableNames.split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
package com.krt.gov.ir.mapper; import com.krt.common.base.BaseMapper; import com.krt.gov.ir.entity.IrProtocol; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.Map; /** * 红外协议映射层 * * @author zsl * @version 1.0 * @date 2019年08月05日 */ @Mapper public interface IrProtocolMapper extends BaseMapper<IrProtocol> { /** * 通过id查询红外协议 * @param id * @return */ Map selectIrProtocolById(@Param(value = "id") Integer id); }
package com.arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TwoSum { /*public int[] sum(int[] input,int sum) { if(input == null) return null; Map<Integer, Integer> result = new HashMap<Integer, Integer>(); int length = input.length; for(int i=0;i<length;i++) { int complement = sum-input[i]; if(result.containsKey(complement)) { return new int[] {result.get(complement),i}; } result.put(input[i], i); } throw new IllegalArgumentException("No 2 Sum solution found"); }*/ public int[] sum(int[] input, int sum) { if(input ==null) return null; Map<Integer,Integer> complementMap = new HashMap<Integer, Integer>(); int length = input.length; for(int i=0;i<length;i++) { int complement = sum-input[i]; if(complementMap.containsKey(complement)) { return new int[] { complementMap.get(complement),i}; } complementMap.put(input[i], i); } throw new IllegalArgumentException("no 2 sum solution found"); } public void test() { List<Integer> result = new ArrayList<>(); int[] arr = new int[result.size()]; for(int i = 0; i < result.size(); i++) { if (result.get(i) != null) { arr[i] = result.get(i); } } } public static void main(String[] args) { TwoSum ts = new TwoSum(); int[] input = {2, 7, 11, 15}; int sum = 9; int[] result = ts.sum(input, sum); for (int i : result) { System.out.println(i); } } }
package com.trannguyentanthuan2903.yourfoods.product.model; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.trannguyentanthuan2903.yourfoods.R; import com.trannguyentanthuan2903.yourfoods.category.model.Category; import java.util.ArrayList; /** * Created by Administrator on 10/17/2017. */ public class SpinnerAdapter extends BaseAdapter { private ArrayList<Category> arrCategory; private Activity activity; public SpinnerAdapter(ArrayList<Category> arrCategory, Activity activity) { this.arrCategory = arrCategory; this.activity = activity; } @Override public int getCount() { return arrCategory.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = LayoutInflater.from(activity).inflate(R.layout.item_category_spinner, parent, false); TextView txtCategoryName = (TextView) convertView.findViewById(R.id.txtCateoryName_itemSpinner); Category category = arrCategory.get(position); txtCategoryName.setText(category.getCategoryName().toString()); return convertView; } }
package com.hr.login.model; import java.time.Period; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.hr.login.model.LoginModel; public class SecurityLogin implements UserDetails { private static final long serialVersionUID = -6690946490872875352L; private final LoginModel loginModel; public SecurityLogin(LoginModel loginModel) { this.loginModel = loginModel; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(loginModel.getRole())); return authorities; } @Override public String getPassword() { return loginModel.getEmployeePassword(); } @Override public String getUsername() { return loginModel.getEmpNo(); } @Override public boolean isAccountNonExpired() { // return loginModel.getIsAccountNonExpired(); return true; } @Override public boolean isAccountNonLocked() { // return loginModel.getIsAccountNonLocked(); return true; } @Override public boolean isCredentialsNonExpired() { // Date today = new Date(); // // String date = loginModel.getLastChangeCredentialsDate(); // String year = date.substring(0, 4); // String month = date.substring(5, 7); // String day = date.substring(8); // // Date lastChangeDate = new Date(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day)); // Period difference = Period.between(lastChangeDate, today); // int dayDifference = difference.getDays(); // // // return loginModel.getIsCredentialsNonExpired(); return true; } @Override public boolean isEnabled() { return loginModel.getIsEnable(); //return true; } }
package pos.hurrybunny.appsmatic.com.hurrybunnypos.Fragments; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import pos.hurrybunny.appsmatic.com.hurrybunnypos.Activites.MainActivity; import pos.hurrybunny.appsmatic.com.hurrybunnypos.Adabtors.CustomFragmentPagerAdapter; import pos.hurrybunny.appsmatic.com.hurrybunnypos.Fragments.OrdersStatusFragments.CanceledOrdersFrag; import pos.hurrybunny.appsmatic.com.hurrybunnypos.Fragments.OrdersStatusFragments.CompletedOrdersFrag; import pos.hurrybunny.appsmatic.com.hurrybunnypos.Fragments.OrdersStatusFragments.PindingOrdersFrag; import pos.hurrybunny.appsmatic.com.hurrybunnypos.Fragments.OrdersStatusFragments.AcceptedOrdersFrag; import pos.hurrybunny.appsmatic.com.hurrybunnypos.R; public class OrdersFrag extends Fragment { ViewPager p; TabLayout tabsStrip; CustomFragmentPagerAdapter adapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_orders, container, false); } @Override public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); adapter = new CustomFragmentPagerAdapter(getChildFragmentManager()); PindingOrdersFrag pindingOrdersFrag =new PindingOrdersFrag(); AcceptedOrdersFrag proseccingOrdersFrag =new AcceptedOrdersFrag(); CanceledOrdersFrag canceledOrdersFrag =new CanceledOrdersFrag(); CompletedOrdersFrag completedOrdersFrag =new CompletedOrdersFrag(); adapter.addFragment(pindingOrdersFrag, getResources().getString(R.string.wait)); adapter.addFragment(proseccingOrdersFrag, getResources().getString(R.string.accepted)); adapter.addFragment(canceledOrdersFrag, getResources().getString(R.string.canceld)); adapter.addFragment(completedOrdersFrag, getResources().getString(R.string.completed)); p=(ViewPager)view.findViewById(R.id.viewpager_presentcards); tabsStrip = (TabLayout) view.findViewById(R.id.orders_tabs); p.setAdapter(adapter); tabsStrip.setupWithViewPager(p); adapter.notifyDataSetChanged(); tabsStrip.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { Log.e("key",tab.getPosition()+""); MainActivity.selectedTap=tab.getPosition(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { Log.e("key",tab.getPosition()+""); MainActivity.selectedTap=tab.getPosition(); } }); tabsStrip.getTabAt(MainActivity.selectedTap).select(); } }
import java.io.PrintWriter; import java.util.*; public class Society { private int sizeOfPopulation; private int healthy; private int infected; private int immune; private int dead; private double probOfExtrovert; private double averageNumberOfFriends; private double probOfMeeting; private List<Agent> agents; private void setAttributes(int sizeOfPopulation, double probOfExtrovert, double averageNumberOfFriends, double probOfMeeting) { this.sizeOfPopulation = sizeOfPopulation; this.probOfExtrovert = probOfExtrovert; this.averageNumberOfFriends = averageNumberOfFriends; this.probOfMeeting = probOfMeeting; healthy = sizeOfPopulation - 1; infected = 1; immune = 0; dead = 0; } private void drawAgents(Random r) { agents = new ArrayList<>(sizeOfPopulation); double agentType; for(int i = 0; i < sizeOfPopulation; i++) { agentType = r.nextDouble(); if(agentType <= probOfExtrovert) { agents.add(i, new Extrovert(i + 1, probOfMeeting)); } else { agents.add(i, new Common(i + 1, probOfMeeting)); } } agents.get(r.nextInt(sizeOfPopulation)).infect(); } //tworzy listę wszystkich możliwych krawędzi (przyjaźni) //tasuje ją metodą shuffle //i zdejmuje pierwszych n (n == śrLiczbaZnajomych * liczbaAgentów) krawędzi //metoda dobra dla niedużych grafów (inaczej złożona czasowoi bardzo złożona pamięciowo - lista krawędzi jest kwadratowa względem liczby wierzchołków...) private void drawGraphOfConnections() { int sumOfFriends = (int)Math.round(sizeOfPopulation * averageNumberOfFriends); List<Edge> edges = new LinkedList<>(); for(int i = 0; i < agents.size(); i++) { for(int j = i + 1; j < agents.size(); j++) { edges.add(new Edge(agents.get(i), agents.get(j))); } } Collections.shuffle(edges); for(int i = 0; i < sumOfFriends; i += 2) { edges.remove(0).setEdge(); } } //metoda dobra, gdy grafy nie są "bliskie klice" //losuje jeden wierzchołek, aż wylosuje jakiś, który jeszcze nie ma wszystkich możliwych znajomych //losuje drugi wierzchołek, aż natrafi na jakiś, który jeszcze nie jest zaprzyjaźniony z pierwszym (i sam nie jest pierwszym) //chyba nie ma gwarancji rokładu normalnego (niektóre krawedzie mogą m private void drawGraph(Random r) { int sumOfFriends = (int)Math.round(sizeOfPopulation * averageNumberOfFriends); for(int i = 0; i < sumOfFriends; i += 2) { Agent a, b; while((a = agents.get(r.nextInt(agents.size()))).getFriendsNumber() == sizeOfPopulation - 1); while(a.isFriend(b = agents.get(r.nextInt(agents.size()))) || a == b); a.addFriend(b); b.addFriend(a); } } //metoda podobna do poprzedniej private void drawGrApH(Random r) { int sumOfFriends = (int)Math.round(sizeOfPopulation * averageNumberOfFriends); for(int i = 0; i < sumOfFriends; i += 2) { Agent a = null, b = null; //inaczej kompilator daje warning, że a || b mogą być niezainicjalizowane... boolean edge_set = false; while(!edge_set) { a = agents.get(r.nextInt(agents.size())); b = agents.get(r.nextInt(agents.size())); if(a != b && !a.isFriend(b)) edge_set = true; } a.addFriend(b); b.addFriend(a); } } public Society(int sizeOfPopulation, double probOfExtrovert, double averageNumberOfFriends, double probOfMeeting, Random r) { setAttributes(sizeOfPopulation, probOfExtrovert, averageNumberOfFriends, probOfMeeting); drawAgents(r); //drawGrApH(r); //drawGraphOfConnections(); drawGraph(r); } public void increaseInfected(int newly_infected) { infected += newly_infected; } public void decreaseHealthy(int newly_infected) { healthy -= newly_infected; } public void drawDeaths(Epidemic e, Random r) { Iterator<Agent> it = agents.iterator(); Agent a; while(it.hasNext()) { a = it.next(); if(a.isInfected() && r.nextDouble() <= e.getProbOfDeath()) { a.kill(); it.remove(); dead++; infected--; } } } public void drawRecoveries(Epidemic e, Random r) { Iterator<Agent> it = agents.iterator(); Agent a; while(it.hasNext()) { a = it.next(); if(a.isInfected() && r.nextDouble() <= e.getProbOfRecovery()) { a.cure(); immune++; infected--; } } } public void drawMeetings(Day[] days, Random r) { Iterator<Agent> it = agents.iterator(); for(Agent a: agents) { a.drawMeetings(days, r); } } public String Summary() { return healthy + " " + infected + " " + immune; } public void printGraph(PrintWriter writer) { writer.println("# graf"); Iterator<Agent> it = agents.iterator(); while(it.hasNext()) { it.next().print(writer); } writer.println(); } public void printAgents(PrintWriter writer) { writer.println("# agenci jako: id typ lub id* typ dla chorego"); Iterator<Agent> it = agents.iterator(); int i = 1; Agent a; while(it.hasNext()) { writer.format("%d", i++); a = it.next(); if(a.isInfected()) writer.format("*"); if(a instanceof Extrovert) { writer.println(" towarzyski"); } else { writer.println(" zwykły"); } } writer.println(); } }
/* * Copyright 2002-2023 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.web.servlet.view.xml; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamResult; import jakarta.xml.bind.JAXBElement; import org.junit.jupiter.api.Test; import org.springframework.oxm.Marshaller; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; import org.springframework.web.testfixture.servlet.MockHttpServletRequest; import org.springframework.web.testfixture.servlet.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Arjen Poutsma * @author Juergen Hoeller */ class MarshallingViewTests { private Marshaller marshallerMock = mock(); private MarshallingView view = new MarshallingView(marshallerMock); @Test void getContentType() { assertThat(view.getContentType()).as("Invalid content type").isEqualTo("application/xml"); } @Test void isExposePathVars() { assertThat(view.isExposePathVariables()).as("Must not expose path variables").isFalse(); } @Test void isExposePathVarsDefaultConstructor() { assertThat(new MarshallingView().isExposePathVariables()).as("Must not expose path variables").isFalse(); } @Test void renderModelKey() throws Exception { Object toBeMarshalled = new Object(); String modelKey = "key"; view.setModelKey(modelKey); Map<String, Object> model = new HashMap<>(); model.put(modelKey, toBeMarshalled); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(Object.class)).willReturn(true); marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class)); view.render(model, request, response); assertThat(response.getContentType()).as("Invalid content type").isEqualTo("application/xml"); assertThat(response.getContentLength()).as("Invalid content length").isEqualTo(0); } @Test void renderModelKeyWithJaxbElement() throws Exception { String toBeMarshalled = "value"; String modelKey = "key"; view.setModelKey(modelKey); Map<String, Object> model = new HashMap<>(); model.put(modelKey, new JAXBElement<>(new QName("model"), String.class, toBeMarshalled)); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(String.class)).willReturn(true); marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class)); view.render(model, request, response); assertThat(response.getContentType()).as("Invalid content type").isEqualTo("application/xml"); assertThat(response.getContentLength()).as("Invalid content length").isEqualTo(0); } @Test void renderInvalidModelKey() throws Exception { Object toBeMarshalled = new Object(); String modelKey = "key"; view.setModelKey("invalidKey"); Map<String, Object> model = new HashMap<>(); model.put(modelKey, toBeMarshalled); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); assertThatIllegalStateException().isThrownBy(() -> view.render(model, request, response)); assertThat(response.getContentLength()).as("Invalid content length").isEqualTo(0); } @Test void renderNullModelValue() throws Exception { String modelKey = "key"; Map<String, Object> model = new HashMap<>(); model.put(modelKey, null); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); assertThatIllegalStateException().isThrownBy(() -> view.render(model, request, response)); assertThat(response.getContentLength()).as("Invalid content length").isEqualTo(0); } @Test void renderModelKeyUnsupported() throws Exception { Object toBeMarshalled = new Object(); String modelKey = "key"; view.setModelKey(modelKey); Map<String, Object> model = new HashMap<>(); model.put(modelKey, toBeMarshalled); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(Object.class)).willReturn(false); assertThatIllegalStateException().isThrownBy(() -> view.render(model, request, response)); } @Test void renderNoModelKey() throws Exception { Object toBeMarshalled = new Object(); String modelKey = "key"; Map<String, Object> model = new HashMap<>(); model.put(modelKey, toBeMarshalled); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(Object.class)).willReturn(true); view.render(model, request, response); assertThat(response.getContentType()).as("Invalid content type").isEqualTo("application/xml"); assertThat(response.getContentLength()).as("Invalid content length").isEqualTo(0); verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class)); } @Test void renderNoModelKeyAndBindingResultFirst() throws Exception { Object toBeMarshalled = new Object(); String modelKey = "key"; Map<String, Object> model = new LinkedHashMap<>(); model.put(BindingResult.MODEL_KEY_PREFIX + modelKey, new BeanPropertyBindingResult(toBeMarshalled, modelKey)); model.put(modelKey, toBeMarshalled); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(BeanPropertyBindingResult.class)).willReturn(true); given(marshallerMock.supports(Object.class)).willReturn(true); view.render(model, request, response); assertThat(response.getContentType()).as("Invalid content type").isEqualTo("application/xml"); assertThat(response.getContentLength()).as("Invalid content length").isEqualTo(0); verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class)); } @Test void testRenderUnsupportedModel() throws Exception { Object toBeMarshalled = new Object(); String modelKey = "key"; Map<String, Object> model = new HashMap<>(); model.put(modelKey, toBeMarshalled); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(Object.class)).willReturn(false); assertThatIllegalStateException().isThrownBy(() -> view.render(model, request, response)); } }
import java.io.*; import java.util.*; public class Main { static Scanner in = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { long n = in.nextLong(); long k = in.nextLong(); long remaining = n - k * (k + 1) / 2; // out.println("sum: " + (k * (k + 1) / 2)); // out.println("remaining: " + remaining); boolean OK = remaining >= 0; if (!OK) out.println("NO"); else { long[] ans = new long[(int)k]; long dividen = remaining / k; for (int i = 0; i < k; i++) { ans[i] = i + 1; if (dividen > 0) { ans[i] += dividen; remaining -= dividen; } } long counter = k; while (remaining > 0 && counter >= 1) { long take = Math.min(remaining, ans[(int)counter - 2] - 1); // out.println("take: " + take); if (take < 0) { OK = false; break; } ans[(int)counter - 1] += take; remaining -= take; counter--; } if (OK) { out.println("YES"); for (int i = 0; i < k; i++) { out.print(ans[i] + " "); } } else { out.println("NO"); } } in.close(); out.close(); } }
package br.com.metodo.service.vo; import java.io.Serializable; import org.codehaus.jettison.json.JSONObject; public class Favorito implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private int id; private String nome; private String urlImagem; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getUrlImagem() { return urlImagem; } public void setUrlImagem(String urlImagem) { this.urlImagem = urlImagem; } public JSONObject toJson(){ JSONObject json = new JSONObject(); json.put("id",String.valueOf(getId())); json.put("nome",getNome()); json.put("urlImagem",getUrlImagem()); return json; } }
import java.util.*; public class TriesNode { String character; List<Map<String, Object>> location; Map<String,TriesNode> children; HashSet<String> orn; public TriesNode() { //character = ""; children = new HashMap<>(); location = new LinkedList<>(); orn = new HashSet<>(); } public TriesNode(String a) { character = a; children = new HashMap<>(); location = new LinkedList<>(); orn = new HashSet<>(); } public void insert (TriesNode root, String name, Map<String, Object> value) { TriesNode node = root; int i = 0; String cleanname = new String(name); cleanname = GraphDB.cleanString(cleanname); while (i < cleanname.length()) { //String test = GraphDB.cleanstringAlter(String.valueOf(name.charAt(i))); /*if (test == "") { System.out.println("I met a space"); }*/ String t = String.valueOf(cleanname.charAt(i)); if (node.children.containsKey(t)) { node = node.children.get(t); i++; //System.out.println("a"); } else { break; } } while (i < cleanname.length()) { //System.out.println("d"); String a = String.valueOf(cleanname.charAt(i)); node.children.put(a , new TriesNode(a)); //System.out.println("b"); node = node.children.get(a); i++; //System.out.println("c"); } node.location.add(value); node.orn.add(name); } public List<Map<String, Object>> find (String key) { TriesNode node = this; String clk = GraphDB.cleanString(key); for (int i = 0; i < clk.length(); i++) { String a = GraphDB.cleanString(String.valueOf(clk.charAt(i))); //System.out.println(GraphDB.cleanString(a)); if (node.children.containsKey(a)) { node = node.children.get(a); } else { //System.out.println("n"); return null; } } return node.location; } public List<String> prefixname (TriesNode n, String pre) { String cleanpre; //System.out.println(pre); cleanpre = GraphDB.cleanString(pre); TriesNode node = n; for (int i = 0; i < cleanpre.length(); i++) { String b = GraphDB.cleanString(String.valueOf(cleanpre.charAt(i))); if (node.children.containsKey(b)) { node = node.children.get(b); } else { return null; } } List<String> result; result = prefixhelper(node); return result; } private List<String> prefixhelper (TriesNode n) { List<String> result = new LinkedList<>(); if (n.children.isEmpty()) { for (String t : n.orn) result.add(t); return result; } Set<String> a = n.children.keySet(); for (String i : a) { if (!n.orn.isEmpty()) { for (String t : n.orn) result.add(t); } List<String> mid = prefixhelper(n.children.get(i)); for (String j : mid) result.add(j); } return result; } }
package com.example.consultants.week4daily2.model.data; import android.util.Log; import com.example.consultants.week4daily2.model.data.local.LocalDataSource; import com.example.consultants.week4daily2.model.data.remote.RemoteDataSource; import com.example.consultants.week4daily2.model.data.remote.RemoteObserver; import com.example.consultants.week4daily2.model.githubresponse.GithubResponse; import com.example.consultants.week4daily2.ui.github.GithubContract; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class GithubRepository { public static final String TAG = GithubRepository.class.getSimpleName() + "_TAG"; LocalDataSource localDataSource; RemoteDataSource remoteDataSource; public GithubRepository(LocalDataSource localDataSource, RemoteDataSource remoteDataSource) { this.localDataSource = localDataSource; this.remoteDataSource = remoteDataSource; } public RemoteDataSource getRemoteDataSource() { return remoteDataSource; } public LocalDataSource getLocalDataSource() { return localDataSource; } //unused, as I moved this logic to be done in presenter for now public void getUserInfo(String login) { Log.d(TAG, "getUserInfo: "); remoteDataSource.getUserInfo(login).enqueue(new Callback<GithubResponse>() { @Override public void onResponse(Call<GithubResponse> call, Response<GithubResponse> response) { if (response.body() != null) { //I get a correct response here in logs, but didn't know how to get this value back to main UI Log.d(TAG, "onResponse: "+ response.body().getCompany()); } } @Override public void onFailure(Call<GithubResponse> call, Throwable t) { } }); } public void getRepos(String login, final RepoCallback callback) { remoteDataSource.getRepositoriesObs(login) // make the network call on the worker thread .subscribeOn(Schedulers.io()) // get the results back on the main thread .observeOn(AndroidSchedulers.mainThread()) .subscribe(new RemoteObserver(callback)); } }
package msip.go.kr.member.web; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import egovframework.com.cmm.EgovMessageSource; import egovframework.com.cmm.LoginVO; import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper; import msip.go.kr.common.entity.Tree; import msip.go.kr.member.entity.FvrtGroup; import msip.go.kr.member.entity.FvrtMember; import msip.go.kr.member.service.FvrtGroupService; import msip.go.kr.member.service.FvrtMemberService; /** * 나의그룹 관리 Controller * * @author 양준호 * @since 2015.07.15 * @see <pre> * == 개정이력(Modification Information) == * * 수정일 수정자 수정내용 * --------------------------------------------------------------------------------- * 2015.07.15 양준호 최초생성 * * </pre> */ @Controller public class FvrtGroupController { @Resource(name = "fvrtGroupService") private FvrtGroupService fvrtGroupService; @Resource(name = "fvrtMemberService") private FvrtMemberService fvrtMemberService; @Resource(name="egovMessageSource") EgovMessageSource egovMessageSource; /** * 나의 그룹 등록 * * @param entity * @param model * @return * @throws Exception */ @RequestMapping(value = "/fvrt/group/regist", method = RequestMethod.POST) @ResponseBody public String regist(FvrtGroup entity, ModelMap model) throws Exception { String message = egovMessageSource.getMessage("success.common.insert"); try { // 로그인VO에서 사용자 정보 가져오기 LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); entity.setRegistInfo(loginVO); entity.setRegDate(new Date()); fvrtGroupService.persist(entity); } catch (Exception e) { e.printStackTrace(); message = egovMessageSource.getMessage("fail.common.insert"); } return message; } @RequestMapping(value = "/fvrt/group/{id}", method = RequestMethod.GET) @ResponseBody public FvrtGroup find(@PathVariable Long id, ModelMap model) throws Exception { FvrtGroup entity = null; try { entity = fvrtGroupService.findById(id); } catch (Exception e) { e.printStackTrace(); } return entity; } @RequestMapping(value = "/fvrt/group/update", method = RequestMethod.POST) @ResponseBody public String update(FvrtGroup entity, ModelMap model) throws Exception { String message = egovMessageSource.getMessage("success.common.update"); try { // 로그인VO에서 사용자 정보 가져오기 LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); fvrtGroupService.merge(entity); } catch (Exception e) { e.printStackTrace(); message = egovMessageSource.getMessage("fail.common.update"); } return message; } @RequestMapping(value = "/fvrt/group/remove", method = RequestMethod.POST) @ResponseBody public String remove(FvrtGroup entity, ModelMap model) throws Exception { String message = egovMessageSource.getMessage("success.common.delete"); try { // 로그인VO에서 사용자 정보 가져오기 LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); fvrtGroupService.remove(entity); } catch (Exception e) { e.printStackTrace(); message = egovMessageSource.getMessage("fail.common.delete"); } return message; } @RequestMapping(value = "/fvrt/member/regist", method = RequestMethod.POST) @ResponseBody public String addMember(Long groupId, String[] esntlId, Model model) throws Exception { String message = egovMessageSource.getMessage("success.common.insert"); try { LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); List<FvrtMember> list = fvrtMemberService.findAll(groupId); for(String id : esntlId) { FvrtMember entity = new FvrtMember(); entity.setGroupId(groupId); entity.setEsntlId(id); entity.setRegistInfo(loginVO); boolean insertable = true; for(FvrtMember member : list) { if(member.getEsntlId().equals(entity.getEsntlId())) { insertable = false; } } if(insertable) fvrtMemberService.persist(entity); } } catch (Exception e) { e.printStackTrace(); message = egovMessageSource.getMessage("fail.common.insert"); } return message; } @RequestMapping(value = "/fvrt/member/remove", method = RequestMethod.POST) @ResponseBody public String removeMember(@RequestParam(value="ids[]") List<Long> ids, Model model) throws Exception { String message = egovMessageSource.getMessage("success.common.delete"); try { for(Long id : ids) { FvrtMember entity = new FvrtMember(); entity.setId(id); fvrtMemberService.remove(id); } } catch (Exception e) { e.printStackTrace(); message = egovMessageSource.getMessage("fail.common.delete"); } return message; } @RequestMapping(value = "/organ/fvrt/tree", method = RequestMethod.GET) @ResponseBody public List<Tree> tree(Model model) throws Exception { List<Tree> list = fvrtGroupService.treeList(); return list; } }
package com.cs.control; import com.cs.persistence.NotFoundException; import com.cs.security.AccessDeniedException; import com.cs.system.SystemControl; import com.cs.system.WhiteListedEmail; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import static org.springframework.transaction.annotation.Isolation.READ_COMMITTED; /** * @author Omid Alaepour */ @Service @Transactional(isolation = READ_COMMITTED) public class SystemControlServiceImpl implements SystemControlService { private final SystemControlRepository systemControlRepository; @Autowired public SystemControlServiceImpl(final SystemControlRepository systemControlRepository) { this.systemControlRepository = systemControlRepository; } private SystemControl getSystemControl() { final SystemControl systemControl = systemControlRepository.findOne(SystemControl.ID); if (systemControl == null) { throw new NotFoundException("System control settings not available"); } return systemControl; } @Override public void validateRegistrationAllowed(final String email) { if (checkEmail(email)) { return; } if (!getSystemControl().getRegistrationEnabled()) { throw new AccessDeniedException("Registration is disabled"); } } @Override public boolean validateLoginAllowed(final String email) { return checkEmail(email) ? true : getSystemControl().getLoginEnabled(); } @Override public boolean isBrontoEnabled() { return getSystemControl().getBrontoEnabled(); } private boolean checkEmail(final String email) { return WhiteListedEmail.isWhiteListed(email); } }
package com.alibaba.druid.bvt.sql.transform.datatype.oracle2pg; import com.alibaba.druid.sql.SQLTransformUtils; import com.alibaba.druid.sql.ast.SQLDataType; import com.alibaba.druid.sql.parser.SQLParserUtils; import com.alibaba.druid.util.JdbcConstants; import junit.framework.TestCase; public class Oracle2PG_DataTypeTest_int extends TestCase { public void test_oracle2pg_int() throws Exception { String sql = "int"; SQLDataType dataType = SQLParserUtils.createExprParser(sql, JdbcConstants.ORACLE).parseDataType(); SQLDataType pgDataType = SQLTransformUtils.transformOracleToPostgresql(dataType); assertEquals("DECIMAL(38)", pgDataType.toString()); } public void test_oracle2pg_integer() throws Exception { String sql = "integer"; SQLDataType dataType = SQLParserUtils.createExprParser(sql, JdbcConstants.ORACLE).parseDataType(); SQLDataType pgDataType = SQLTransformUtils.transformOracleToPostgresql(dataType); assertEquals("DECIMAL(38)", pgDataType.toString()); } public void test_oracle2pg_smallint() throws Exception { String sql = "smallint"; SQLDataType dataType = SQLParserUtils.createExprParser(sql, JdbcConstants.ORACLE).parseDataType(); SQLDataType pgDataType = SQLTransformUtils.transformOracleToPostgresql(dataType); assertEquals("SMALLINT", pgDataType.toString()); } }
package cn.test.classes; /* * 类作为方法参数 */ public class TestArguments { public static void main(String[] args) { Person p = new Person(); method(p); } public static void method(Person p) { p.eat(); p.run(); } }
package week1_Q1; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; /** * * @author CIT-Labs * * compute the number of inversions in the file given * */ public class Question1 { //static List<Integer> numbers = new ArrayList<Integer>(); public static int[] convertIntegers(List<Integer> integers) { int[] ret = new int[integers.size()]; for (int i=0; i < ret.length; i++) { ret[i] = integers.get(i).intValue(); } return ret; } public static int[] readFileByLines( String filename ) throws IOException{ File file = new File(filename); BufferedReader reader = null; List<Integer> numbers = new ArrayList<Integer>(); try{ reader = new BufferedReader(new FileReader(file)); String tempString = null; while((tempString = reader.readLine()) != null){ numbers.add(Integer.parseInt(tempString)); //System.out.println(tempString); } } catch (IOException e) { e.printStackTrace(); } return convertIntegers(numbers); } public static long merge(int[] arr, int[] left, int [] right) { int i = 0; int j = 0; long count = 0; while ( i < left.length || j < right.length) { if ( i == left.length){ arr[i+j] = right[j]; j++; } else if ( j == right.length ) { arr[i+j] = left[i]; i++; } else if (left[i] <= right[j]){ arr[i+j] = left[i]; i++; } else if (right[j] < left[i]){ arr[i+j] = right[j]; j++; count += left.length - i; } } return count; } public static long invCount( int[] arr) { if (arr.length < 2) return 0; int m = (arr.length + 1) /2; int left[] = Arrays.copyOfRange(arr, 0, m); int right[] = Arrays.copyOfRange(arr, m, arr.length); return invCount(left) + invCount(right) + merge(arr, left, right); } public static void main(String[] args) throws IOException { int[] numArray = readFileByLines("C:/Users/cit-labs/Downloads/IntegerArray.txt"); System.out.println("====================="); System.out.print(invCount(numArray)); // TODO Auto-generated method stub } }
/*********************************************************** * @Description : 数据库日志工厂 * @author : 梁山广(Liang Shan Guang) * @date : 2020/5/17 14:44 * @email : liangshanguang2@gmail.com ***********************************************************/ package 第04章_工厂方法模式.第3节_应用举例; public class FileLoggerFactory extends LoggerFactory{ @Override public Logger createLogger() { // 创建文件日志记录器 Logger logger = new FileLogger(); // 创建文件,代码省略 return logger; } @Override public Logger createLogger(String args) { // 使用字符串args做些初始化的工作 // 创建文件日志记录器 Logger logger = new FileLogger(); // 创建文件,代码省略 return logger; } @Override public Logger createLogger(Object obj) { // 使用对象obj里面的属性做些初始化的工作 // 创建文件日志记录器 Logger logger = new FileLogger(); // 创建文件,代码省略 return logger; } }
package com.karya.dao.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.karya.dao.ICompanyandAccountsDao; import com.karya.model.AccGenLedge001MB; import com.karya.model.AccountChart001MB; import com.karya.model.CompanyAccounts001MB; import com.karya.model.JournalEntry001MB; @Repository @Transactional public class CompanyandAccountsDAoImpl implements ICompanyandAccountsDao{ @PersistenceContext private EntityManager entityManager; public void addaccgenledge(AccGenLedge001MB accgenledge001mb) { entityManager.merge(accgenledge001mb); } @SuppressWarnings("unchecked") public List<AccGenLedge001MB> listaccgenledge() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<AccGenLedge001MB> cq = builder.createQuery(AccGenLedge001MB.class); Root<AccGenLedge001MB> root = cq.from(AccGenLedge001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public AccGenLedge001MB getaccgenledge(int accglId) { AccGenLedge001MB accgenledge001mb = entityManager.find(AccGenLedge001MB.class, accglId); return accgenledge001mb; } public void deleteaccgenledge(int accglId) { AccGenLedge001MB accgenledge001mb = entityManager.find(AccGenLedge001MB.class, accglId); entityManager.remove(accgenledge001mb); } //Journal Entry public void addjournalentry(JournalEntry001MB journalentry001mb) { entityManager.merge(journalentry001mb); } @SuppressWarnings("unchecked") public List<JournalEntry001MB> listjournalentry() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<JournalEntry001MB> cq = builder.createQuery(JournalEntry001MB.class); Root<JournalEntry001MB> root = cq.from(JournalEntry001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public JournalEntry001MB getjournalentry(int jeId) { JournalEntry001MB journalentry001mb = entityManager.find(JournalEntry001MB.class, jeId); return journalentry001mb; } public void deletejournalentry(int jeId) { JournalEntry001MB journalentry001mb = entityManager.find(JournalEntry001MB.class, jeId); entityManager.remove(journalentry001mb); } //Account charts public void addaccountchart(AccountChart001MB accountchart001mb) { entityManager.merge(accountchart001mb); } @SuppressWarnings("unchecked") public List<AccountChart001MB> listaccountchart() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<AccountChart001MB> cq = builder.createQuery(AccountChart001MB.class); Root<AccountChart001MB> root = cq.from(AccountChart001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public AccountChart001MB getaccountchart(int chartId) { AccountChart001MB accountchart001mb = entityManager.find(AccountChart001MB.class, chartId); return accountchart001mb; } public void deleteaccountchart(int chartId) { AccountChart001MB accountchart001mb = entityManager.find(AccountChart001MB.class, chartId); entityManager.remove(accountchart001mb); } //Company Accounts public void addcompanyaccounts(CompanyAccounts001MB companyaccounts001mb) { entityManager.merge(companyaccounts001mb); } @SuppressWarnings("unchecked") public List<CompanyAccounts001MB> listcompanyaccounts() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<CompanyAccounts001MB> cq = builder.createQuery(CompanyAccounts001MB.class); Root<CompanyAccounts001MB> root = cq.from(CompanyAccounts001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public CompanyAccounts001MB getcompanyaccounts(int caId) { CompanyAccounts001MB companyaccounts001mb = entityManager.find(CompanyAccounts001MB.class, caId); return companyaccounts001mb; } public void deletecompanyaccounts(int caId) { CompanyAccounts001MB companyaccounts001mb = entityManager.find(CompanyAccounts001MB.class, caId); entityManager.remove(companyaccounts001mb); } }
package edu.kis.vh.nursery; import edu.kis.vh.nursery.stacks.IIntStack; import edu.kis.vh.nursery.stacks.IntLinkedList; /** * Klasa HanoiRhymer rozszerza klase DefaultCountingOutRhymer */ public class HanoiRhymer extends DefaultCountingOutRhymer { private int totalRejected = 0; public HanoiRhymer(IIntStack iIntStack) { super(iIntStack); } public HanoiRhymer() { super(); } /**Metoda zwraca nam wartosc int totalRejected * * @return totalRejected */ public int reportRejected() { return totalRejected; } /** * Sprawdza czy liczba wieksza od peekaboo() * @param in oznacza liczbe do sprawdzenia */ @Override public void countIn(int in) { if (!callCheck() && in > peekaboo()) totalRejected++; else super.countIn(in); } }
package nature; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import lem.LemGui; import org.junit.Before; import org.junit.Test; public class GodTest { private God god; @Before public void init() { god = new God(); } @Test public void createsTime() { god.day1(); assertNotNull(god.getTime()); assertTrue(god.getTime().isStarted()); } @Test public void createsPhysicalLaw() { god.day1(); god.day2(); assertNotNull(god.getNewton()); } @Test public void makesTheWorldMovable() { god.day1(); Time timeMock = mock(Time.class); god.setTime(timeMock); god.day2(); verify(timeMock).addObserver(god.getNewton()); } @Test public void createsLemConcept() { god.day1(); god.day2(); god.day3(); assertEquals(god.getLem(), god.getNewton().getLem()); assertEquals(god.getLem().getAltitude(), 50); } @Test public void makesLemTangible() { god.day1(); god.day2(); god.day3(); god.day4(); assertNotNull(god.getLemGui()); } @Test public void givesLife() { god.day1(); god.day2(); god.day3(); god.day4(); LemGui guiMock = mock(LemGui.class); god.setLemGui(guiMock); god.day5(); verify(god.getLemGui()).update(anyInt()); } @Test public void createsLight() { god.day1(); god.day2(); god.day3(); god.day4(); god.day5(); god.day6(); assertTrue(god.getLemGui().isVisible()); assertTrue(god.getLemGui().getWidth() > 0); assertTrue(god.getLemGui().getHeight() > 0); } @Test public void justRelax() { god.day7(); } }
package com.izasoft.jcart.web.contoller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ModelAttribute; import com.izasoft.jcart.common.service.JCLogger; import com.izasoft.jcart.security.AuthenticatedUser; public abstract class JCartAdminBaseContoller { @Autowired private MessageSource messageSource; protected final JCLogger logger = JCLogger.getLogger(getClass()); protected abstract String getHeaderTitle(); public String getMessage(String code) { return messageSource.getMessage(code, null, null); } public String getMessage(String code, String defaultMsg) { return messageSource.getMessage(code, null, defaultMsg, null); } @ModelAttribute("authenticatedUser") public AuthenticatedUser authenticatedUser(@AuthenticationPrincipal AuthenticatedUser authenticatedUser) { return authenticatedUser; } public static AuthenticatedUser getCurrentUser() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if(principal instanceof AuthenticatedUser ) { return (AuthenticatedUser) principal; } return null; } public static boolean isLoggedIn() { return getCurrentUser()!=null; } }
package id.barkost.waris; public class MateriAhliAdapter { private String name; public MateriAhliAdapter(){ super(); } public MateriAhliAdapter(String name) { super(); this.name = name; } @Override public String toString() { return this.name; } }
package com.logzc.webzic.reflection.fs; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Objects; /** * The abstract Dir base class of ZicFs. * Created by lishuang on 2016/7/17. */ public abstract class ZicDir { public abstract String getPath(); public abstract Collection<ZicFile> getFiles(); public static ZicDir fromURL(URL url) { Objects.requireNonNull(url); String protocol = url.getProtocol(); if (protocol.equals("file")) { String path = url.getPath(); if (path.endsWith(".jar")) { try { URL jarUrl = new URL("jar:file:" + path + "!/"); return new JarInputDir(jarUrl); } catch (MalformedURLException e) { throw new RuntimeException("convert to jar url error"); } } else { return new SystemDir(url); } } else if (protocol.equals("jar")) { return new JarInputDir(url); } else { throw new RuntimeException("Not support the url protocol of " + protocol); } } }
package com.finalyearproject.spring.web.dao; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.finalyearproject.spring.web.entity.Forum; import com.finalyearproject.spring.web.entity.User; public class ForumRowMapper implements RowMapper<Forum>{ @Override public Forum mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setAuthority(rs.getString("authority")); user.setEnabled(true); user.setFirstName(rs.getString("firstName")); user.setLastName(rs.getString("lastName")); user.setUsername(rs.getString("username")); Forum forum = new Forum(); forum.setId(rs.getInt("id")); forum.setForumTitle(rs.getString("forumTitle")); forum.setForumContent(rs.getString("forumContent")); forum.setUser(user); return forum; } }
package cn.newsuper.Demo; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.Ignition; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import java.util.Arrays; import java.util.Scanner; /** * Created by Administrator on 2018/3/15. */ public class Demo1 { private static Integer test_rows =5000; private static Integer thread_num=200; private static Ignite ignite; public static void main(String[] args) { keyMap(); ignite = getIgnite(); // testWrite(); testRead(); System.out.println("线程数"+thread_num+"数据量:"+test_rows); ignite.close(); } /*** * 键盘设置参数 * @return */ private static void keyMap(){ //测试数据行数 System.out.println("测试数据行数"); Scanner sc1 = new Scanner(System.in); test_rows = sc1.nextInt(); //测试线程数 // System.out.println("测试线程数:"); // Scanner sc2 = new Scanner(System.in); // thread_num= sc2.nextInt(); } private static void testWrite(){ Thread[] threads = new Thread[thread_num]; final long start = System.currentTimeMillis(); IgniteCache<String,String> cache = ignite.getOrCreateCache("Ignite_test"); for (int i =0;i<threads.length;i++){ threads[i] = new Thread(new IgniteThread(false, cache)); } for (int i = 0; i<threads.length;i++){ threads[i].start(); } for (Thread thread:threads){ try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } final long end = System.currentTimeMillis(); float times = end-start; float count = (float)test_rows/times; System.out.println("插入数据花费时间:"+(end-start)+"ms"); System.out.println("每秒插入数据量:"+count*1000); } private static void testRead(){ Thread[] read_Thread = new Thread[thread_num]; final long start = System.currentTimeMillis(); IgniteCache<String,String> cache = ignite.getOrCreateCache("Ignite_test"); for (int i =0;i<read_Thread.length;i++){ read_Thread[i] = new Thread(new IgniteThread(true, cache)); } for (int i = 0; i<read_Thread.length;i++){ read_Thread[i].start(); } for (Thread thread:read_Thread){ try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } final long end = System.currentTimeMillis(); float times = end-start; float count = (float)test_rows/times; System.out.println("读取数据花费时间:"+(end-start)+"ms"); System.out.println("每秒读取数据量:"+count*1000); } private static Ignite getIgnite() { TcpDiscoverySpi spi = new TcpDiscoverySpi(); TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder(); ipFinder.setAddresses(Arrays.asList("192.168.1.172:47500..47509")); spi.setIpFinder(ipFinder); // CacheConfiguration cacheConfiguration = new CacheConfiguration<String,String>(); //cacheConfiguration.setCacheMode(CacheMode.LOCAL); // cacheConfiguration.setBackups(1); IgniteConfiguration cfg = new IgniteConfiguration(); cfg.setDiscoverySpi(spi); cfg.setClientMode(true); ignite = Ignition.start(cfg); return ignite; } static class IgniteThread implements Runnable { private static boolean startFlag = true; private static IgniteCache<String, String> cache; IgniteThread(boolean startFlag, IgniteCache<String, String> cache) { this.startFlag = startFlag; this.cache = cache; } public void run() { for (int i = 0; i < test_rows / thread_num;i++ ) { if (this.startFlag) { cache.get(Integer.toString(i)); } else { cache.put(Integer.toString(i), "aa" + i); } } } } }
package com.xixiwan.platform.sys.form; import com.xixiwan.platform.module.web.form.BaseForm; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) public class SysRoleForm extends BaseForm { /** * 角色权限 */ private String authorities; /** * 角色名称 */ private String name; /** * 用户id */ private Integer userid; /** * 角色状态(1:启用 0:禁用) */ private Integer status; }
package com.alibaba.druid.bvt.sql; import com.alibaba.druid.sql.ast.expr.SQLExtractExpr; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.sql.dialect.mysql.parser.MySqlExprParser; public class EqualTest_extract_mysql extends TestCase { public void test_exits() throws Exception { String sql = "EXTRACT (YEAR FROM x)"; String sql_c = "EXTRACT (MONTH FROM y)"; SQLExtractExpr exprA, exprB, exprC; { MySqlExprParser parser = new MySqlExprParser(sql); exprA = (SQLExtractExpr) parser.expr(); } { MySqlExprParser parser = new MySqlExprParser(sql); exprB = (SQLExtractExpr) parser.expr(); } { MySqlExprParser parser = new MySqlExprParser(sql_c); exprC = (SQLExtractExpr) parser.expr(); } Assert.assertEquals(exprA, exprB); Assert.assertNotEquals(exprA, exprC); Assert.assertTrue(exprA.equals(exprA)); Assert.assertFalse(exprA.equals(new Object())); Assert.assertEquals(exprA.hashCode(), exprB.hashCode()); Assert.assertEquals(new SQLExtractExpr(), new SQLExtractExpr()); Assert.assertEquals(new SQLExtractExpr().hashCode(), new SQLExtractExpr().hashCode()); } }
package com.wencheng.domain; import java.util.Date; import java.util.LinkedList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; @Entity public class Project { private int id; private String name; //项目名称 private String number; //项目编号 private Date startingTime; //开始时间 private ProjectLevel level; //项目分类 private int status = 1; //项目状态 0.超前 1.顺利 2.延迟 3.中断 4.终止 private School school; //学院 private List<Student> member = new LinkedList<Student>();//成员 private Teacher teacher; //指导教师 private List<Journal> journals = new LinkedList<Journal>(); //日志 private ApplicationReport appliocationReport; //申请报告 private MiddleReport middleReport; //中期报告 private EndReport endReport; //结题报告 private List<Message> messages = new LinkedList<Message>(); //站内信 private List<Message> messages1 = new LinkedList<Message>(); //站内信 private Account account; //登陆账户 private int process; //项目进度 private boolean important; private List<Error> errors = new LinkedList<Error>(); //警告处分 private List<Fee> fees = new LinkedList<Fee>(); private int grade; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(unique=true) public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(unique=true) public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public Date getStartingTime() { return startingTime; } public void setStartingTime(Date startingTime) { this.startingTime = startingTime; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="level") public ProjectLevel getLevel() { return level; } public void setLevel(ProjectLevel level) { this.level = level; } @Column(name="status") public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="school") public School getSchool() { return school; } public void setSchool(School school) { this.school = school; } @OneToMany(mappedBy="project",cascade=CascadeType.ALL) public List<Student> getMember() { return member; } public void setMember(List<Student> member) { this.member = member; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="teacher") public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } @OneToMany(mappedBy="project",fetch=FetchType.LAZY,cascade=CascadeType.ALL) public List<Journal> getJournals() { return journals; } public void setJournals(List<Journal> journals) { this.journals = journals; } @OneToOne(mappedBy="project",fetch=FetchType.LAZY,cascade=CascadeType.ALL) public ApplicationReport getAppliocationReport() { return appliocationReport; } public void setAppliocationReport(ApplicationReport appliocationReport) { this.appliocationReport = appliocationReport; } @OneToOne(mappedBy="project",fetch=FetchType.LAZY,cascade=CascadeType.ALL) public MiddleReport getMiddleReport() { return middleReport; } public void setMiddleReport(MiddleReport middleReport) { this.middleReport = middleReport; } @OneToOne(mappedBy="project",fetch=FetchType.LAZY,cascade=CascadeType.ALL) public EndReport getEndReport() { return endReport; } public void setEndReport(EndReport endReport) { this.endReport = endReport; } @OneToMany(mappedBy="toProject",fetch=FetchType.LAZY,cascade=CascadeType.ALL) public List<Message> getMessages() { return messages; } public void setMessages(List<Message> messages) { this.messages = messages; } @OneToMany(mappedBy="fromProject",fetch=FetchType.LAZY,cascade=CascadeType.ALL) public List<Message> getMessages1() { return messages1; } public void setMessages1(List<Message> messages) { this.messages1 = messages; } @OneToOne(mappedBy="project",cascade=CascadeType.ALL,fetch=FetchType.LAZY) public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } public int getProcess() { return process; } public void setProcess(int process) { this.process = process; } @OneToMany(mappedBy="project",fetch=FetchType.LAZY,cascade=CascadeType.ALL) public List<Error> getErrors() { return errors; } public void setErrors(List<Error> errors) { this.errors = errors; } @OneToMany(mappedBy="project",fetch=FetchType.LAZY,cascade=CascadeType.ALL) public List<Fee> getFees() { return fees; } public void setFees(List<Fee> fees) { this.fees = fees; } public boolean isImportant() { return important; } public void setImportant(boolean important) { this.important = important; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } }
import java.awt.List; import java.util.ArrayList; public class program { public static void main(String[] args) { // TODO Auto-generated method stub SeleniumCrawler selTest = new SeleniumCrawler(); // getSearchResult 에 가수이름과 곡제목 넣으면 // 가수 구글 검색 결과, 가수+곡 구글 검색 결과, 가수+곡 기사 결과 순으로 ArrayList로 반환함 ArrayList<String> testArray = selTest.getSearchResult("아이유", "love poem"); for (int i=0; i<testArray.size(); i++) { System.out.println(testArray.get(i)); } } }
package br.com.fiap.to; import java.util.List; public class Documentos { private List<DadosPessoa> docs; public List<DadosPessoa> getDocs() { return docs; } public void setDocs(List<DadosPessoa> docs) { this.docs = docs; } }
/* * Dryuf framework * * ---------------------------------------------------------------------------------- * * Copyright (C) 2000-2015 Zbyněk Vyškovský * * ---------------------------------------------------------------------------------- * * LICENSE: * * This file is part of Dryuf * * Dryuf is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * Dryuf 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 Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with Dryuf; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * @author 2000-2015 Zbyněk Vyškovský * @link mailto:kvr@matfyz.cz * @link http://kvr.matfyz.cz/software/java/dryuf/ * @link http://github.com/dryuf/ * @license http://www.gnu.org/licenses/lgpl.txt GNU Lesser General Public License v3 */ package net.dryuf.comp.wedding.mvp; import net.dryuf.comp.wedding.WeddingGiftsHeader; import net.dryuf.comp.wedding.dao.WeddingGiftsGiftDao; import net.dryuf.comp.wedding.form.WeddingGiftsCancelForm; import net.dryuf.meta.ActionDef; import net.dryuf.mvp.Presenter; public class WeddingGiftsCancelPresenter extends net.dryuf.mvp.BeanFormPresenter<WeddingGiftsCancelForm> { public WeddingGiftsCancelPresenter(net.dryuf.mvp.Presenter parentPresenter, net.dryuf.core.Options options) { super(parentPresenter, options.cloneAddingListed("formClass", "net.dryuf.wedding.WeddingGiftsCancelForm")); giftPresenter = (WeddingGiftsGiftPresenter)parentPresenter; weddingGiftsGiftDao = giftPresenter.getWeddingGiftsGiftDao(); weddingGiftsHeader = giftPresenter.getWeddingGiftsHeader(); giftPresenter.setMode(WeddingGiftsPresenter.MODE_CANCEL); } @Override protected WeddingGiftsCancelForm createBackingObject() { return new WeddingGiftsCancelForm(); } public boolean performCancel(ActionDef action) { WeddingGiftsCancelForm cancelForm = getBackingObject(); if (!weddingGiftsGiftDao.revertReservedCode(weddingGiftsHeader.getWeddingGiftsId(), giftPresenter.getGift().getDisplayName(), cancelForm.getReservedCode())) { this.addMessageLocalized(Presenter.MSG_Error, WeddingGiftsCancelPresenter.class, "Your gift reservation cancellation failed, probably wrong code specified"); return true; } else { this.confirmed = true; giftPresenter.setMode(WeddingGiftsPresenter.MODE_CANCEL_DONE); this.addMessageLocalized(Presenter.MSG_Info, WeddingGiftsCancelPresenter.class, "Your gift reservation has been successfully cancelled :-("); return true; } } public void render() { if (this.confirmed) { this.output(this.localize(WeddingGiftsCancelPresenter.class, "Please go back to <a href=\"..\">wedding gifts list</a> and reserve different one :-)")); } else { super.render(); } } protected WeddingGiftsGiftPresenter giftPresenter; protected WeddingGiftsGiftDao weddingGiftsGiftDao; protected WeddingGiftsHeader weddingGiftsHeader; protected boolean confirmed = false; }
import java.util.*; class stack_reverse { int size; int top; char[] a; boolean isEmpty() { return (top < 0); } stack_reverse(int n) { top = -1; size = n; a = new char[size]; } boolean push(char x) { if (top >= size) { System.out.println("Stack Overflow"); return false; } else { a[++top] = x; return true; } } char pop() { if (top < 0) { System.out.println("Stack Underflow"); return 0; } else { char x = a[top--]; return x; } } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter string"); String s=sc.nextLine(); int n = s.length(); String r=""; stack_reverse obj = new stack_reverse(n); for (int i = 0; i < n; i++) obj.push(s.charAt(i)); for (int i = 0; i < n; i++) { char ch = obj.pop(); r=r+ch; } System.out.println("Reversed string is: " + r); } }
package br.com.wasys.gfin.cheqfast.cliente.service; import android.util.Log; import br.com.wasys.gfin.cheqfast.cliente.endpoint.Endpoint; import br.com.wasys.gfin.cheqfast.cliente.endpoint.TransferenciaEndpoint; import br.com.wasys.gfin.cheqfast.cliente.model.TransferenciaModel; import br.com.wasys.library.service.Service; import retrofit2.Call; import rx.Observable; import rx.Subscriber; /** * Created by pascke on 03/09/16. */ public class TransferenciaService extends Service { public static TransferenciaModel obter(Long id) throws Throwable { TransferenciaEndpoint endpoint = Endpoint.create(TransferenciaEndpoint.class); Call<TransferenciaModel> call = endpoint.obter(id); TransferenciaModel model = Endpoint.execute(call); return model; } public static class Async { public static Observable<TransferenciaModel> obter(final Long id) { return Observable.create(new Observable.OnSubscribe<TransferenciaModel>() { @Override public void call(Subscriber<? super TransferenciaModel> subscriber) { try { TransferenciaModel model = TransferenciaService.obter(id); subscriber.onNext(model); subscriber.onCompleted(); } catch (Throwable e) { subscriber.onError(e); } } }); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mmorg29.appointmentscheduler; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.stage.Stage; /** * FXML Controller class * * @author mam * Handles the GUI operation of the user login. * Can display in English and Spanish languages. */ public class LoginFormController implements Initializable { @FXML private Label login_error_message_lbl; @FXML private TextField login_username_input; @FXML private PasswordField login_password_input; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { //mam Don't show error message when scene loads. login_error_message_lbl.setVisible(false); } @FXML private void handlePasswordEnterKey(KeyEvent event) throws IOException { //mam Get stage from event and call loadMainForm function if (event.getCode() == KeyCode.ENTER) { Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow(); loadMainForm(window); } } @FXML private void handleLoginButtonAction(ActionEvent event) throws IOException { //mam Get stage from event and call loadMainForm function Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow(); loadMainForm(window); } /** * mam * Verifies login info and displays the main form if the login info is correct. * Logs the login event. * @param stage reference to the stage to display the main form in. * @throws IOException */ private void loadMainForm(final Stage stage) throws IOException { try { SecurePassword.verifyUserAndPassword(login_username_input.getText(), login_password_input.getText()); AppointmentScheduler.LOGGER.log(Level.INFO, "Successful login for: {0}", this.login_username_input.getText()); User.getInstance().blowFuse(); Parent mainFormParent = FXMLLoader.load(getClass().getResource("MainForm.fxml")); Scene mainFormScene = new Scene(mainFormParent); stage.setScene(mainFormScene); stage.show(); } catch (InvalidLoginException ilEx) { //mam Login attempt unsuccessful display error message label and log failed login attempt. login_error_message_lbl.setVisible(true); AppointmentScheduler.LOGGER.log(Level.WARNING, "Failed login attempt for: {0}", this.login_username_input.getText()); } } }
package com.faikturan; import java.awt.BorderLayout; import java.awt.Font; import java.awt.GraphicsEnvironment; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class MainFrame4 extends JFrame { private JLabel sampleText; private JComboBox fontComboBox, sizeComboBox; private JCheckBox boldCheck, italCheck; private String[] fonts; public MainFrame4() { setSize(600, 600); setTitle("Yazı Biçimini Değiştir"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); sampleText = new JLabel("İsmek Yenibosna Uzmanlık Merkezi Java Grubu"); this.add(sampleText, BorderLayout.NORTH); GraphicsEnvironment g; g = GraphicsEnvironment.getLocalGraphicsEnvironment(); fonts = g.getAvailableFontFamilyNames(); JPanel controlPanel = new JPanel(); fontComboBox = new JComboBox<String>(fonts); fontComboBox.addActionListener(e->updateText()); controlPanel.add(new JLabel("Font Family")); controlPanel.add(fontComboBox); Integer[] sizes = {7,8,9,10,12,14,18,20,22,24,36}; sizeComboBox = new JComboBox<Integer>(sizes); sizeComboBox.addActionListener(e->updateText()); controlPanel.add(new JLabel("Size")); controlPanel.add(sizeComboBox); boldCheck = new JCheckBox("Bold"); boldCheck.addActionListener(e->updateText()); controlPanel.add(boldCheck); italCheck = new JCheckBox("Italic"); italCheck.addActionListener(e->updateText()); controlPanel.add(italCheck); this.add(controlPanel, BorderLayout.CENTER); updateText(); this.setVisible(true); } public void updateText() { String name = (String) fontComboBox.getSelectedItem(); Integer size = (Integer) sizeComboBox.getSelectedItem(); int style; if (boldCheck.isSelected() && italCheck.isSelected()) style = Font.BOLD | Font.ITALIC; else if (boldCheck.isSelected()) style = Font.BOLD; else if (italCheck.isSelected()) style = Font.ITALIC; else style = Font.PLAIN; Font f = new Font(name, style, size.intValue()); sampleText.setFont(f); } public static void main(String[] args) { new MainFrame4(); } }
/* * Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.rest.jwt.endpoint; import java.util.Collections; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pl.edu.icm.unity.rest.authn.JAXRSAuthentication; import pl.edu.icm.unity.server.api.IdentitiesManagement; import pl.edu.icm.unity.server.api.PKIManagement; import pl.edu.icm.unity.server.api.internal.NetworkServer; import pl.edu.icm.unity.server.api.internal.SessionManagement; import pl.edu.icm.unity.server.api.internal.TokensManagement; import pl.edu.icm.unity.server.authn.AuthenticationProcessor; import pl.edu.icm.unity.server.endpoint.EndpointFactory; import pl.edu.icm.unity.server.endpoint.EndpointInstance; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.types.endpoint.EndpointTypeDescription; /** * Factory for {@link JWTManagementEndpoint}. * @author K. Benedyczak */ @Component public class JWTManagementEndpointFactory implements EndpointFactory { public static final String NAME = "JWTMan"; public static final EndpointTypeDescription TYPE = new EndpointTypeDescription( NAME, "A RESTful endpoint allowing for management of tokens (issuing, refreshing) " + "which are subsequently used to authenticate to Unity by " + "non-browser clients in a simple way.", Collections.singleton(JAXRSAuthentication.NAME), Collections.singletonMap("", "The REST management base path")); @Autowired private UnityMessageSource msg; @Autowired private SessionManagement sessionMan; @Autowired private TokensManagement tokensMan; @Autowired private PKIManagement pkiManagement; @Autowired private NetworkServer server; @Autowired private IdentitiesManagement identitiesMan; @Autowired private AuthenticationProcessor authenticationProcessor; @Override public EndpointTypeDescription getDescription() { return TYPE; } @Override public EndpointInstance newInstance() { return new JWTManagementEndpoint(msg, sessionMan, authenticationProcessor, "", tokensMan, pkiManagement, server, identitiesMan); } }
package com.indoorpositioning.persistence; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.validation.constraints.NotNull; @Entity @Table(name="receiver") public class Receiver { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id_rcv; @NotNull private Integer x_pos; @NotNull private Integer y_pos; @OneToMany(mappedBy = "receiver") @OrderBy("date DESC") private List<History> histories; public Receiver() {} public Receiver(Integer id_rcv, Integer x_pos, Integer y_pos) { this.id_rcv = id_rcv; this.x_pos = x_pos; this.y_pos = y_pos; } @Override public String toString() { return String.format( "Receiver [id_rcv='%d',x_pos='%d',y_pos='%d']", this.id_rcv,this.x_pos,this.y_pos); } public Integer getId_rcv() { return id_rcv; } public void setId_rcv(Integer id_rcv) { this.id_rcv = id_rcv; } public Integer getX_pos() { return x_pos; } public void setX_pos(Integer x_pos) { this.x_pos = x_pos; } public Integer getY_pos() { return y_pos; } public void setY_pos(Integer y_pos) { this.y_pos = y_pos; } public List<History> getHistories() { return histories; } public void setHistories(List<History> histories) { this.histories = histories; } // public List<History> getLastNHistories(Integer n) { // Integer numOfHistories=histories.size(); // //To avoid an out of range index // if (n>numOfHistories) { // n=numOfHistories; // } // List<History> historyList = null; // for (int i = 0; i <numOfHistories; i++) { // History h=histories.get(i); // historyList.add(h); // } // return historyList; // } }
package com.bnk.featurelib.common.facade.service; import com.bnk.featurelib.common.facade.model.ScriptMeta; /** * @author ratel * @create 2018/12/3 */ public interface ScriptMetaFacade { /** * * @param scriptId * @return */ public ScriptMeta getScriptMetaById(int scriptId); }
package rocks.zipcode.stringsgalore; import org.junit.Assert; import org.junit.Test; import java.util.Calendar; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.*; import static rocks.zipcode.stringsgalore.StringTheory.allInterleavings; public class StringTheoryTest { StringTheory st = null; @org.junit.Before public void setUp() throws Exception { this.st = new StringTheory(); } @org.junit.After public void tearDown() throws Exception { } @Test public void testExercise1() { //Given String expectedres = "Java Exercises!\n" + "J\n" + "i"; StringTheory stringTheory = new StringTheory(); String actualres = stringTheory.Exercise1(expectedres); Assert.assertEquals(expectedres, actualres); System.out.println("Original String = " + actualres); } @Test public void testExercise2() { //Given String expectedres = "w3resource.com\n" + "51\n" + "101"; StringTheory stringTheory = new StringTheory(); String actualres = stringTheory.Exercise2(expectedres); Assert.assertEquals(expectedres, actualres); System.out.println("Original String = " + actualres); } @Test public void testExercise3() { //Given String expectedres = "w3resource.com\n" + "119\n" + "99"; StringTheory stringTheory = new StringTheory(); String actualres = stringTheory.Exercise3(expectedres); Assert.assertEquals(expectedres, actualres); System.out.println("Original String = " + actualres); } @Test public void testExercise4() { //Given String expectedres = "w3resource.com\n" + "9"; StringTheory stringTheory = new StringTheory(); String actualres = stringTheory.Exercise4(expectedres); Assert.assertEquals(expectedres, actualres); System.out.println("Original String = " + actualres); } @Test public void testExercise5() { //Given String string1 = "This is Exercise 1"; String string2 = "This is Exercise 2"; String expresult = "This is Exercise 1 is less than This is Exercise 2"; StringTheory stringTheory = new StringTheory(); String actualres = (String) stringTheory.Exercise5(string1, string2); Assert.assertEquals(expresult, actualres); System.out.println(actualres); } @Test public void testExercise6() { //Given String string1 = "This is exercise 1"; String string2 = "This is Exercise 1"; String expresult = "This is exercise 1 is equal to This is Exercise 1"; StringTheory stringTheory = new StringTheory(); String actualres = (String) stringTheory.Exercise6(string1, string2); Assert.assertEquals(expresult, actualres); System.out.println(actualres); } @Test public void testExercise7() { //Given String string1 = "PHP Exercises and "; String string2 = "Python Exercises"; String expresult = "PHP Exercises and Python Exercises"; StringTheory stringTheory = new StringTheory(); String actualres = (String) stringTheory.Exercise7(string1, string2); Assert.assertEquals(expresult, actualres); System.out.println(actualres); } @Test public void testExercise8() { //Given String string1 = "PHP Exercises and Python Exercises "; String string2 = "and"; boolean expresult = true; StringTheory stringTheory = new StringTheory(); Boolean actualres = stringTheory.Exercise8(string1, string2); Assert.assertEquals(expresult, actualres); System.out.println("Original String: " + string1 + "\n" + "Specified sequence of char values: " + string2); System.out.println(actualres); } @Test public void testExercise9() { //Given String string1 = "example.com"; String string2 = "Example.com"; CharSequence cs = "example.com"; boolean expresult1 = true; boolean expresult2 = false; StringTheory stringTheory = new StringTheory(); Boolean actualres1 = (Boolean) stringTheory.Exercise9(string1, cs); Boolean actualres2 = (Boolean) stringTheory.Exercise9(string2, cs); Assert.assertEquals(expresult1, actualres1); Assert.assertEquals(expresult2, actualres2); System.out.println("Comparing " + string1 + " and " + cs + ":" + actualres1); System.out.println("Comparing " + string2 + " and " + cs + ":" + actualres2); // System.out.println(actualres); } @Test public void testExercise10() { //Given String string1 = "example.com"; String string2 = "Example.com"; StringBuffer strburf = new StringBuffer(string1); boolean expresult1 = true; boolean expresult2 = false; StringTheory stringTheory = new StringTheory(); Boolean actualres1 = (Boolean) stringTheory.Exercise10(string1, strburf); Boolean actualres2 = (Boolean) stringTheory.Exercise10(string2, strburf); Assert.assertEquals(expresult1, actualres1); Assert.assertEquals(expresult2, actualres2); System.out.println("Comparing " + string1 + " and " + strburf + ":" + actualres1); System.out.println("Comparing " + string2 + " and " + strburf + ":" + actualres2); } @Test public void testExercise11() { //Given char[] arr_num = new char[] { '1', '2', '3', '4' }; String expectedRes = "The book contains 234 pages."; StringTheory stringTheory = new StringTheory(); String actualRes = stringTheory.Exercise11(arr_num); Assert.assertEquals(expectedRes, "The book contains " + actualRes +" pages."); System.out.println("\nThe book contains " + actualRes +" pages.\n"); } @Test public void testExercise12() { //Given String str1 = "Python Exercises"; String str2 = "Python Exercise"; String end_str1 = "se"; Boolean expectedRes1 = false; Boolean expectedRes2 = true; StringTheory stringTheory = new StringTheory(); Boolean actualRes1 = stringTheory.Exercise12(str1, end_str1); Boolean actualRes2 = stringTheory.Exercise12(str2, end_str1); Assert.assertEquals(expectedRes1, actualRes1); Assert.assertEquals(expectedRes2, actualRes2); System.out.println("\"" + str1 + "\" ends with " + "\"" + end_str1 + "\"? " + actualRes1); System.out.println("\"" + str2 + "\" ends with " + "\"" + end_str1 + "\"? " + actualRes2); } @Test public void testExercise13() { //Given String str1 = "Stephen Edwin King"; String str2 = "Walter Winchell"; String str3 = "Mike Royko"; Boolean expectedRes1 = false; Boolean expectedRes2 = false; StringTheory stringTheory = new StringTheory(); Boolean actualRes1 = stringTheory.Exercise13(str1, str2); Boolean actualRes2 = stringTheory.Exercise13(str1, str3); Assert.assertEquals(expectedRes1, actualRes1); Assert.assertEquals(expectedRes2, actualRes2); System.out.println("\"" + str1 + "\" equals " + "\"" + str2 + "\"? " + actualRes1); System.out.println("\"" + str1 + "\" equals " + "\"" + str3 + "\"? " + actualRes2); } @Test public void testExercise14() { //Given String str1 = "Stephen Edwin King"; String str2 = "Walter Winchell"; String str3 = "stephen edwin king"; Boolean expectedRes1 = false; Boolean expectedRes2 = true; StringTheory stringTheory = new StringTheory(); Boolean actualRes1 = stringTheory.Exercise14(str1, str2); Boolean actualRes2 = stringTheory.Exercise14(str1, str3); Assert.assertEquals(expectedRes1, actualRes1); Assert.assertEquals(expectedRes2, actualRes2); System.out.println("\"" + str1 + "\" equals " + "\"" + str2 + "\"? " + actualRes1); System.out.println("\"" + str1 + "\" equals " + "\"" + str3 + "\"? " + actualRes2); } @Test public void testExercise15(){ //Given String calanderFormat = "%tB %te, %tY%n"; StringTheory stringTheory = new StringTheory(); String actualRes = stringTheory.Exercise15(calanderFormat); System.out.println(actualRes); } @Test public void testExercise16(){ //Given String str = "This is a sample String."; String expectedRes = "This is a sample String."; //When StringTheory stringTheory = new StringTheory(); String actualRes = stringTheory.Exercise16(str); //Then Assert.assertEquals(expectedRes, actualRes); System.out.println("\nThe new String equals " +actualRes + "\n"); } @Test public void testExercise17(){ //Given String str = "This is a sample string."; //When StringTheory stringTheory = new StringTheory(); char[] actualRes = stringTheory.Exercise17(str); //Then Assert.assertTrue("This is a sample string.", true); } @Test public void testExercise18() { //Given String str = "Python Exercises."; Integer expectedRes = 863132599; //When StringTheory stringTheory = new StringTheory(); Integer actualRes = stringTheory.Exercise18(str); //Then Assert.assertEquals(expectedRes, actualRes); System.out.println("The hash for " + str + " is " + actualRes); } @Test public void testExercise19(){ //Given String str = "The quick brown fox jumps over the lazy dog."; //When StringTheory stringTheory = new StringTheory(); String actualRes = stringTheory.Exercise19(str); //Then Assert.assertTrue(true); System.out.println(actualRes); } @Test public void testExercise20(){ //Given String str1 = "Java Exercises"; String str2 = new StringBuffer("Java").append(" Exercises").toString(); String str3 = str2.intern(); Boolean expectedRes1 = false; Boolean expectedRes2 = true; //When StringTheory stringTheory = new StringTheory(); Boolean actualRes1 = stringTheory.Exercise20(str1, str2); Boolean actualRes2 = stringTheory.Exercise20(str1, str3); Assert.assertEquals(expectedRes1, actualRes1); System.out.println("str1 == str2? " + actualRes1); Assert.assertEquals(expectedRes2, actualRes2); System.out.println("str1 == str3? " + actualRes2); } @Test public void testExercise21(){ //Given String str = "The quick brown fox jumps over the lazy dog."; //When StringTheory stringTheory = new StringTheory(); Integer actualRes = stringTheory.Exercise21(str); } @Test public void testExercise22(){ //Given String str = "example.com"; Integer expectedRes = 11; //When StringTheory stringTheory = new StringTheory(); Integer actualRes = stringTheory.Exercise22(str); //Then Assert.assertEquals(expectedRes, actualRes); System.out.println("The string length of " + "\'" + str + "\'" + " is: " + actualRes); } @Test public void testExercise23(){ //Given String str1 = "Shanghai Houston Colorado Alexandria"; String str2 = "Alexandria Colorado Houston Shanghai"; Boolean expectedRes1 = true; Boolean expectedRes2 = false; //When StringTheory stringTheory = new StringTheory(); Boolean actualRes1 = stringTheory.Exercise23(str1, str2); Boolean actualRes2 = stringTheory.Exercise23(str1, str2); Assert.assertEquals(expectedRes1, actualRes1); System.out.println("str1[0 - 7] == str2[28 - 35]? " + actualRes1); Assert.assertEquals(expectedRes2, actualRes2); System.out.println("str1[9 - 15] == str2[9 - 15]? " + actualRes2); } @Test public void testExercise24() { //Given String str1 = "The quick brown fox jumps over the lazy dog."; String expectedRes1 = "The quick brown fox jumps over the lazy fog."; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise24(str1); Assert.assertEquals(expectedRes1, actualRes1); System.out.println(actualRes1); } @Test public void testExercise25() { //Given String str1 = "The quick brown fox jumps over the lazy dog."; String expectedRes1 = "The quick brown cat jumps over the lazy dog."; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise25(str1); Assert.assertEquals(expectedRes1, actualRes1); System.out.println(actualRes1); } @Test public void testExercise26() { //Given String str1 = "Red is favorite color."; String str2 = "Orange is also my favorite color."; String str3 = "Red"; Boolean expectedRes1 = true; Boolean expectedRes2 = false; //When StringTheory stringTheory = new StringTheory(); Boolean actualRes1 = stringTheory.Exercise26(str1, str3); Boolean actualRes2 = stringTheory.Exercise26(str2, str3); Assert.assertEquals(expectedRes1, actualRes1); System.out.println(str1 + " starts with " + str3 + "? " + actualRes1); Assert.assertEquals(expectedRes2, actualRes2); System.out.println(str2 + " starts with " + str3 + "? " + actualRes2); } @Test public void testExercise27() { //Given String str1 = "The quick brown fox jumps over the lazy dog."; String expectedRes1 = "brown fox jumps "; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise27(str1); Assert.assertEquals(expectedRes1, actualRes1); System.out.println(actualRes1); } @Test public void testExercise28() { //Given String str1 = "Java Exercises."; // String expectedRes1 = "Java Exercises."; //When StringTheory stringTheory = new StringTheory(); char[] actualRes1 = stringTheory.Exercise28(str1); Assert.assertTrue(true); System.out.println(actualRes1); } @Test public void testExercise29() { //Given String str1 = "The Quick BroWn FoX!"; String expectedRes1 = "the quick brown fox!"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise29(str1); Assert.assertEquals(expectedRes1, actualRes1); System.out.println(actualRes1); } @Test public void testExercise30() { //Given String str1 = "The Quick BroWn FoX!"; String expectedRes1 = "THE QUICK BROWN FOX!"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise30(str1); Assert.assertEquals(expectedRes1, actualRes1); System.out.println(actualRes1); } @Test public void testExercise31() { //Given String str1 = " Java Exercises "; String expectedRes1 = "Java Exercises"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise31(str1); Assert.assertEquals(expectedRes1, actualRes1); System.out.println(actualRes1); System.out.println(str1); } @Test public void testExercise32() { //Given String str1 = "thequickbrownfoxxofnworbquickthe"; String expectedRes1 = "brownfoxxofnworb"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise32(str1); Assert.assertEquals(expectedRes1, actualRes1); System.out.println(actualRes1); System.out.println(str1); } @Test public void testExercise34() { String str1 = "successes"; String expectedRes = "c"; //When StringTheory stringTheory = new StringTheory(); String actualRes= stringTheory.Exercise34(str1); //Then Assert.assertEquals(expectedRes,actualRes); System.out.println(actualRes); } @Test public void testExercise33() { //Given String P = "WX"; String Q = "YZ"; Set<String> out = new HashSet<>(); out.stream().forEach(System.out::println); //When StringTheory stringTheory = new StringTheory(); allInterleavings("", P, Q, out); String actualRes1 = stringTheory.Exercise33("", P, Q, out); Assert.assertTrue(true); System.out.println(actualRes1); } @Test public void testExercise38() { //Given String string = "w3resource"; String expectedRes = "w3resouc"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise38(string); Assert.assertEquals(expectedRes, actualRes1); System.out.println("After removing duplicates characters the new string is: " + actualRes1); } @Test public void testExercise39() { //Given String string = "gibblegabbler"; String expectedRes = "i"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise39(string); Assert.assertEquals(expectedRes, actualRes1); System.out.println("The first non repeated character in String is: " + actualRes1); } @Test public void testExercise40() { //Given String string = "abcdefghijklmnopqrstuvwxy"; int splitNum = 5; // String expectedRes = "i"; //When StringTheory stringTheory = new StringTheory(); int actualRes1 = stringTheory.Exercise40(string, splitNum); Assert.assertTrue(true); // Assert.assertEquals(expectedRes, actualRes1); System.out.println("The string divided into " + " parts and they are: " + actualRes1); } @Test public void testExercise41() { //Given String string1 = "the quick brown fox"; String string2 = "queen"; String expectedRes = "th ick brow fox"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise41(string1, string2); Assert.assertEquals(expectedRes, actualRes1); System.out.println("The new String is: " + actualRes1); } @Test public void testExercise43() { //Given String string1 = "test string"; String expectedRes = "t"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise43(string1); Assert.assertEquals(expectedRes, actualRes1); System.out.println("Max Occurring character is: " + actualRes1); } @Test public void testExercise44() { //Given String string1 = "The quick brown fox jumps"; String expectedRes = "spmuj xof nworb kciuq ehT"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise44(string1); Assert.assertEquals(expectedRes, actualRes1); System.out.println("The string in reverse order: " + actualRes1); } @Test public void testExercise45() { //Given String string1 = "Reverse words in a given string"; String expectedRes = "string given a in words Reverse"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise45(string1); Assert.assertEquals(expectedRes, actualRes1); System.out.println("New String after reversed words: " + actualRes1); } @Test public void testExercise46() { //Given String string1 = "This is a test string"; String expectedRes = "sihT si a tset gnirts"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise46(string1); Assert.assertEquals(expectedRes, actualRes1); System.out.println("New String reversed word by word is: " + actualRes1); } @Test public void testExercise48() { //Given String string1 = "abrambabasc"; String ptn1 = "ac"; String ptn2 = "b"; String expectedRes = "aramaasc"; //When StringTheory stringTheory = new StringTheory(); String actualRes1 = stringTheory.Exercise48(string1, ptn1, ptn2); Assert.assertEquals(expectedRes, actualRes1); System.out.println("After removing the new string is: " + actualRes1); } @Test public void testExercise52() { //Given String string1 = "ABACD"; String string2 = "CDABA"; // String expectedRes = "aramaasc"; //When StringTheory stringTheory = new StringTheory(); Boolean actualRes1 = stringTheory.Exercise52(string1, string2); Assert.assertTrue(true); System.out.println("The given strings are: "+string1+" and "+string2); System.out.println("\nThe concatination of 1st string twice is: "+string1+string2); if (stringTheory.Exercise52(string1, string2)) { System.out.println("The 2nd string " + string2 + " exists in the new string."); System.out.println("\nStrings are rotations of each other"); } else { System.out.println("The 2nd string " + string2 + " not exists in the new string."); System.out.printf("\nStrings are not rotations of each other"); } } @Test public void testExercise53() { String st1="abcdhgh"; String st2="abc*d?*"; System.out.println("The given string is: "+st1); System.out.println("The given pattern string is: "+st2); char[] str1 = st1.toCharArray(); char[] patstr = st2.toCharArray(); //When StringTheory stringTheory = new StringTheory(); // Boolean actualRes1 = stringTheory.Exercise53(st1, st2); boolean[][] lookup = new boolean[str1.length + 1][patstr.length + 1]; if (stringTheory.Exercise53(str1, patstr, str1.length - 1, patstr.length - 1, lookup)) { System.out.println("The given pattern is matching."); } else { System.out.println("The given pattern is not matching."); } } }
package JewelsandStones771; /** * @ClassName Solution01 * @Description https://leetcode-cn.com/problems/jewels-and-stones/ * @Author tangchao@mfexcel.com * @Date 2019/10/17 16:21 * @Version 1.0 */ public class Solution01 { public int numJewelsInStones(String J, String S) { int count = 0; for(int i = 0; i < S.length(); i++) { if (J.contains(String.valueOf(S.charAt(i)))) { count++; } } return count; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by Tyler on 09/02/2017. */ public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int K = Integer.parseInt(st.nextToken()); ArrayList<Integer> friends = new ArrayList<>(); ArrayList<Integer> temp = new ArrayList<>(); for(int a = 1; a <= K; a++) { friends.add(a); } st = new StringTokenizer(br.readLine()); int M = Integer.parseInt(st.nextToken()); for(int b = 0; b < M; b++) { st = new StringTokenizer(br.readLine()); int divisor = Integer.parseInt(st.nextToken()); for(int x = 1; x <= friends.size(); x++) { if(x%divisor == 0) { } else { temp.add(friends.get(x-1)); } } friends.clear(); friends.addAll(temp); temp.clear(); } friends.stream().forEach(x -> System.out.println(x)); } }
package sr.hakrinbank.intranet.api.controller; import jcifs.smb.SmbException; import org.apache.commons.codec.binary.Base64; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import sr.hakrinbank.intranet.api.dto.*; import sr.hakrinbank.intranet.api.mapping.AtmToDtoMap; import sr.hakrinbank.intranet.api.mapping.PosMerchantToDtoMap; import sr.hakrinbank.intranet.api.mapping.RatesToDtoMap; import sr.hakrinbank.intranet.api.mapping.RelationshipAccountToDtoMap; import sr.hakrinbank.intranet.api.model.*; import sr.hakrinbank.intranet.api.projection.EmployeeWithoutMedia; import sr.hakrinbank.intranet.api.service.*; import sr.hakrinbank.intranet.api.util.Constant; import java.net.MalformedURLException; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import static sr.hakrinbank.intranet.api.controller.BannerPictureController.mapBannerPictureToDto; import static sr.hakrinbank.intranet.api.controller.CbvsRatesController.mapCbvsRatesToDto; import static sr.hakrinbank.intranet.api.controller.EmployeeController.*; import static sr.hakrinbank.intranet.api.controller.GalleryController.mapGalleryToDto; import static sr.hakrinbank.intranet.api.controller.JubilarisController.mapJubilarisToDto; import static sr.hakrinbank.intranet.api.controller.LeaveController.mapLeaveToDto; import static sr.hakrinbank.intranet.api.controller.ListedPersonBlackController.mapListedPersonBlackToDto; import static sr.hakrinbank.intranet.api.controller.ListedPersonGreyController.mapListedPersonGreyToDto; import static sr.hakrinbank.intranet.api.controller.ListedPersonPepController.mapListedPersonPepToDto; /** * Created by clint on 4/20/17. */ @RestController @RequestMapping(value = "/display") public class DisplayController { @Autowired private NewsService newsService; @Autowired private NewsJobOfferService newsJobOfferService; @Autowired private NewsHwoService newsHwoService; @Autowired private NewsPvService newsPvService; @Autowired private FxRatesService fxRatesService; @Autowired private CbvsRatesService cbvsRatesService; @Autowired private BlackListedPersonService blackListedPersonService; @Autowired private PosMerchantService posMerchantService; @Autowired private AtmService atmService; @Autowired private DistrictService districtService; @Autowired private EmployeeService employeeService; @Autowired private TelephoneService telephoneService; @Autowired private DepartmentService departmentService; @Autowired private BranchService branchService; @Autowired private CurrencyService currencyService; @Autowired private RatesService ratesService; @Autowired private RelationshipAccountService relationshipAccountService; @Autowired private SambaService sambaService; @Autowired private InterestService interestService; @Autowired private GalleryService galleryService; @Autowired private BannerPictureService bannerPictureService; @Autowired private LeaveService leaveService; @Autowired private ListedPersonBlackService listedPersonBlackService; @Autowired private ListedPersonGreyService listedPersonGreyService; @Autowired private ListedPersonPepService listedPersonPepService; @Autowired private ListedPersonWebsiteLinkService listedPersonWebsiteLinkService; @Autowired private NationalityService nationalityService; @Autowired private JubilarisService jubilarisService; //-------------------Retrieve new News count-------------------------------------------------------- @RequestMapping(value = "/news/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countNewsOfTheWeek() { int results = newsService.countNewsOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All News-------------------------------------------------------- @RequestMapping(value = "/news", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllNews() { List<News> news = newsService.findAllActiveNewsOrderedByDate(); if(news.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapNewsToDto(news), null), HttpStatus.OK); } //-------------------Retrieve All News By Search-------------------------------------------------------- @RequestMapping(value = "/news/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listNewsBySearchQuery(@RequestParam String characters, @RequestParam String date) { List<News> news = newsService.findAllActiveNewsBySearchQueryOrDate(characters, date); if(news.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapNewsToDto(news), mapNewsToDto(news).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve One News-------------------------------------------------------- @RequestMapping(value = "/news/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> getNews(@PathVariable("id") long id) { System.out.println("Fetching Module with id " + id); News news = newsService.findById(id); if (news == null) { System.out.println("Module with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } ModelMapper modelMapper = new ModelMapper(); return new ResponseEntity<ResponseDto>(new ResponseDto(modelMapper.map(news, NewsBasisDto.class), null), HttpStatus.OK); } //-------------------Retrieve One News-------------------------------------------------------- @RequestMapping(value = "/newslatest", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listLatestNews() { List<News> news = newsService.findLatestNews(); if(news.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapNewsToDto(news), null), HttpStatus.OK); } //-------------------Retrieve new NewsJobOffer count-------------------------------------------------------- @RequestMapping(value = "/newsjoboffer/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countNewsJobOfferOfTheWeek() { int results = newsJobOfferService.countNewsJobOfferOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All NewsJobOffer-------------------------------------------------------- @RequestMapping(value = "/newsjoboffer", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllNewsJobOffer() { List<NewsJobOffer> newsJobOffer = newsJobOfferService.findAllActiveNewsJobOfferOrderedByDate(); if(newsJobOffer.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapNewsJobOfferToDto(newsJobOffer), null), HttpStatus.OK); } //-------------------Retrieve All NewsJobOffer By Search-------------------------------------------------------- @RequestMapping(value = "/newsjoboffer/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listNewsJobOfferBySearchQuery(@RequestParam String characters, @RequestParam String date) { List<NewsJobOffer> newsJobOffer = newsJobOfferService.findAllActiveNewsJobOfferBySearchQueryOrDate(characters, date); if(newsJobOffer.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapNewsJobOfferToDto(newsJobOffer), mapNewsJobOfferToDto(newsJobOffer).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve One NewsJobOffer-------------------------------------------------------- @RequestMapping(value = "/newsjoboffer/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> getNewsJobOffer(@PathVariable("id") long id) { System.out.println("Fetching Module with id " + id); NewsJobOffer newsJobOffer = newsJobOfferService.findById(id); if (newsJobOffer == null) { System.out.println("Module with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } ModelMapper modelMapper = new ModelMapper(); return new ResponseEntity<ResponseDto>(new ResponseDto(modelMapper.map(newsJobOffer, NewsJobOfferDto.class), null), HttpStatus.OK); } //-------------------Retrieve new NewsHwo count-------------------------------------------------------- @RequestMapping(value = "/newshwo/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countNewsHwoOfTheWeek() { int results = newsHwoService.countNewsHwoOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All NewsHwo-------------------------------------------------------- @RequestMapping(value = "/newshwo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllNewsHwo() { List<NewsHwo> newsHwo = newsHwoService.findAllActiveNewsHwoOrderedByDate(); if(newsHwo.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapNewsHwoToDto(newsHwo), null), HttpStatus.OK); } //-------------------Retrieve All NewsHwo By Search-------------------------------------------------------- @RequestMapping(value = "/newshwo/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listNewsHwoBySearchQuery(@RequestParam String characters, @RequestParam String date) { List<NewsHwo> newsHwo = newsHwoService.findAllActiveNewsHwoBySearchQueryOrDate(characters, date); if(newsHwo.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapNewsHwoToDto(newsHwo), mapNewsHwoToDto(newsHwo).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve One NewsHwo-------------------------------------------------------- @RequestMapping(value = "/newshwo/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> getNewsHwo(@PathVariable("id") long id) { System.out.println("Fetching Module with id " + id); NewsHwo newsHwo = newsHwoService.findById(id); if (newsHwo == null) { System.out.println("Module with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } ModelMapper modelMapper = new ModelMapper(); return new ResponseEntity<ResponseDto>(new ResponseDto(modelMapper.map(newsHwo, NewsHwoDto.class), null), HttpStatus.OK); } //-------------------Retrieve new NewsPv count-------------------------------------------------------- @RequestMapping(value = "/newspv/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countNewsPvOfTheWeek() { int results = newsPvService.countNewsPvOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All NewsPv-------------------------------------------------------- @RequestMapping(value = "/newspv", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllNewsPv() { List<NewsPv> newsPv = newsPvService.findAllActiveNewsPvOrderedByDate(); if(newsPv.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapNewsPvToDto(newsPv), null), HttpStatus.OK); } //-------------------Retrieve All NewsPv By Search-------------------------------------------------------- @RequestMapping(value = "/newspv/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listNewsPvBySearchQuery(@RequestParam String characters, @RequestParam String date) { List<NewsPv> newsPv = newsPvService.findAllActiveNewsPvBySearchQueryOrDate(characters, date); if(newsPv.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapNewsPvToDto(newsPv), mapNewsPvToDto(newsPv).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve One NewsPv-------------------------------------------------------- @RequestMapping(value = "/newspv/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> getNewsPv(@PathVariable("id") long id) { System.out.println("Fetching Module with id " + id); NewsPv newsPv = newsPvService.findById(id); if (newsPv == null) { System.out.println("Module with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } ModelMapper modelMapper = new ModelMapper(); return new ResponseEntity<ResponseDto>(new ResponseDto(modelMapper.map(newsPv, NewsPvDto.class), null), HttpStatus.OK); } //-------------------Retrieve new FxRates count-------------------------------------------------------- @RequestMapping(value = "/fxrates/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countFxRatesOfTheWeek() { int results = fxRatesService.countFxRatesOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All FxRates-------------------------------------------------------- @RequestMapping(value = "/fxrates", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllFxRates() { List<FxRates> rates = fxRatesService.findAllActiveFxRatesOrderedByDate(); if(rates.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(FxRatesController.mapFxRatesToDto(rates), null), HttpStatus.OK); } //-------------------Retrieve All FxRates By Search-------------------------------------------------------- @RequestMapping(value = "/fxrates/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listFxRatesBySearchQuery(@RequestParam String date) { List<FxRates> rates = fxRatesService.findAllActiveFxRatesByDate(date); if(rates.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(FxRatesController.mapFxRatesToDto(rates), FxRatesController.mapFxRatesToDto(rates).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); }//-------------------Retrieve new CbvsRates count-------------------------------------------------------- @RequestMapping(value = "/cbvsrates/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countCbvsRatesOfTheWeek() { int results = cbvsRatesService.countCbvsRatesOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All CbvsRates-------------------------------------------------------- @RequestMapping(value = "/cbvsrates", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllCbvsRates() { List<CbvsRates> rates = cbvsRatesService.findAllActiveCbvsRatesOrderedByDate(); if(rates.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapCbvsRatesToDto(rates), null), HttpStatus.OK); } //-------------------Retrieve All CbvsRates By Search-------------------------------------------------------- @RequestMapping(value = "/cbvsrates/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listCbvsRatesBySearchQuery(@RequestParam String qry) { List<CbvsRates> rates = cbvsRatesService.findAllActiveCbvsRatesBySearchQuery(qry); if(rates.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapCbvsRatesToDto(rates), mapCbvsRatesToDto(rates).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve new Rates count-------------------------------------------------------- @RequestMapping(value = "/rates/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countRatesOfTheWeek() { int results = ratesService.countRatesOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All Rates-------------------------------------------------------- @RequestMapping(value = "/rates", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllRates() { List<Rates> rates = ratesService.findAllActiveRatesOrderedByDate(); if(rates.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapRatesToDto(rates), null), HttpStatus.OK); } //-------------------Retrieve All RelationshipAccount-------------------------------------------------------- @RequestMapping(value = "/relationshipaccount", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllRelationshipAccount() { List<RelationshipAccount> relationshipAccount = relationshipAccountService.findAllActiveRelationshipAccount(); if(relationshipAccount.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapRelationshipAccountToDto(relationshipAccount), null), HttpStatus.OK); } //-------------------Retrieve All RelationshipAccount By Search-------------------------------------------------------- @RequestMapping(value = "/relationshipaccount/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listRelationshipAccountBySearchQuery(@RequestParam String characters) { List<RelationshipAccount> relationshipAccount = relationshipAccountService.findAllActiveRelationshipAccountBySearchQuery(characters); if(relationshipAccount.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapRelationshipAccountToDto(relationshipAccount), mapRelationshipAccountToDto(relationshipAccount).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve All Rates By Search-------------------------------------------------------- @RequestMapping(value = "/rates/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listRatesBySearchQuery(@RequestParam String characters) { List<Rates> rates = ratesService.findAllActiveRatesBySearchQuery(characters); if(rates.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapRatesToDto(rates), mapRatesToDto(rates).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve All Department-------------------------------------------------------- @RequestMapping(value = "/department", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllDepartments() { List<Department> departments = departmentService.findAllActiveDepartments(); if(departments.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } List<DepartmentDto> departmentsDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(Department department: departments){ departmentsDtoList.add(modelMapper.map(department, DepartmentDto.class)); } return new ResponseEntity<ResponseDto>(new ResponseDto(departmentsDtoList, null), HttpStatus.OK); } //-------------------Retrieve All Department-------------------------------------------------------- @RequestMapping(value = "/branch", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllBranches() { List<Branch> branchs = branchService.findAllActiveBranches(); if(branchs.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } List<DepartmentDto> branchsDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(Branch branch: branchs){ branchsDtoList.add(modelMapper.map(branch, DepartmentDto.class)); } return new ResponseEntity<ResponseDto>(new ResponseDto(branchsDtoList, null), HttpStatus.OK); } //-------------------Retrieve All Department-------------------------------------------------------- @RequestMapping(value = "/currency", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllCurrencies() { List<Currency> currencys = currencyService.findAllActiveCurrencies(); if(currencys.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } List<DepartmentDto> currencysDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(Currency currency: currencys){ currencysDtoList.add(modelMapper.map(currency, DepartmentDto.class)); } return new ResponseEntity<ResponseDto>(new ResponseDto(currencysDtoList, null), HttpStatus.OK); } //-------------------Retrieve All Department-------------------------------------------------------- @RequestMapping(value = "/nationality", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllNationalities() { List<Nationality> nationalities = nationalityService.findAllActiveNationalities(); if(nationalities.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } List<DepartmentDto> nationalitiesDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(Nationality nationality: nationalities){ nationalitiesDtoList.add(modelMapper.map(nationality, DepartmentDto.class)); } return new ResponseEntity<ResponseDto>(new ResponseDto(nationalitiesDtoList, null), HttpStatus.OK); } //-------------------Retrieve new Employee count-------------------------------------------------------- @RequestMapping(value = "/employee/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countEmployeeOfTheWeek() { int results = employeeService.countEmployeeOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve new Employee birthday count-------------------------------------------------------- @RequestMapping(value = "/employee/birthday/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countEmployeeBirthdayOfTheMonth() { int results = employeeService.countEmployeeBirthdayOfTheMonth(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All Employee-------------------------------------------------------- @RequestMapping(value = "/employee", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllEmployee() throws MalformedURLException, SmbException { List<Employee> employee = employeeService.findAllActiveEmployeeOrderedByName(); if(employee.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDto(employee, false), null), HttpStatus.OK); } //-------------------Retrieve All Employee With Pagination-------------------------------------------------------- @RequestMapping(value = "/employee/bypage", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllEmployee(Pageable pageable) throws MalformedURLException, SmbException { Page<Employee> employee = employeeService.listAllByPage(pageable); if(employee.getTotalElements() == 0){ return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDtoByPage(employee, true), Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDtoByPage(employee, false), mapModelToDtoByPage(employee, true).getTotalElements() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve All Employee With Birthday Current Month-------------------------------------------------------- @RequestMapping(value = "/employee/birthday", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllEmployeeWithBirthdayCurrentMonth() throws MalformedURLException, SmbException { List<Employee> employee = employeeService.listAllEmployeeWithBirthdayCurrentMonth(); if(employee.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDto(employee, false), null), HttpStatus.OK); } //-------------------Retrieve All Employee By Search-------------------------------------------------------- @RequestMapping(value = "/employee/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listEmployeeBySearchQuery(@RequestParam String characters, @RequestParam String department, @RequestParam String branch, Pageable pageable) throws MalformedURLException, SmbException { Page<Employee> employee = employeeService.findAllActiveEmployeeBySearchQueryOrDepartmentOrBranch(characters, department, branch, pageable); if(employee.getTotalElements() == 0){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDtoByPage(employee, false), mapModelToDtoByPage(employee, true).getTotalElements() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve All Employee for phonebook-------------------------------------------------------- @RequestMapping(value = "/phonebook", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllEmployeeForPhonebook() throws MalformedURLException, SmbException { List<EmployeeWithoutMedia> employee = employeeService.findAllActiveEmployeeOrderedByNameWithoutMedia(); if(employee.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapEmployeeWithoutMediaToDto(employee), null), HttpStatus.OK); } //-------------------Retrieve All Employee By Name For Phonebook -------------------------------------------------------- @RequestMapping(value = "/phonebook/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listEmployeeByNameSearchQuery(@RequestParam String characters, @RequestParam String department, @RequestParam String branch) throws MalformedURLException, SmbException { List<EmployeeWithoutMedia> employee = employeeService.findAllActiveEmployeeBySearchQueryOrDepartmentOrBranchWithoutMedia(characters, department, branch); if(employee.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapEmployeeWithoutMediaToDto(employee), mapEmployeeWithoutMediaToDto(employee).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve All Telephone for phonebook-------------------------------------------------------- @RequestMapping(value = "/telephone", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllTelephoneForPhonebook() throws MalformedURLException, SmbException { List<Telephone> telephone = telephoneService.findAllActiveTelephoneOrderedByName(); if(telephone.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(TelephoneController.mapTelephoneToDto(telephone), null), HttpStatus.OK); } //-------------------Retrieve All Telephone By Name For Phonebook -------------------------------------------------------- @RequestMapping(value = "/telephone/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listTelephoneByNameSearchQuery(@RequestParam String characters, @RequestParam String department, @RequestParam String branch) throws MalformedURLException, SmbException { List<Telephone> telephone = telephoneService.findAllActiveTelephoneBySearchQueryOrDepartmentOrBranch(characters, department, branch); if(telephone.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(TelephoneController.mapTelephoneToDto(telephone), TelephoneController.mapTelephoneToDto(telephone).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve new BlackListedPerson count-------------------------------------------------------- @RequestMapping(value = "/blacklist/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countBlackListedPersonOfTheWeek() { int results = blackListedPersonService.countBlackListedPersonOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All BlackListedPerson-------------------------------------------------------- @RequestMapping(value = "/blacklist", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllBlackListedPerson() { List<BlackListedPerson> blackListedPerson = blackListedPersonService.findAllActiveBlackListedPersonOrderedByDate(); if(blackListedPerson.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapBlackListedPersonToDto(blackListedPerson), null), HttpStatus.OK); } //-------------------Retrieve All BlackListedPerson By Search-------------------------------------------------------- @RequestMapping(value = "/blacklist/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listBlackListedPersonBySearchQuery(@RequestParam String characters, @RequestParam String date) { List<BlackListedPerson> blackListedPerson = blackListedPersonService.findAllActiveBlackListedPersonBySearchQueryOrDate(characters, date); if(blackListedPerson.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapBlackListedPersonToDto(blackListedPerson), mapBlackListedPersonToDto(blackListedPerson).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve new PosMerchant count-------------------------------------------------------- @RequestMapping(value = "/posmerchant/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countPosMerchantOfTheWeek() { int results = posMerchantService.countPosMerchantOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All PosMerchant-------------------------------------------------------- @RequestMapping(value = "/posmerchant", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllPosMerchant() { List<PosMerchant> posMerchant = posMerchantService.findAllActivePosMerchantOrderedByDate(); if(posMerchant.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapPosMerchantToDto(posMerchant), null), HttpStatus.OK); } //-------------------Retrieve All PosMerchant By Search-------------------------------------------------------- @RequestMapping(value = "/posmerchant/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listPosMerchantBySearchQuery(@RequestParam String characters, @RequestParam String district) { List<PosMerchant> posMerchant = posMerchantService.findAllActivePosMerchantBySearchQueryOrDistrict(characters, district); if(posMerchant.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapPosMerchantToDto(posMerchant), mapPosMerchantToDto(posMerchant).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve new Atm count-------------------------------------------------------- @RequestMapping(value = "/atm/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countAtmOfTheWeek() { int results = atmService.countAtmOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All Atm-------------------------------------------------------- @RequestMapping(value = "/atm", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllAtm() { List<Atm> atm = atmService.findAllActiveAtmOrderedByDate(); if(atm.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapAtmToDto(atm), null), HttpStatus.OK); } //-------------------Retrieve All Atm By Search-------------------------------------------------------- @RequestMapping(value = "/atm/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAtmBySearchQuery(@RequestParam String characters, @RequestParam String district) { List<Atm> atm = atmService.findAllActiveAtmBySearchQueryOrDistrict(characters, district); if(atm.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapAtmToDto(atm), mapAtmToDto(atm).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve All District-------------------------------------------------------- @RequestMapping(value = "/district", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllDistrict() { List<District> district = districtService.findAllActiveDistricts(); if(district.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapDistrictToDto(district), null), HttpStatus.OK); } //-------------------Retrieve All Gallery-------------------------------------------------------- @RequestMapping(value = "/gallerysimple", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllGallerySimple() { List<Gallery> gallery = galleryService.findAllActiveGallery(); if(gallery.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapGalleryToDto(gallery, true), null), HttpStatus.OK); } @RequestMapping(value = "/gallery", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllGallery() { List<Gallery> gallery = galleryService.findAllActiveGallery(); if(gallery.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapGalleryToDto(gallery, false), null), HttpStatus.OK); } //-------------------Retrieve All BannerPicture-------------------------------------------------------- @RequestMapping(value = "/bannerpicturesimple", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllBannerPictureSimple() { List<BannerPicture> bannerPicture = bannerPictureService.findAllActiveBannerPicture(); if(bannerPicture.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapBannerPictureToDto(bannerPicture, true), null), HttpStatus.OK); } @RequestMapping(value = "/bannerpicture", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllBannerPicture() { List<BannerPicture> bannerPicture = bannerPictureService.findAllActiveBannerPicture(); if(bannerPicture.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapBannerPictureToDto(bannerPicture, false), null), HttpStatus.OK); } //-------------------Retrieve new Interest count-------------------------------------------------------- @RequestMapping(value = "/interest/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countInterestOfTheWeek() { int results = interestService.countInterestOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All Interest-------------------------------------------------------- @RequestMapping(value = "/interest", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllInterest() { List<Interest> interest = interestService.findAllActiveInterestOrderedByDate(); if(interest.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapInterestToDto(interest), null), HttpStatus.OK); } //-------------------Retrieve All Interest By Search-------------------------------------------------------- @RequestMapping(value = "/interest/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listInterestBySearchQuery(@RequestParam String characters, @RequestParam String date) { List<Interest> interest = interestService.findAllActiveInterestBySearchQueryOrDate(characters, date); if(interest.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapInterestToDto(interest), mapInterestToDto(interest).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve One Interest-------------------------------------------------------- @RequestMapping(value = "/interest/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> getInterest(@PathVariable("id") long id) { System.out.println("Fetching Module with id " + id); Interest interest = interestService.findById(id); if (interest == null) { System.out.println("Module with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } ModelMapper modelMapper = new ModelMapper(); return new ResponseEntity<ResponseDto>(new ResponseDto(modelMapper.map(interest, InterestBasisDto.class), null), HttpStatus.OK); } //-------------------Retrieve new LeaveOfAbsence count-------------------------------------------------------- @RequestMapping(value = "/leave/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countLeaveOfTheWeek() { int results = leaveService.countLeaveOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All LeaveOfAbsence-------------------------------------------------------- @RequestMapping(value = "/leave", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllLeave() { List<LeaveOfAbsence> leaveOfAbsence = leaveService.findAllActiveLeave(); if(leaveOfAbsence.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapLeaveToDto(leaveOfAbsence), null), HttpStatus.OK); } //-------------------Retrieve All LeaveOfAbsence By Search-------------------------------------------------------- @RequestMapping(value = "/leave/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listLeaveBySearchQuery(@RequestParam String characters) { List<LeaveOfAbsence> leaveOfAbsence = leaveService.findByName(characters); if(leaveOfAbsence.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapLeaveToDto(leaveOfAbsence), mapLeaveToDto(leaveOfAbsence).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve One LeaveOfAbsence-------------------------------------------------------- @RequestMapping(value = "/leave/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> getLeave(@PathVariable("id") long id) { System.out.println("Fetching Module with id " + id); LeaveOfAbsence leaveOfAbsence = leaveService.findById(id); if (leaveOfAbsence == null) { System.out.println("Module with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } ModelMapper modelMapper = new ModelMapper(); return new ResponseEntity<ResponseDto>(new ResponseDto(modelMapper.map(leaveOfAbsence, LeaveDto.class), null), HttpStatus.OK); } //-------------------Retrieve new ListedPersonBlack count-------------------------------------------------------- @RequestMapping(value = "/listedpersonblack/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countListedPersonBlackOfTheWeek() { int results = listedPersonBlackService.countListedPersonBlackOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All ListedPersonBlack-------------------------------------------------------- @RequestMapping(value = "/listedpersonblack", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllListedPersonBlack() { List<ListedPersonBlack> listedPersonsBlack = listedPersonBlackService.findAllActiveListedPersonBlack(); if(listedPersonsBlack.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapListedPersonBlackToDto(listedPersonsBlack), null), HttpStatus.OK); } //-------------------Retrieve All ListedPersonBlack By Search-------------------------------------------------------- @RequestMapping(value = "/listedpersonblack/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listListedPersonBlackBySearchQuery(@RequestParam String qry) { List<ListedPersonBlack> listedPersonsBlack = listedPersonBlackService.findAllActiveListedPersonBlackBySearchQuery(qry); if(listedPersonsBlack.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapListedPersonBlackToDto(listedPersonsBlack), mapListedPersonBlackToDto(listedPersonsBlack).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve One ListedPersonBlack-------------------------------------------------------- @RequestMapping(value = "/listedpersonblack/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> getListedPersonBlack(@PathVariable("id") long id) { System.out.println("Fetching Module with id " + id); ListedPersonBlack listedPersonBlack = listedPersonBlackService.findById(id); if (listedPersonBlack == null) { System.out.println("Module with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } ModelMapper modelMapper = new ModelMapper(); return new ResponseEntity<ResponseDto>(new ResponseDto(modelMapper.map(listedPersonBlack, LeaveDto.class), null), HttpStatus.OK); } //-------------------Retrieve new ListedPersonGrey count-------------------------------------------------------- @RequestMapping(value = "/listedpersongrey/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countListedPersonGreyOfTheWeek() { int results = listedPersonGreyService.countListedPersonGreyOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All ListedPersonGrey-------------------------------------------------------- @RequestMapping(value = "/listedpersongrey", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllListedPersonGrey() { List<ListedPersonGrey> listedPersonsGrey = listedPersonGreyService.findAllActiveListedPersonGrey(); if(listedPersonsGrey.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapListedPersonGreyToDto(listedPersonsGrey), null), HttpStatus.OK); } //-------------------Retrieve All ListedPersonGrey By Search-------------------------------------------------------- @RequestMapping(value = "/listedpersongrey/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listListedPersonGreyBySearchQuery(@RequestParam String qry) { List<ListedPersonGrey> listedPersonsGrey = listedPersonGreyService.findAllActiveListedPersonGreyBySearchQuery(qry); if(listedPersonsGrey.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapListedPersonGreyToDto(listedPersonsGrey), mapListedPersonGreyToDto(listedPersonsGrey).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve One ListedPersonGrey-------------------------------------------------------- @RequestMapping(value = "/listedpersongrey/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> getListedPersonGrey(@PathVariable("id") long id) { System.out.println("Fetching Module with id " + id); ListedPersonGrey listedPersonGrey = listedPersonGreyService.findById(id); if (listedPersonGrey == null) { System.out.println("Module with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } ModelMapper modelMapper = new ModelMapper(); return new ResponseEntity<ResponseDto>(new ResponseDto(modelMapper.map(listedPersonGrey, LeaveDto.class), null), HttpStatus.OK); } //-------------------Retrieve new ListedPersonPep count-------------------------------------------------------- @RequestMapping(value = "/listedpersonpep/count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> countListedPersonPepOfTheWeek() { int results = listedPersonPepService.countListedPersonPepOfTheWeek(); return new ResponseEntity<ResponseDto>(new ResponseDto(results, null), HttpStatus.OK); } //-------------------Retrieve All ListedPersonPep-------------------------------------------------------- @RequestMapping(value = "/listedpersonpep", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllListedPersonPep() { List<ListedPersonPep> listedPersonsPep = listedPersonPepService.findAllActiveListedPersonPep(); if(listedPersonsPep.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapListedPersonPepToDto(listedPersonsPep), null), HttpStatus.OK); } //-------------------Retrieve All ListedPersonPep By Search-------------------------------------------------------- @RequestMapping(value = "/listedpersonpep/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listListedPersonPepBySearchQuery(@RequestParam String qry) { List<ListedPersonPep> listedPersonsPep = listedPersonPepService.findAllActiveListedPersonPepBySearchQuery(qry); if(listedPersonsPep.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapListedPersonPepToDto(listedPersonsPep), mapListedPersonPepToDto(listedPersonsPep).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve One ListedPersonPep-------------------------------------------------------- @RequestMapping(value = "/listedpersonpep/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> getListedPersonPep(@PathVariable("id") long id) { System.out.println("Fetching Module with id " + id); ListedPersonPep listedPersonPep = listedPersonPepService.findById(id); if (listedPersonPep == null) { System.out.println("Module with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } ModelMapper modelMapper = new ModelMapper(); return new ResponseEntity<ResponseDto>(new ResponseDto(modelMapper.map(listedPersonPep, LeaveDto.class), null), HttpStatus.OK); } //-------------------Retrieve All ListedPersonWebsiteLink-------------------------------------------------------- @RequestMapping(value = "/listedpersonwebsitelink", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllListedPersonWebsiteLinks() { List<ListedPersonWebsiteLink> listedPersonWebsiteLinks = listedPersonWebsiteLinkService.findAllActiveListedPersonWebsiteLinks(); if(listedPersonWebsiteLinks.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } List<ListedPersonWebsiteLinkDto> listedPersonWebsiteLinksDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(ListedPersonWebsiteLink listedPersonWebsiteLink: listedPersonWebsiteLinks){ listedPersonWebsiteLinksDtoList.add(modelMapper.map(listedPersonWebsiteLink, ListedPersonWebsiteLinkDto.class)); } return new ResponseEntity<ResponseDto>(new ResponseDto(listedPersonWebsiteLinksDtoList, null), HttpStatus.OK); } //-------------------Retrieve All Jubilaris-------------------------------------------------------- @RequestMapping(value = "/jubilaris", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllJubilaris() { List<Jubilaris> jubilarisList = jubilarisService.findAllActiveJubilaris(); if(jubilarisList.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapJubilarisToDto(jubilarisList), null), HttpStatus.OK); } //------------------- HELPER METHODS -------------------------------------------------------- public List<NewsBasisDto> mapNewsToDto(List<News> news) { List<NewsBasisDto> newsBasisDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(News newsItem: news){ NewsToDisplayDto newsToDisplayDto = modelMapper.map(newsItem, NewsToDisplayDto.class); if(newsItem instanceof NewsHrm) newsToDisplayDto.setNewsBy(Constant.HRM); if(newsItem instanceof NewsIct) newsToDisplayDto.setNewsBy(Constant.ICT); if(newsItem instanceof NewsMarketing) newsToDisplayDto.setNewsBy(Constant.MARKETING); if(newsItem instanceof NewsJobOffer) newsToDisplayDto.setNewsBy(Constant.JOB_OFFER); if(newsItem instanceof NewsHwo) newsToDisplayDto.setNewsBy(Constant.HWO); if(newsItem instanceof NewsPv) newsToDisplayDto.setNewsBy(Constant.PV); if(newsItem instanceof NewsCompliance) newsToDisplayDto.setNewsBy(Constant.COMPLIANCE); if(newsItem instanceof NewsExb) newsToDisplayDto.setNewsBy(Constant.EXB); newsToDisplayDto.setAttachement(encodeFileToBase64Binary(newsItem.getAttachement(), newsItem)); newsBasisDtoList.add(newsToDisplayDto); } return newsBasisDtoList; } // public List<NewsBasisDto> mapLatestNewsToDto(List<News> news) { // List<NewsBasisDto> newsBasisDtoList = new ArrayList<>(); // ModelMapper modelMapper = new ModelMapper(); // for(News newsItem: news) { // NewsToDisplayDto newsToDisplayDto = modelMapper.map(newsItem, NewsToDisplayDto.class); // if (newsItem instanceof NewsHrm) newsToDisplayDto.setNewsBy(Constant.HRM); // if (newsItem instanceof NewsIct) newsToDisplayDto.setNewsBy(Constant.ICT); // if (newsItem instanceof NewsMarketing) newsToDisplayDto.setNewsBy(Constant.MARKETING); // if (newsItem instanceof NewsJobOffer) newsToDisplayDto.setNewsBy(Constant.JOB_OFFER); // if (newsItem instanceof NewsHwo) newsToDisplayDto.setNewsBy(Constant.HWO); // if (newsItem instanceof NewsPv) newsToDisplayDto.setNewsBy(Constant.PV); // if (newsItem instanceof NewsCompliance) newsToDisplayDto.setNewsBy(Constant.COMPLIANCE); // if (newsItem instanceof NewsExb) newsToDisplayDto.setNewsBy(Constant.EXB); // newsToDisplayDto.setAttachement(encodeFileToBase64Binary(newsItem.getAttachement(), newsItem)); // newsBasisDtoList.add(newsToDisplayDto); // // } // // return newsBasisDtoList; // } public List<NewsBasisDto> mapNewsJobOfferToDto(List<NewsJobOffer> newsJobOffer) { List<NewsBasisDto> newsJobOfferBasisDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(News newsJobOfferItem: newsJobOffer){ if(newsJobOfferItem instanceof NewsJobOffer){ NewsJobOfferToDisplayDto newsJobOfferToDisplayDto = modelMapper.map(newsJobOfferItem, NewsJobOfferToDisplayDto.class); newsJobOfferToDisplayDto.setNewsBy(Constant.JOB_OFFER); newsJobOfferToDisplayDto.setStatus(((NewsJobOffer) newsJobOfferItem).getStatus().getName()); newsJobOfferToDisplayDto.setAttachement(encodeFileToBase64Binary(newsJobOfferItem.getAttachement(), newsJobOfferItem)); newsJobOfferBasisDtoList.add(newsJobOfferToDisplayDto); } } return newsJobOfferBasisDtoList; } public List<NewsBasisDto> mapNewsHwoToDto(List<NewsHwo> newsHwo) { List<NewsBasisDto> newsHwoBasisDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(News newsHwoItem: newsHwo){ if(newsHwoItem instanceof NewsHwo){ NewsHwoToDisplayDto newsHwoToDisplayDto = modelMapper.map(newsHwoItem, NewsHwoToDisplayDto.class); newsHwoToDisplayDto.setNewsBy(Constant.HWO); newsHwoToDisplayDto.setAttachement(encodeFileToBase64Binary(newsHwoItem.getAttachement(), newsHwoItem)); newsHwoBasisDtoList.add(newsHwoToDisplayDto); } } return newsHwoBasisDtoList; } public List<NewsBasisDto> mapNewsPvToDto(List<NewsPv> newsPv) { List<NewsBasisDto> newsPvBasisDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(News newsPvItem: newsPv){ if(newsPvItem instanceof NewsPv){ NewsPvToDisplayDto newsPvToDisplayDto = modelMapper.map(newsPvItem, NewsPvToDisplayDto.class); newsPvToDisplayDto.setNewsBy(Constant.PV); newsPvToDisplayDto.setAttachement(encodeFileToBase64Binary(newsPvItem.getAttachement(), newsPvItem)); newsPvBasisDtoList.add(newsPvToDisplayDto); } } return newsPvBasisDtoList; } public static String encodeFileToBase64Binary(byte[] bytes, News news){ if(news.getAttachementName() != null) { String mimeType = URLConnection.guessContentTypeFromName(news.getAttachementName()); if (mimeType.contentEquals(Constant.IMAGE_JPEG_MIME_TYPE)) { return Constant.JPG_BASE64_PREFIX + Base64.encodeBase64String(bytes); } else if (mimeType.contentEquals(Constant.IMAGE_PNG_MIME_TYPE)) { return Constant.PNG_BASE64_PREFIX + Base64.encodeBase64String(bytes); }else if (mimeType.contentEquals(Constant.FILE_ZIP_MIME_TYPE)){ return Constant.ZIP_BASE64_PREFIX + Base64.encodeBase64String(bytes); }else if (mimeType.contentEquals(Constant.FILE_PDF_MIME_TYPE)){ return Constant.PDF_BASE64_PREFIX + Base64.encodeBase64String(bytes); }else { return Constant.OCTET_STREAM_BASE64_PREFIX + Base64.encodeBase64String(bytes); } } return null; } public List<RelationshipAccountBasisDto> mapRelationshipAccountToDto(List<RelationshipAccount> relationshipAccounts) { List<RelationshipAccountBasisDto> relationshipAccountDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addMappings(new RelationshipAccountToDtoMap()); for(RelationshipAccount relationshipAccount : relationshipAccounts){ RelationshipAccountToDisplayDto relationshipAccountToDisplayDto = modelMapper.map(relationshipAccount, RelationshipAccountToDisplayDto.class); if(relationshipAccount instanceof RelationshipAccountManager) { relationshipAccountToDisplayDto.setFunction(Constant.RELATIONSHIP_MANAGER); relationshipAccountToDisplayDto.setRelationshipManagerFullName(((RelationshipAccountManager) relationshipAccount).getRelationshipManager().getLastName() +" "+ ((RelationshipAccountManager) relationshipAccount).getRelationshipManager().getFirstName()); relationshipAccountToDisplayDto.setOfficerFullName(((RelationshipAccountManager) relationshipAccount).getRelationshipManager().getLastName() +" "+ ((RelationshipAccountManager) relationshipAccount).getRelationshipManager().getFirstName()); } if(relationshipAccount instanceof RelationshipAccountOfficer) { relationshipAccountToDisplayDto.setFunction(Constant.RELATIONSHIP_OFFICER); relationshipAccountToDisplayDto.setRelationshipManagerFullName(((RelationshipAccountOfficer) relationshipAccount).getRelationshipManager().getLastName() +" "+ ((RelationshipAccountOfficer) relationshipAccount).getRelationshipManager().getFirstName()); relationshipAccountToDisplayDto.setOfficerFullName(((RelationshipAccountOfficer) relationshipAccount).getRelationshipOfficer().getLastName() +" "+ ((RelationshipAccountOfficer) relationshipAccount).getRelationshipOfficer().getFirstName()); } if(relationshipAccount instanceof RelationshipCrossSellOfficer) { relationshipAccountToDisplayDto.setFunction(Constant.CROSS_SELL_OFFICER); relationshipAccountToDisplayDto.setRelationshipManagerFullName(((RelationshipCrossSellOfficer) relationshipAccount).getRelationshipManager().getLastName() +" "+ ((RelationshipCrossSellOfficer) relationshipAccount).getRelationshipManager().getFirstName()); relationshipAccountToDisplayDto.setOfficerFullName(((RelationshipCrossSellOfficer) relationshipAccount).getCrossSellOfficer().getLastName() +" "+ ((RelationshipCrossSellOfficer) relationshipAccount).getCrossSellOfficer().getFirstName()); } if(relationshipAccount instanceof ProblemLoanOfficer) { relationshipAccountToDisplayDto.setFunction(Constant.PROBLEM_LOAN_OFFICER); relationshipAccountToDisplayDto.setRelationshipManagerFullName(((ProblemLoanOfficer) relationshipAccount).getRelationshipManager().getLastName() +" "+ ((ProblemLoanOfficer) relationshipAccount).getRelationshipManager().getFirstName()); relationshipAccountToDisplayDto.setOfficerFullName(((ProblemLoanOfficer) relationshipAccount).getProblemLoanOfficer().getLastName() +" "+ ((ProblemLoanOfficer) relationshipAccount).getProblemLoanOfficer().getFirstName()); } relationshipAccountToDisplayDto.setBusinessAccountTypeName(relationshipAccount.getBusinessAccountType().getName()); relationshipAccountDtoList.add(relationshipAccountToDisplayDto); } return relationshipAccountDtoList; } public List<BlackListedPersonBasisDto> mapBlackListedPersonToDto(List<BlackListedPerson> blackListedPersons) { List<BlackListedPersonBasisDto> blackListedPersonBasisDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(BlackListedPerson blackListedPersonItem: blackListedPersons){ BlackListedPersonToDisplayDto blackListedPersonToDisplayDto = modelMapper.map(blackListedPersonItem, BlackListedPersonToDisplayDto.class); if(blackListedPersonItem instanceof BlackListedPersonCompliance) blackListedPersonToDisplayDto.setListedBy(Constant.COMPLIANCE); if(blackListedPersonItem instanceof BlackListedPersonRetailBanking) blackListedPersonToDisplayDto.setListedBy(Constant.RETAIL_BANKING); blackListedPersonBasisDtoList.add(blackListedPersonToDisplayDto); } return blackListedPersonBasisDtoList; } public List<RatesToDisplayDto> mapRatesToDto(List<Rates> rates) { List<RatesToDisplayDto> ratesToDisplayDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addMappings(new RatesToDtoMap()); for(Rates ratesItem: rates){ RatesToDisplayDto ratesToDisplayDto = modelMapper.map(ratesItem, RatesToDisplayDto.class); if(ratesItem instanceof RatesControlling) ratesToDisplayDto.setRatesBy(Constant.CONTROLLING); if(ratesItem instanceof RatesIad) ratesToDisplayDto.setRatesBy(Constant.IAD); if(ratesItem instanceof RatesPaymentSettlements) ratesToDisplayDto.setRatesBy(Constant.PAYMENTS_SETTLEMENTS); if(ratesItem instanceof RatesRetailBanking) ratesToDisplayDto.setRatesBy(Constant.RETAIL_BANKING); if(ratesItem instanceof RatesSalesAdministration) ratesToDisplayDto.setRatesBy(Constant.SALES_ADMINISTRATION); if(ratesItem instanceof RatesTreasurySecurities) ratesToDisplayDto.setRatesBy(Constant.TREASURY_SECURITIES); ratesToDisplayDto.setCurrencyName(ratesItem.getCurrency().getName()); ratesToDisplayDtoList.add(ratesToDisplayDto); } return ratesToDisplayDtoList; } public List<PosMerchantDto> mapPosMerchantToDto(List<PosMerchant> posMerchant) { List<PosMerchantDto> posMerchantDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addMappings(new PosMerchantToDtoMap()); for(PosMerchant posMerchantItem: posMerchant){ PosMerchantDto posMerchantDto = modelMapper.map(posMerchantItem, PosMerchantDto.class); posMerchantDtoList.add(posMerchantDto); } return posMerchantDtoList; } public List<AtmDto> mapAtmToDto(List<Atm> atm) { List<AtmDto> atmDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addMappings(new AtmToDtoMap()); for(Atm atmItem: atm){ AtmDto atmDto = modelMapper.map(atmItem, AtmDto.class); atmDtoList.add(atmDto); } return atmDtoList; } public List<DistrictDto> mapDistrictToDto(List<District> district) { List<DistrictDto> districtDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(District districtItem: district){ DistrictDto districtDto = modelMapper.map(districtItem, DistrictDto.class); districtDtoList.add(districtDto); } return districtDtoList; } public List<InterestBasisDto> mapInterestToDto(List<Interest> interest) { List<InterestBasisDto> interestBasisDtoList = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); for(Interest interestItem: interest){ InterestToDisplayDto interestToDisplayDto = modelMapper.map(interestItem, InterestToDisplayDto.class); if(interestItem instanceof InterestSavingsAccount) interestToDisplayDto.setCategory(Constant.SAVINGS_ACCOUNT); if(interestItem instanceof InterestCurrentAccount) interestToDisplayDto.setCategory(Constant.CURRENT_ACCOUNT); if(interestItem instanceof InterestTimeAccount) interestToDisplayDto.setCategory(Constant.TIME_ACCOUNT); interestBasisDtoList.add(interestToDisplayDto); } return interestBasisDtoList; } }
package com.tobe.springcloudfeignlearning; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.feign.EnableFeignClients; @SpringBootApplication @EnableFeignClients public class SpringCloudFeignLearningApplication { @Autowired private MailClient mailClient; public static void main(String[] args) { SpringApplication.run(SpringCloudFeignLearningApplication.class, args); } }
package com.cxhello.sign.controller; import com.cxhello.sign.entity.UserSignVo; import com.cxhello.sign.exception.BusinessException; import com.cxhello.sign.util.Result; import com.cxhello.sign.util.ResultUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.BitFieldSubCommands; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.List; /** * @author cxhello * @date 2021/7/29 */ @RestController public class UserSignController { public final static String USER_SIGN_IN = "userSign:%d:%d"; @Autowired private StringRedisTemplate stringRedisTemplate; /** * 签到接口 * @param id * @return */ @GetMapping(value = "/sign/{id}") public Result sign(@PathVariable Long id) { String userSignInKey = String.format(USER_SIGN_IN, LocalDate.now().getYear(), id); long day = Long.parseLong(LocalDate.now().format(DateTimeFormatter.ofPattern("MMdd"))); if (stringRedisTemplate.opsForValue().getBit(userSignInKey, day)) { throw new BusinessException("今日已签到"); } stringRedisTemplate.opsForValue().setBit(userSignInKey, day, true); return ResultUtils.success(); } @GetMapping(value = "/getSignInfo/{id}") public Result getSignInfo(@PathVariable Long id) { String userSignInKey = String.format(USER_SIGN_IN, LocalDate.now().getYear(), id); LocalDate localDate = LocalDate.now(); // 当年累计签到天数 Long totalDays = stringRedisTemplate.execute((RedisCallback<Long>) connection -> connection.bitCount(userSignInKey.getBytes())); // 当年连续签到天数 int signCount = 0; List<Long> longList = stringRedisTemplate.opsForValue().bitField(userSignInKey, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.signed(localDate.getDayOfMonth())).valueAt(localDate.getMonthValue() * 100 + 1)); if (longList != null && longList.size() > 0) { //可能该用户这个月就没有签到过,需要判断一下,如果是空就给一个默认值0 long v = longList.get(0) == null ? 0 : longList.get(0); for (int i = 0; i < localDate.getDayOfMonth(); i++) { // 如果是连续签到得到的long值右移一位再左移一位后与原始值不相等,代表低位为1,连续天数加一 if (v >> 1 << 1 == v) { break; } signCount += 1; v >>= 1; } } long day = Long.parseLong(LocalDate.now().format(DateTimeFormatter.ofPattern("MMdd"))); // 今日是否签到 int isSign = stringRedisTemplate.opsForValue().getBit(userSignInKey, day) ? 1 : 0; UserSignVo userSignVo = new UserSignVo(); userSignVo.setTotalDays(totalDays); userSignVo.setSignCount(signCount); userSignVo.setIsSign(isSign); return ResultUtils.result(userSignVo); } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.types.basic; import pl.edu.icm.unity.exceptions.IllegalAttributeValueException; import pl.edu.icm.unity.exceptions.InternalException; import pl.edu.icm.unity.types.JsonSerializable; /** * Base interface defining attribute value type. It provides handling of the * configuration (typically used server side to validate values), (de)serialization * which can be used on both sides and equality test. * <p> * Implementations can offer arbitrary constructors, however it is preferable to * offer also a special extension of {@link Attribute} class, which uses the * provided implementation of this interface so {@link Attribute} class instances * can be easily created without an instance of {@link AttributeValueSyntax}. * * Note that validation is only meaningful when the implementation was properly * populated with configuration. So if an instance is created ad-hoc on the client side, * then validation probably won't work as on the server side. * * @author K. Benedyczak */ public interface AttributeValueSyntax<T> extends JsonSerializable { /** * @return attribute value syntax ID */ String getValueSyntaxId(); /** * Validates the value * @param value */ void validate(T value) throws IllegalAttributeValueException; /** * @param value * @param another * @return true only if the two values are the same. */ boolean areEqual(T value, Object another); /** * @param value, must be of T type, otherwise the standard hash should be returned. * @return java hashcode of the value */ int hashCode(Object value); /** * @param domain object * @return value in the byte array form * @throws InternalException */ byte[] serialize(T value) throws InternalException; /** * @param domain object * @return value in the form of an object directly serializable to Json (either simple object, map or JsonNode). * @throws InternalException */ Object serializeSimple(T value) throws InternalException; /** * @param value to deserialize * @return domain object * @throws InternalException */ T deserializeSimple(Object value) throws InternalException; /** * @param raw data * @return domain object * @throws InternalException */ T deserialize(byte []raw) throws InternalException; /** * @return true if values can be confirmed by user */ boolean isVerifiable(); /** * Many attributes are passed in a string form, especially when obtained externally. Whenever it is possible * this method should convert the string representation to the domain object. * @param stringRepresentation * @return * @throws IllegalAttributeValueException if the conversion can not be performed. */ T convertFromString(String stringRepresentation) throws IllegalAttributeValueException; }
package ru.forpda.example.an21utools; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.os.IBinder; import ru.forpda.example.an21utools.model.AutoRunModel; import ru.forpda.example.an21utools.model.ModelFactory; import ru.forpda.example.an21utools.util.LogHelper; import ru.forpda.example.an21utools.util.SysUtils; import java.util.Date; /** * Created by max on 31.10.2014. * Воновый сервис предполагаеться что это он будеть запускать приложения */ public class BackgroudService extends IntentService { public BackgroudService() { super("BackgroudService"); } private static LogHelper Log = new LogHelper(BackgroudService.class); NotificationManager notificationManager; @Override public void onCreate() { super.onCreate(); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Log.d("Create"); } @Override public IBinder onBind(Intent intent) { Log.d("OnBind"); return null; } @Override public void onDestroy() { super.onDestroy(); Log.d("Destroy"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override protected void onHandleIntent(Intent intent) { int notifyID = 1; AutoRunModel model = ModelFactory.getAutoRunModel(); // ничего не делаем пока if (!model.isStarting()){ Log.d("отключен автоматический запуск"); return; } if (model.getAppInfoList().size()==0){ Log.d("количество запускаемых приложений =0"); return; } Notification.Builder builder = new Notification.Builder(this) .setContentTitle("Автозапуск приложений") .setContentText("Ожидание запуска") .setSmallIcon(R.drawable.ic_terminal); Notification notification = null; try { // Первоначальный останов задержка notification = builder.build(); startForeground(notifyID, notification ); notificationManager.notify(notifyID,notification); Thread.sleep(model.getStartDelay()); // пошли по приложениям for (int i=0;i<model.getAppInfoList().size();i++){ String pakageName =model.getAppInfoList().get(i).getName(); String info = String.format("Запускаем -> %s", pakageName); Log.d(info); builder.setContentText(info); builder.setProgress(model.getAppInfoList().size(),i+1,false); notification = builder.build(); notificationManager.notify(notifyID,notification); startForeground(notifyID, notification ); try { SysUtils.runAndroidPackage(pakageName); Thread.sleep(model.getApplicationDelay()); } catch (Exception e) { Log.e("ошибка запуска",e); } } builder.setContentText("Завершение"); builder.setProgress(0,0,false); notification = builder.build(); notificationManager.notify(notifyID,notification); Thread.sleep(100); if (model.isShitchToHomeScreen()){ Intent startMain = new Intent(Intent.ACTION_MAIN); startMain.addCategory(Intent.CATEGORY_HOME); startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(startMain); } } catch (InterruptedException e) { e.printStackTrace(); } stopForeground(true); notificationManager.cancel(notifyID); } }
package webshop.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import webshop.domain.Product; import webshop.dto.ProductAdapter; import webshop.dto.ProductDTO; import webshop.dto.ProductOrderedEventDTO; import webshop.respository.ProductRepository; import java.util.Map; import java.util.Optional; @Service public class ProductServiceImpl implements ProductService{ private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class.getName()); @Autowired private ProductRepository productRepository; @Override public ProductDTO add(ProductDTO productDTO) { logger.info("Calling add product"); Product product = ProductAdapter.fromDTO(productDTO); productRepository.save(product); logger.info("Adding new product"); return ProductAdapter.toDTO(product); } @Override public void remove(String id) { productRepository.deleteById(id); } @Override public ProductDTO update(String id, ProductDTO productDTO) { logger.info("Calling update"); Optional<Product> optionalProduct = productRepository.findById(id); if(optionalProduct.isPresent()){ Product product = ProductAdapter.fromDTO(productDTO); productRepository.save(product); logger.info("Updating product"); return ProductAdapter.toDTO(product); } logger.error("Product update with invalid id"); return null; } @Override public ProductDTO addToStock(String id, int addedQuantity) { logger.info("Calling add To Stock"); Optional<Product> optionalProduct = productRepository.findById(id); if(optionalProduct.isPresent()){ Product product = optionalProduct.get(); product.setNumberInStock(product.getNumberInStock() + addedQuantity); productRepository.save(product); logger.info("Adding quantity to stock"); return ProductAdapter.toDTO(product); } logger.error("Add to stock with invalid id"); return null; } @Override public ProductDTO removeFromStock(String id, int soldQuantity) { logger.info("Calling remove from Stock"); Optional<Product> optionalProduct = productRepository.findById(id); if(optionalProduct.isPresent()){ Product product = optionalProduct.get(); product.setNumberInStock(product.getNumberInStock() - soldQuantity); productRepository.save(product); logger.info("Removing quantity from stock"); return ProductAdapter.toDTO(product); } logger.error("Remove from stock with invalid id"); return null; } @Override public void handle(ProductOrderedEventDTO productOrderedEventDTO) { logger.info("Calling handle"); Map<String,Integer> productMap = productOrderedEventDTO.getOrderedProductsMap(); for (String key: productMap.keySet()){ removeFromStock(key,productMap.get(key)); } logger.info("Handling Product Ordered Event"); } @Override public ProductDTO getProduct(String id) { logger.info("Calling get product"); Optional<Product> optionalProduct = productRepository.findById(id); if(optionalProduct.isPresent()){ logger.info("Getting product"); return ProductAdapter.toDTO(optionalProduct.get()); } logger.error("Invalid Id."); return null; } }
package ir.madreseplus.ui.view.login; import java.util.List; import ir.madreseplus.data.model.req.Student; import ir.madreseplus.data.model.req.User; import ir.madreseplus.data.model.res.ConfirmRes; import ir.madreseplus.utilities.BaseNavigator; import retrofit2.Response; public interface LoginNavigator<T> extends BaseNavigator { void error(Throwable throwable); void login(User userResponse); void password(T t); void profile(List<Student> students); void confirmResult(ConfirmRes response); }
package com.taotao.item.listener; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import com.taotao.item.pojo.Item; import com.taotao.pojo.TbItem; import com.taotao.pojo.TbItemDesc; import com.taotao.service.ItemService; import freemarker.template.Configuration; import freemarker.template.Template; public class ItemAddMessageListener implements MessageListener { @Autowired private ItemService itemService; @Autowired private FreeMarkerConfigurer freeMarkerConfigurer; @Value("${HTML_OUT_PATH}") private String HTML_OUT_PATH;//保存的路径 @Override public void onMessage(Message message){ try { TextMessage textMessage = (TextMessage) message; String itemIdStr = textMessage.getText(); Long itemId = Long.parseLong(itemIdStr); Thread.sleep(1000); TbItem tbItem = itemService.getItemById(itemId); TbItemDesc itemDesc = itemService.getDescById(itemId); Item item = new Item(tbItem); //使用freemarker生成静态页面 Configuration configuration = freeMarkerConfigurer.getConfiguration(); //创建模板并加载模板对象 Template template = configuration.getTemplate("item.ftl"); //准备模板需要的数据 Map data = new HashMap<>(); data.put("item", item); data.put("itemDesc", itemDesc); //指定输出的目录及文件名 OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(new File(HTML_OUT_PATH+itemIdStr+".html")),"UTF-8"); //生成静态页面 template.process(data, out); //关闭流 out.close(); } catch (Exception e) { e.printStackTrace(); } } }
package com.madrapps.dagger.subcomponent.simple; import com.madrapps.dagger.models.Cycle; import dagger.Component; @Component(modules = {SimpleSubComponent.InstallSubComponentModule.class, SimpleRootModule.class}) public interface SimpleRootComponent { Cycle obtainVehicle(); SeaWays seaways(); }
package common.constant; public class ValueConstants { public static final int REGION_NUMS = 6; }
package com.axibase.tsd.api.method.entity; import com.axibase.tsd.api.model.entity.Entity; import com.axibase.tsd.api.util.Registry; import org.testng.annotations.Test; import static com.axibase.tsd.api.method.entity.EntityTest.assertEntityExisting; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static org.testng.AssertJUnit.assertEquals; /** * @author Dmitry Korchagin. */ public class EntityGetTest extends EntityMethod { /* #1278 */ @Test public void testEntityNameContainsWhitespace() throws Exception { final String name = "getentity 1"; Registry.Entity.register(name); assertEquals("Method should fail if entityName contains whitespace", BAD_REQUEST.getStatusCode(), getEntityResponse(name).getStatus()); } /* #1278 */ @Test public void testEntityNameContainsSlash() throws Exception { Entity entity = new Entity("getentity/2"); createOrReplaceEntityCheck(entity); assertEntityExisting(entity); } /* #1278 */ @Test public void testEntityNameContainsCyrillic() throws Exception { Entity entity = new Entity("getйёentity3"); createOrReplaceEntityCheck(entity); assertEntityExisting(entity); } }
/** * Makes an Alien that attacks the base * @author Rishav Bose * @version 1.00 */ public class Alien8 extends Monster { /** * Makes an alien with health 100 */ public Alien8() { super(100, "provided/res/Pixel-Alien-8.png"); } /** * Attacks the base with 400 attack * @param a the base to hurt */ public void attack(Base a) { a.hurt(400); } }
package org.controlsfx.control.images; import impl.org.controlsfx.behavior.ClickItemBehavior; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import mw.wspolne.model.Obrazek; import org.controlsfx.control.Rating; import org.controlsfx.control.SmallRating; import org.controlsfx.control.button.FontAwesomeButton; import org.controlsfx.glyphfont.FontAwesome; import org.controlsfx.glyphfont.Glyph; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; /** * Created by mw on 24.08.16. */ public class LargeImageWithRating extends VBox { private int DEFAULT_THUMBNAIL_WIDTH = 600; private ClickItemBehavior<Obrazek> onClickCallback; private ImageView imageView; private Rating rating; private Label name; private Obrazek obrazek; private Button przyciskUsun; public LargeImageWithRating(Obrazek aObrazek, ClickItemBehavior aOnClickCallback) { super(); obrazek = aObrazek; getStyleClass().add("large-image"); name = new Label(aObrazek.getSciezka().getFileName().toString()); imageView = createImageView(aObrazek.getSciezka(), aOnClickCallback); rating = new SmallRating(); rating.setRating(obrazek.getOcena()); rating.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { obrazek.setOcena(rating.getRating()); } }); przyciskUsun = new FontAwesomeButton(24, FontAwesome.Glyph.TRASH); przyciskUsun.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { rating.setRating(0); obrazek.setOcena(0); } }); this.setSpacing(20); this.getChildren().add(imageView); this.getChildren().add(rating); this.getChildren().add(przyciskUsun); this.getChildren().add(name); } private ImageView createImageView(final Path imageFile, ClickItemBehavior aOnClickCallback) { // DEFAULT_THUMBNAIL_WIDTH is a constant you need to define // The last two arguments are: preserveRatio, and use smooth (slower) // resizing onClickCallback = aOnClickCallback; ImageView imageView = null; try { final Image image = new Image(Files.newInputStream(imageFile)); imageView = new ImageView(image); if (image.getHeight() > image.getWidth()) { imageView.setFitHeight(DEFAULT_THUMBNAIL_WIDTH); } else { imageView.setFitWidth(DEFAULT_THUMBNAIL_WIDTH); } imageView.setPreserveRatio(true); imageView.setSmooth(true); imageView.setCache(true); imageView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) { if (mouseEvent.getClickCount() == 2) { onClickCallback.clickItem(obrazek); } } } }); } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } catch (IOException e) { new IllegalArgumentException(e); } return imageView; } public ImageView getImageView() { return imageView; } public Rating getRating() { return rating; } }
package br.com.wasys.gfin.cheqfast.cliente.realm; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; import io.realm.annotations.Required; /** * Created by pascke on 04/07/17. */ public class Arquivo extends RealmObject { @PrimaryKey public Long id; @Required public String caminho; public Digitalizacao digitalizacao; }
package com.gxtc.huchuan.ui.mine.browsehistory; import com.gxtc.commlibrary.utils.ErrorCodeUtil; import com.gxtc.huchuan.bean.BrowseHistoryBean; import com.gxtc.huchuan.data.BrowseHistoryRepository; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.http.ApiCallBack; import java.util.ArrayList; import java.util.List; /** * Describe: * Created by ALing on 2017/5/16 . */ public class BrowseHistoryPresenter implements BrowseHistoryContract.Presenter { private BrowseHistoryContract.Source mData; private BrowseHistoryContract.View mView; private int start = 0; private String token = UserManager.getInstance().getToken(); public BrowseHistoryPresenter(BrowseHistoryContract.View mView) { this.mView = mView; this.mView.setPresenter(this); mData = new BrowseHistoryRepository(); } @Override public void start() { } @Override public void destroy() { } @Override public void getData(final boolean isRefresh) { if(isRefresh){ start = 0; }else{ if(mView == null) return; mView.showLoad(); } mData.getData(token,0+"", new ApiCallBack<List<BrowseHistoryBean>>() { @Override public void onSuccess(List<BrowseHistoryBean> data) { if(mView == null) return; mView.showLoadFinish(); if(data == null || data.size() == 0){ mView.showEmpty(); return ; } if(isRefresh){ mView.showRefreshFinish(data); }else{ mView.showData(data); } } @Override public void onError(String errorCode, String message) { if(mView == null) return; mView.showLoadFinish(); ErrorCodeUtil.handleErr(mView,errorCode,message); } }); } @Override public void deleteBrowseRecord(String token, ArrayList<String> list) { mView.showLoad(); mData.deleteBrowseRecord(token,list, new ApiCallBack<List<Object>>() { @Override public void onSuccess(List<Object> data) { mView.showLoadFinish(); mView.showDelResult(data); } @Override public void onError(String errorCode, String message) { mView.showLoadFinish(); ErrorCodeUtil.handleErr(mView,errorCode,message); } }); } @Override public void loadMore() { start += 15; mData.getData(token,start+"", new ApiCallBack<List<BrowseHistoryBean>>() { @Override public void onSuccess(List<BrowseHistoryBean> data) { if(data == null || data.size() == 0){ mView.showNoMore(); return ; } mView.showLoadMore(data); } @Override public void onError(String errorCode, String message) { start += 15; mView.showLoad(); ErrorCodeUtil.handleErr(mView,errorCode,message); } }); } }
package br.com.fatec.proximatrilha.repository; import org.springframework.data.repository.CrudRepository; import br.com.fatec.proximatrilha.model.Multimedia; public interface MultimediaRepository extends CrudRepository<Multimedia, Long> { }
package me.ewriter.storagedemo; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.storage.StorageManager; import android.support.v4.provider.DocumentFile; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { TextView textView; private static final int REQUEST_DOCUMENT_TREE_CODE = 1234; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.text); } public void BtnExternal1(View view) { String output = ""; // getExternalStorageDirectory 获取的是 外置sd 卡1 的根目录 output += "A:getExternalStorageDirectory= " + Environment.getExternalStorageDirectory().getAbsolutePath() + "\n"; output += "getExternalFilesDir= " + getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "\n"; output += "B:getExternalCacheDir= " + getExternalCacheDir(); textView.setText(output); } public void BtnExternal2(View view) { // 4.4 之后 Context.getExternalFilesDirs(null)(注意最后多了一个’s’),它返回的是一个字符串数组。第0个就是主存储路径,第1个是副存储路径(如果有的话) // if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { // // 这个返回的 file 类型就是 data/package/files // // File[] files = this.getExternalFilesDirs(null); // // 如果指定了 type ,返回的就是 data/package/files/Download // File[] files = this.getExternalFilesDirs(Environment.DIRECTORY_DOWNLOADS); // String output = ""; // for (int i = 0; i < files.length; i++) { // output += files[i].getAbsolutePath() + "\n"; // } // textView.setText(output); // } // 4.4 以下 最好使用反射,然后通过 uri 来操作 Intent intent = new Intent(); intent.setAction("android.intent.action.OPEN_DOCUMENT_TREE"); startActivityForResult(intent, REQUEST_DOCUMENT_TREE_CODE); // // String extSdcardPath = System.getenv("ENV_EXTERNAL_STORAGE"); // Toast.makeText(MainActivity.this, extSdcardPath, Toast.LENGTH_SHORT).show(); // if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { // File[] test = this.getExternalCacheDirs(); // for (int i = 0; i < test.length; i++) { // Log.d("abc", test[i].getAbsolutePath()); // } // // writeSomeThingToSD("sd.text", test[1].getAbsolutePath()); // } else { // // } // List<StorageInfo> fileList = listAvaliableStorage(this); // String path = fileList.get(1).path + File.separator + "Android" + File.separator + // "data" + File.separator + "me.ewriter.storagedemo" + File.separator + // "cache" + File.separator + "test"; // // writeSomeThingToSD("123.txt", path); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_DOCUMENT_TREE_CODE && resultCode == RESULT_OK) { // 返回的inte 是 dat=content://com.android.externalstorage.documents/tree/C431-11E2: flg=0xc3 Log.d("abc", data.toString()); // http://stackoverflow.com/questions/26744842/how-to-use-the-new-sd-card-access-api-presented-for-lollipop // 这个 Uri 最好记录下来,不然每次都得让用户选择 Uri uri = data.getData(); DocumentFile pickedDir = DocumentFile.fromTreeUri(this, uri); Log.d("abc", "DocumentFile canwrite = " + pickedDir.canWrite() + "; canread = " + pickedDir.canRead()); // List all existing files inside picked directory for (DocumentFile file : pickedDir.listFiles()) { Log.d("abc", file.getName() + " with size " + file.length()); } // Create new File and write into it DocumentFile newFile = pickedDir.createFile("text/plain", "My Test"); pickedDir.createDirectory("documentfile"); try { OutputStream out = getContentResolver().openOutputStream(newFile.getUri()); out.write("A longlong agp, 加个中文".getBytes()); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } public List listAvaliableStorage(Context context) { ArrayList storagges = new ArrayList(); StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE); try { Class<?>[] paramClasses = {}; Method getVolumeList = StorageManager.class.getMethod("getVolumeList", paramClasses); getVolumeList.setAccessible(true); Object[] params = {}; Object[] invokes = (Object[]) getVolumeList.invoke(storageManager, params); if (invokes != null) { StorageInfo info = null; for (int i = 0; i < invokes.length; i++) { Object obj = invokes[i]; Method getPath = obj.getClass().getMethod("getPath", new Class[0]); String path = (String) getPath.invoke(obj, new Object[0]); info = new StorageInfo(path); File file = new File(info.path); // 6.0 上还没读写的时候返回的是false,sd卡需要自己申请 Log.d("abc", "file = " + file.getAbsolutePath() + ";exits = " + file.exists() + "; isdirectory = " + file.isDirectory() + "; canwrite= " + file.canWrite() + ";canread= " + file.canRead()); if ((file.exists()) && (file.isDirectory())) { Method isRemovable = obj.getClass().getMethod("isRemovable", new Class[0]); String state = null; try { Method getVolumeState = StorageManager.class.getMethod("getVolumeState", String.class); state = (String) getVolumeState.invoke(storageManager, info.path); info.state = state; } catch (Exception e) { e.printStackTrace(); } if (info.isMounted()) { info.isRemoveable = ((Boolean) isRemovable.invoke(obj, new Object[0])).booleanValue(); storagges.add(info); } } } } } catch (NoSuchMethodException e1) { e1.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } storagges.trimToSize(); return storagges; } public void BtnInternal(View view) { String output = "Internal\n"; output += "A: " + this.getFilesDir().getAbsolutePath() + "\n"; // 会新建 data/data/package/app_demo output += "B: " + this.getDir("demo", Context.MODE_PRIVATE).getAbsolutePath() + "\n"; textView.setText(output); } public void writeSomeThingToSD(String fileName, String path) { try { File file = new File(path, fileName); if (!file.exists()) file.mkdirs(); FileOutputStream fos = new FileOutputStream(file); String output = "sd卡"; byte[] bytes = output.getBytes(); fos.write(bytes); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public String readSomeThingFromSD(String fileName, String path) { try { File file = new File(path, fileName); FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[fileInputStream.available()]; fileInputStream.read(buffer); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public class StorageInfo { public String path; public String state; public boolean isRemoveable; public StorageInfo(String path) { this.path = path; } public boolean isMounted() { return "mounted".equals(state); } } }
/* *비트연산 &:and |:or ~:not ^:xor ex(clusive or) *음수를 표현하는 방법 2의보수 : 1의보수(0>1, 1>0)+1 * */public class BiteOpTest1 { public static void main(String[] args) { // TODO Auto-generated method stub int a=10; int result=~a;//2의보수로 표현 -10:~a+1 => -a:-11 System.out.println(result); int su1=10; int su2=20; int result2=su1|su2;// and 비트 연산 System.out.println(result2); } }
package exemplos.aula11.ex2.domain; public enum TipoUsuario { FUNCIONARIO, SEGURANCA, DIRETOR }