blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
d2c16412b918bfe93e5cf35e36a7070f92f74949
3f30da44835a1d499635dda54a9adf9343359c22
/src/com/miao/util/PageUtil.java
edce169e03f86479a20d1a96c42f4b75f5cb120e
[]
no_license
miaochangchun/javaPrj_2
27e4587fa072b152f3166dfaf81583d63a55cf7b
94e9e4bce309cf2086b41f3bdeabbef53dea69a1
refs/heads/master
2021-01-12T16:01:57.241800
2016-10-29T08:35:34
2016-10-29T08:35:34
71,921,232
0
0
null
null
null
null
GB18030
Java
false
false
2,861
java
package com.miao.util; public class PageUtil { /** * 构造函数,分页辅助类,必须要知道三个参数,当前页,每页显示的记录数以及总记录数,其他参数可以通过这三个参数计算出来。 * @param everyPage 每页显示的记录数 * @param totalCount 总的记录数 * @param currentPage 当前页 * @return */ public static Page createPage(int everyPage, int totalCount, int currentPage){ everyPage = getEveryPage(everyPage); currentPage = getCurrentPage(currentPage); int totalPage = getTotalPage(everyPage, totalCount); int beginIndex = getBeginIndex(everyPage, currentPage); boolean hasPrePage = getHasPrePage(currentPage); boolean hasNextPage = getHasNextPage(totalPage, currentPage); return new Page(everyPage, totalCount, totalPage, currentPage,beginIndex, hasPrePage, hasNextPage); } /** * 是否有下一页,当前页等于总页数没有下一页,总页数为0,也没有下一页 * @param totalPage 总页数 * @param currentPage 当前页 * @return */ private static boolean getHasNextPage(int totalPage, int currentPage) { // TODO Auto-generated method stub return currentPage == totalPage | totalPage == 0 ? false : true; } /** * 是否有上一页 * @param currentPage * @return */ private static boolean getHasPrePage(int currentPage) { // TODO Auto-generated method stub return currentPage == 1 ? false : true; } /** * 获取当前页的起始index数 * @param everyPage 每页显示的记录数 * @param currentPage 当前页 * @return */ private static int getBeginIndex(int everyPage, int currentPage) { // TODO Auto-generated method stub return (currentPage - 1) * everyPage; } /** * 获取总的页数,总的记录数/每页显示的记录数+1 * @param everyPage 每页心事记录数 * @param totalCount 总的记录数 * @return */ private static int getTotalPage(int everyPage, int totalCount) { // TODO Auto-generated method stub int totalPage = 0; if (totalCount != 0 && totalCount % everyPage == 0) { totalPage = totalCount / everyPage; }else { totalPage = totalCount / everyPage + 1; } return totalPage; } /** * 获得当前页的页数,默认位第一页,否则为设置的页数 * @param currentPage 当前页的设置参数 * @return */ private static int getCurrentPage(int currentPage) { // TODO Auto-generated method stub return currentPage == 0 ? 1 : currentPage; } /** * 获得每页显示的记录数,默认是10条记录,如果设置了就使用设置的记录数 * @param everyPage * @return */ private static int getEveryPage(int everyPage) { // TODO Auto-generated method stub return everyPage == 0 ? 10 : everyPage; } }
fdfd0adedf3e3d0c58c5d72cca2f84eb75912a47
abadc4bfecebf2476f84af43dac3e86b6a7c5551
/ATM-Simulator-System/src/FastCash.java
7a1a4f455a551ab57b3d93a9353d02bbfb5fe097
[]
no_license
skdhal/ATM-Simulator-System
135728c9b489ddce62561552935dc4b752edc758
7a6fbb93147cb6e0ddb9f69a1ac783b871f703de
refs/heads/main
2023-06-30T18:54:29.005860
2021-08-05T15:21:28
2021-08-05T15:21:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,459
java
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.sql.*; import java.util.Date; public class FastCash extends JFrame implements ActionListener { JLabel l1, l2; JButton b1, b2, b3, b4, b5, b6, b7, b8; JTextField t1; String pin; FastCash(String pin) { this.pin = pin; ImageIcon i1 = new ImageIcon(ClassLoader.getSystemResource("ASimulatorSystem/icons/atm.jpg")); Image i2 = i1.getImage().getScaledInstance(1000, 1180, Image.SCALE_DEFAULT); ImageIcon i3 = new ImageIcon(i2); JLabel l3 = new JLabel(i3); l3.setBounds(0, 0, 960, 1080); add(l3); l1 = new JLabel("SELECT WITHDRAWL AMOUNT"); l1.setForeground(Color.WHITE); l1.setFont(new Font("System", Font.BOLD, 16)); b1 = new JButton("Rs 100"); b2 = new JButton("Rs 500"); b3 = new JButton("Rs 1000"); b4 = new JButton("Rs 2000"); b5 = new JButton("Rs 5000"); b6 = new JButton("Rs 10000"); b7 = new JButton("BACK"); setLayout(null); l1.setBounds(235, 400, 700, 35); l3.add(l1); b1.setBounds(170, 499, 150, 35); l3.add(b1); b2.setBounds(390, 499, 150, 35); l3.add(b2); b3.setBounds(170, 543, 150, 35); l3.add(b3); b4.setBounds(390, 543, 150, 35); l3.add(b4); b5.setBounds(170, 588, 150, 35); l3.add(b5); b6.setBounds(390, 588, 150, 35); l3.add(b6); b7.setBounds(390, 633, 150, 35); l3.add(b7); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); setSize(960, 1080); setLocation(500, 0); setUndecorated(true); setVisible(true); } public void actionPerformed(ActionEvent ae) { try { String amount = ((JButton)ae.getSource()).getText().substring(3); //k Conn c = new Conn(); ResultSet rs = c.s.executeQuery("select * from bank where pin = '"+pin+"'"); int balance = 0; while (rs.next()) { if (rs.getString("mode").equals("Deposit")) { balance += Integer.parseInt(rs.getString("amount")); } else { balance -= Integer.parseInt(rs.getString("amount")); } } String num = "17"; if (ae.getSource() != b7 && balance < Integer.parseInt(amount)) { JOptionPane.showMessageDialog(null, "Insuffient Balance"); return; } if (ae.getSource() == b7) { this.setVisible(false); new Transactions(pin).setVisible(true); }else{ Date date = new Date(); c.s.executeUpdate("insert into bank values('"+pin+"', '"+date+"', 'Withdrawl', '"+amount+"')"); JOptionPane.showMessageDialog(null, "Rs. "+amount+" Debited Successfully"); setVisible(false); new Transactions(pin).setVisible(true); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new FastCash("").setVisible(true); } }
39d224281c2feba85a0f3fa68cd02fa8f97092ac
9bbeb1267bfb335dad02bf7bbdef1535a4f873bb
/PlanGenerator/src/main/java/com/lendico/task/calculators/InterestCalculator.java
5ce1e5c3706547c7604cf6a44935ec03758c6425
[]
no_license
sravanpalakala/plangenerator
0a23dadd4f42ec53f633c497f887c84e4efc42be
2a039bb7248b5125cc8bbf6b7d2ff800a56a42c8
refs/heads/master
2021-07-06T01:07:43.649536
2019-06-21T17:01:16
2019-06-21T17:11:04
193,130,422
0
0
null
null
null
null
UTF-8
Java
false
false
183
java
package com.lendico.task.calculators; import java.math.BigDecimal; public interface InterestCalculator { BigDecimal getMonthlyInterest(double nominalRate, double principal); }
9d3e2f40938b137dd319d8f526bf7f055573c6c8
1087002f0ba5c7c33a6717b3f29d396d6ea9a076
/src/main/java/javaProject/project/model/EnumerableElement.java
d84618cfa3abc36d7ce6d04e0e9fe8d3ea1ed0ed
[]
no_license
sosthenee/Java_Project
c9bb069607659c42d40014c68646295a9314ba49
3064a5c68bffdf4eb150571f2b001c2a412ad9b4
refs/heads/master
2022-10-11T21:15:29.937539
2020-06-07T20:24:36
2020-06-07T20:24:36
267,106,640
0
0
null
null
null
null
UTF-8
Java
false
false
328
java
/* * 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 javaProject.project.model; /** * * @author sosthene */ public abstract interface EnumerableElement { public String getNom(); }
1536596dc4c2f129f7963fc6c75a2d78733fe7b4
2c60d4e685510f12db277197192a35602384333a
/app/src/main/java/org/metabrainz/mobile/api/handler/ArtistLookupHandler.java
8eec1f70d5d40d475e15b5393c9fda2bbd2aa12e
[]
no_license
anirudhjain75/musicbrainz-android-1
ac8b4b8182ffb933cd8368c05328428fa372d64f
622aace7dce7c07c257f22fb8d558ea298c882de
refs/heads/master
2020-04-21T18:44:24.792864
2019-02-07T18:08:06
2019-02-07T18:08:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,025
java
package org.metabrainz.mobile.api.handler; import org.metabrainz.mobile.api.data.Artist; import org.metabrainz.mobile.api.data.Tag; import org.metabrainz.mobile.api.data.WebLink; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class ArtistLookupHandler extends MBHandler { private boolean inTag; private boolean inUrlRelations; private boolean inArtistRelations; private boolean inLabelRelations; private boolean inLifeSpan; private boolean inUnsupported; private Artist artist = new Artist(); private Tag tag; private WebLink link; public Artist getResult() { return artist; } public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (localName.equals("artist") && !inArtistRelations) { artist.setMbid(atts.getValue("id")); artist.setType(atts.getValue("type")); } else if (localName.equals("name")) { buildString(); } else if (localName.equals("tag")) { inTag = true; buildString(); tag = new Tag(); tag.setCount(Integer.parseInt(atts.getValue("count"))); } else if (localName.equals("rating")) { artist.setRatingCount(Integer.parseInt(atts.getValue("votes-count"))); buildString(); } else if (localName.equals("country")) { buildString(); } else if (localName.equals("relation") && inUrlRelations) { buildString(); link = new WebLink(); link.setType(atts.getValue("type")); } else if (localName.equals("target")) { buildString(); } else if (localName.equals("life-span")) { inLifeSpan = true; } else if (localName.equals("begin")) { buildString(); } else if (localName.equals("end")) { buildString(); } else if (localName.equals("relation-list")) { setRelationStatus(atts.getValue("target-type")); } else if (inUnsupported(localName)) { inUnsupported = true; } } private void setRelationStatus(String type) { if (type.equals("url")) { inUrlRelations = true; } else if (type.equals("artist")) { inArtistRelations = true; } else if (type.equals("label")) { inLabelRelations = true; } } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (localName.equals("name")) { if (inTag) { tag.setText(getString()); artist.addTag(tag); } else if (!inArtistRelations && !inLabelRelations && !inUnsupported) { artist.setName(getString()); } } else if (localName.equals("rating")) { artist.setRating(Float.parseFloat(getString())); } else if (localName.equals("country")) { artist.setCountry(getString()); } else if (localName.equals("relation") && inUrlRelations) { artist.addLink(link); } else if (localName.equals("target") && inUrlRelations) { link.setUrl(getString()); } else if (localName.equals("tag")) { inTag = false; } else if (localName.equals("life-span")) { inLifeSpan = false; } else if (localName.equals("begin") && inLifeSpan) { artist.setBegin(getString()); } else if (localName.equals("end") && inLifeSpan) { artist.setEnd(getString()); } else if (localName.equals("relation-list")) { inUrlRelations = false; inArtistRelations = false; inLabelRelations = false; } else if (inUnsupported(localName)) { inUnsupported = false; } } private boolean inUnsupported(String tag) { return tag.equals("area") || tag.equals("begin-area") || tag.equals("end-area"); } }
3c987e71864fe09d285a0641be86440be3941238
74484efc6f6ca9c2f2298826d22a95d72297097f
/day02_00/src/xiaohu/dbutils/DBConnection.java
19cef5b32aeacb6272bed8e444662177ed46add5
[]
no_license
CaiHu/InfoManage
01d24e06b5737982fdb89ecaeadcde48030e1d40
81e988d43bb4a3d695c8f4aeff10da0834c859d4
refs/heads/master
2021-01-20T07:35:59.047746
2017-09-08T06:44:37
2017-09-08T06:44:37
101,526,246
0
0
null
null
null
null
UTF-8
Java
false
false
873
java
package xiaohu.dbutils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBConnection { private static String Driver="oracle.jdbc.driver.OracleDriver"; private static String Url="jdbc:oracle:thin:@localhost:1521:orcl"; private static String userName="um"; private static String passWord="um"; private static ThreadLocal<Connection> threadLocal=new ThreadLocal<Connection>(); static{ try { Class.forName(Driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static synchronized Connection getConnection(){ Connection conn=null; conn=threadLocal.get(); try { if(null==conn||conn.isClosed()){ conn=DriverManager.getConnection(Url,userName,passWord); threadLocal.set(conn); } } catch (SQLException e) { e.printStackTrace(); } return conn; } }
e62d0118d2d78d460fdb5ef5cb6a103a00e64724
b42b29bb2ead243b63b894ead7c112362512ddbb
/app/src/main/java/com/nghiatv/musicapp/online/adapters/BannerAdapter.java
299c6d8c7a78e519bc2017fb321d9dcb61689170
[]
no_license
vannghia133/MusicApp
4befbaed0692ed988db0888c4f7890676a30d376
718185d7ccc5e3f95d4f42812c86b78ae39ed7fa
refs/heads/master
2020-05-20T13:53:23.413292
2019-05-08T13:42:12
2019-05-08T13:42:12
185,609,858
0
1
null
null
null
null
UTF-8
Java
false
false
3,386
java
package com.nghiatv.musicapp.online.adapters; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v4.view.PagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.nghiatv.musicapp.R; import com.nghiatv.musicapp.online.activities.SongsListActivity; import com.nghiatv.musicapp.dto.BannerDto; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.ArrayList; public class BannerAdapter extends PagerAdapter { private static final String TAG = "BannerAdapter"; private Context mContext; private ArrayList<BannerDto> mListBannerDto; public BannerAdapter(Context mContext, ArrayList<BannerDto> mListBannerDto) { this.mContext = mContext; this.mListBannerDto = mListBannerDto; } @Override public int getCount() { return mListBannerDto.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @NonNull // định hình object và gán dữ liệu cho mỗi object tượng trưng cho mỗi cái page @Override public Object instantiateItem(@NonNull ViewGroup container, final int position) { final LayoutInflater inflater = LayoutInflater.from(mContext); View rootView = inflater.inflate(R.layout.item_banner, null); ImageView imgBackgroundBanner = rootView.findViewById(R.id.imgBackgroundBanner); ImageView imgIconBanner = rootView.findViewById(R.id.imgIconBanner); TextView txtTitleBanner = rootView.findViewById(R.id.txtTitleBanner); TextView txtSongBanner = rootView.findViewById(R.id.txtSongBanner); ImageLoader.getInstance().displayImage(mListBannerDto.get(position).getHinhanh(), imgBackgroundBanner, new DisplayImageOptions.Builder() .cacheInMemory(true) .showImageOnLoading(R.drawable.icon_splash_screen) .resetViewBeforeLoading(true).build()); ImageLoader.getInstance().displayImage(mListBannerDto.get(position).getHinhbaihat(), imgIconBanner, new DisplayImageOptions.Builder() .cacheInMemory(true) .showImageOnLoading(R.drawable.icon_splash_screen) .resetViewBeforeLoading(true).build()); txtTitleBanner.setText(mListBannerDto.get(position).getTenbaihat()); txtSongBanner.setText(mListBannerDto.get(position).getNoidung()); rootView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, SongsListActivity.class); intent.putExtra("quangcao", mListBannerDto.get(position)); mContext.startActivity(intent); } }); container.addView(rootView); return rootView; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { // sau khi thuc hien xong thì xóa view container.removeView((View) object); } }
9b7e3f6f3ac24896aa7331c98a3bdf89e70198d5
694883f0e01fce71c8bbfc8d41fd4e57b2db7b8e
/FindFrequentListFromPDF/src/FrequencyTest.java
0ef4d06fa75fb9770f813d321cf4192b7016ad4f
[]
no_license
richardzhou1991/Me-Me-Inn
b828a4daa69f011da60c3f505ad2cebba4abbccc
b64ac50ba7318eef0e2bae1f4c8025660b90654e
refs/heads/master
2021-01-18T05:11:16.063355
2015-03-20T16:37:25
2015-03-20T16:37:25
33,501,875
0
0
null
2015-04-06T19:47:01
2015-04-06T19:47:00
Java
UTF-8
Java
false
false
1,628
java
import static org.junit.Assert.*; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Test; /** * In this class, we use a sample PDF and test on the generated hash table * @author yifanwang * */ public class FrequencyTest { @Before /** * Generate word frequency hash table based on PDFs */ public void preprocessing(){ FindFrequentListFromPDF.pdftoHashmap("testdoc.pdf", false); } @Test /** * Test if PDF files are successfully processed into hashmap tables */ public void testProcessPDFFile() { assertEquals("not null", FindFrequentListFromPDF.wordFreq.size()>0, true); } @Test /** * Test the existance of words */ public void testExistsWord(){ /*Iterator it0 = FindFrequentListFromPDF.wordFreq.entrySet().iterator(); while (it0.hasNext()) { Map.Entry pair = (Map.Entry)it0.next(); System.out.println(pair.getKey() + ": " + pair.getValue()); } */ assertEquals("find his", FindFrequentListFromPDF.wordFreq.get("his").toString(), "3"); assertEquals("find Othello", FindFrequentListFromPDF.wordFreq.get("othello").toString(), "1"); assertEquals("find Merlin", FindFrequentListFromPDF.wordFreq.get("merlin").toString(), "1"); } @Test /** * Test the non-exist word */ public void testNonExistWord() { assertEquals("no beautiful exist", FindFrequentListFromPDF.wordFreq.get("beautiful"), null); assertEquals("no strong exist", FindFrequentListFromPDF.wordFreq.get("strong"), null); assertEquals("no computer exist", FindFrequentListFromPDF.wordFreq.get("computer"), null); } }
b9bae0227076ec773c1c20006c253ddb0787148e
8475756a354793afc09eae25bbe92bb91f979e81
/src/test/java/com/remondis/cdc/consumer/pactbuilder/fieldtests/customconsumerbuilder/Parent.java
a00ddcf032bd761b7345c170c4a8743490bdbaff
[ "Apache-2.0" ]
permissive
remondis-it/pact-consumer-builder
4fdcdc80dc0c57b3ba86890b7616322735221df7
4350f58d646d7aade31dc1caed7fb380b9cd143e
refs/heads/develop
2021-10-27T07:16:40.848053
2020-06-19T11:17:52
2020-06-19T11:17:52
187,044,052
11
7
Apache-2.0
2020-08-10T07:23:35
2019-05-16T14:28:23
Java
UTF-8
Java
false
false
1,101
java
package com.remondis.cdc.consumer.pactbuilder.fieldtests.customconsumerbuilder; public class Parent { private Structure structure; public Parent() { super(); } public Parent(Structure structure) { super(); this.structure = structure; } public Structure getStructure() { return structure; } public void setStructure(Structure structure) { this.structure = structure; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((structure == null) ? 0 : structure.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Parent other = (Parent) obj; if (structure == null) { if (other.structure != null) return false; } else if (!structure.equals(other.structure)) return false; return true; } @Override public String toString() { return "Parent [structure=" + structure + "]"; } }
959f556be5fdbabb4b80735f546f097912a8ef74
dacf88b3683782758fd50dfef2650c62901760c9
/src/main/java/egovframework/ec4/call/cnslt/service/EC4CnsltntMngService.java
3cecc96440748da882c0776016cbbe48b3fd98a8
[]
no_license
latemorning/ec4
8d38c06ec18c60067aadf9d85f3a59bd59b0a71e
40e147950e7bb7999eae98949163c87d926c75b9
refs/heads/master
2020-05-02T18:39:09.561982
2019-04-03T01:08:58
2019-04-03T01:08:58
158,163,759
0
0
null
null
null
null
UTF-8
Java
false
false
1,074
java
package egovframework.ec4.call.cnslt.service; import java.util.List; import egovframework.com.cmm.service.CmmnDetailCode; import egovframework.rte.psl.dataaccess.util.EgovMap; /** * 상담원에 관한 서비스 인터페이스 클래스를 정의한다. * @author 최재중 * @since 2018.04.26 * @version 1.0 * @see * * <pre> * * 수정일 수정자 수정내용 * ------- -------- --------------------------- * 2018.04.26 최재중 최초 생성 * * </pre> */ public interface EC4CnsltntMngService { /** * 목록을 조회한다. * @param cnsltntMngVO cnsltntMngVO * @return List<cnsltntMngVO> * @exception Exception */ public List<EgovMap> selectCnsltntMngList(CnsltntMngVO cnsltntMngVO) throws Exception; int selectCnsltntMngListCnt(CnsltntMngVO cnsltntMngVO) throws Exception; public List<CmmnDetailCode> selectCnsltntComboList(CnsltntMngVO cnsltntMngVO) throws Exception; public List<CmmnDetailCode> selectOrgnztInfoComboDfList(CmmnDetailCode searchVO) throws Exception; }
969734e324dc66ea334ceae0b78950f7b56f01db
55fc30bd992401997d69c952df6aeff6781efdb2
/src/test/java/com/cybertek/tests/day14_extent_reports/NegativeLoginTestWithReporter.java
b8ebf367f563df4a8d7b924b6559daff98233001
[]
no_license
AdemTEN/Vytrack_Project
5cc5736c80ab838134a00f295b3b9b9904ab4d4e
ef8fe35cf7b528b2c5d32e26b9cb0d13d1bb2eb6
refs/heads/master
2022-12-29T18:36:29.920803
2020-10-14T14:01:35
2020-10-14T14:01:35
298,689,897
0
1
null
2020-10-07T07:22:15
2020-09-25T22:15:20
Java
UTF-8
Java
false
false
1,929
java
package com.cybertek.tests.day14_extent_reports; import com.cybertek.pages.LoginPage; import com.cybertek.tests.TestBase; import com.cybertek.tests.TestBaseForDays; import org.testng.Assert; import org.testng.annotations.Test; public class NegativeLoginTestWithReporter extends TestBase { @Test public void wrongPasswordTest(){ /* driver.findElement(By.id("prependedInput")).sendKeys("user1"); driver.findElement(By.id("prependedInput2")).sendKeys("somepassword"); driver.findElement(By.id("_submit")).click(); Assert.assertEquals(driver.getCurrentUrl(),"https://qa1.vytrack.com/user/login"); */ extentLogger = report.createTest("Wrong PassWord Test"); LoginPage loginPage = new LoginPage(); extentLogger.info("Enter username : user1"); loginPage.usernameInput.sendKeys("user1"); extentLogger.info("Enter password: somepassword"); loginPage.passwordInput.sendKeys("somepassword"); extentLogger.info("Click login button"); loginPage.loginBtn.click(); extentLogger.info("Verify Page URL"); Assert.assertEquals(driver.getCurrentUrl(),"https://qa1.vytrack.com/user/login"); extentLogger.pass("Wrong Password Test is Passed"); } @Test public void wrongUsernameTest(){ extentLogger = report.createTest("Wrong Username Test"); LoginPage loginPage = new LoginPage(); extentLogger.info("Enter user name: smeusername"); loginPage.usernameInput.sendKeys("smeusername"); extentLogger.info("Enter password: UserUser123"); loginPage.passwordInput.sendKeys("UserUser123"); extentLogger.info("Click login Button"); loginPage.loginBtn.click(); extentLogger.info("verify URL"); Assert.assertEquals(driver.getCurrentUrl(),"https://qa1.vytrack.com/user/logina"); extentLogger.pass("PASSED"); } }
466e77e0c65e673b40a386ee19b00f7917853033
ee41199b5177c4ab8842bc02bf1ad3307f689f41
/src/leetcode/tool/Util.java
316d82949fcffcc1fcb1a4e4a84d89771e1aaf34
[]
no_license
TrumanXia/leetcode
b32063d338508f48742fa21435a1b9fb7a065bee
4bbadedb79a8b1925b5046b0ac9f038c666a817b
refs/heads/master
2022-12-05T16:32:42.010719
2020-08-29T13:26:33
2020-08-29T13:26:33
277,225,003
0
0
null
null
null
null
UTF-8
Java
false
false
566
java
package leetcode.tool; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Stack; public class Util { public static int max(int x, int y) { if (x > y) return x; return y; } public static void main(String[] args) { LinkedList<Integer> queue = new LinkedList<>(); queue.addFirst(1); queue.addFirst(2); Integer poll = queue.removeFirst(); Integer poll2 = queue.removeFirst(); System.out.println(poll2); // queue.isEmpty() } }
ff6fdd03614a6ea0fc88795c8022eedc914bcf17
589dcd422402477ce80e9c349bd483c2d36b80cd
/trunk/adhoc-solr/src/main/java/org/apache/solr/schema/SchemaAware.java
34ee8e60779c2f82ef634513827126817a3c3607
[ "Apache-2.0", "LicenseRef-scancode-unicode-mappings", "BSD-3-Clause", "CDDL-1.0", "Python-2.0", "MIT", "ICU", "CPL-1.0" ]
permissive
baojiawei1230/mdrill
e3d92f4f1f85b34f0839f8463e7e5353145a9c78
edacdb4dc43ead6f14d83554c1f402aa1ffdec6a
refs/heads/master
2021-06-10T17:42:11.076927
2021-03-15T16:43:06
2021-03-15T16:43:06
95,193,877
0
0
Apache-2.0
2021-03-15T16:43:06
2017-06-23T07:15:00
Java
UTF-8
Java
false
false
1,402
java
package org.apache.solr.schema; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * An interface that can be extended to provide a callback mechanism for * informing an {@link IndexSchema} instance of changes to it, dynamically * performed at runtime. * * @since SOLR-1131 * **/ public interface SchemaAware { /** * Informs the {@link IndexSchema} provided by the <code>schema</code> * parameter of an event (e.g., a new {@link FieldType} was added, etc. * * @param schema * The {@link IndexSchema} instance that inform of the update to. * * @since SOLR-1131 */ public void inform(IndexSchema schema); }
fc15637246dc1fc82d9433865517ca5d88a7b758
aa4f7fd2015c2309ab42d954b54d17d3b8eda788
/src/main/java/servicos/jms/CoordenadorJMSServico.java
19ab09ffbde5d50bfed3aede4b03381683c03db7
[]
no_license
bladerangel/simuladorAmbiente
daf264a1b7147a47a3e0b340d2f05063df05bdfd
7a78a7e37a753aa5455cb5579f063552d188e493
refs/heads/master
2020-12-02T17:59:10.560362
2017-07-13T13:50:46
2017-07-13T13:50:46
96,457,544
0
0
null
null
null
null
UTF-8
Java
false
false
2,103
java
package servicos.jms; import java.util.Hashtable; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; public class CoordenadorJMSServico { private InitialContext contexto; private TopicConnection conexao; private TopicSession sessao; //inicia a conexao com o jms public void iniciarConexao() { try { Hashtable<String, String> propriedades = new Hashtable<>(); propriedades.put(Context.PROVIDER_URL, "tcp://localhost:3035"); propriedades.put(Context.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory"); contexto = new InitialContext(propriedades); TopicConnectionFactory fabrica = (TopicConnectionFactory) contexto.lookup("ConnectionFactory"); conexao = fabrica.createTopicConnection(); sessao = conexao.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); conexao.start(); } catch (Exception e) { e.printStackTrace(); } } //publica um topico no jms public void publicarMensagem(String msg) { try { TextMessage mensagem = sessao.createTextMessage(); mensagem.setText(msg); Topic topico = (Topic) contexto.lookup("topic1"); TopicPublisher emissor = sessao.createPublisher(topico); emissor.publish(mensagem); } catch (Exception e) { e.printStackTrace(); } } //recebe a mensagem num topico no jms public void receberMensagem(MessageListener mensagemListener) { try { Topic topico = (Topic) contexto.lookup("topic1"); TopicSubscriber receptor = sessao.createSubscriber(topico); receptor.setMessageListener(mensagemListener); } catch (Exception e) { e.printStackTrace(); } } //fecha a conexao com o jms public void fecharConexao() { try { contexto.close(); conexao.close(); } catch (Exception e) { e.printStackTrace(); } } }
8a0772a809a6749ce91fdb0dbd6b4e62148e8d05
0fc7796abaa88a04b42678127bc078019d83bf17
/src/main/java/com/classifiers/algo/DataPreProcessor.java
d45bb413e9c67748ac64e339a4378d7c6c39a32f
[]
no_license
vRamananKrish/knn
f3c200842f71a341682818b85da5069b1c40f32b
e3d62fc2c00145d6be131dc0bd2f287e804e24c2
refs/heads/master
2020-09-28T05:19:42.371882
2016-09-04T01:37:02
2016-09-04T01:37:02
67,315,574
0
0
null
null
null
null
UTF-8
Java
false
false
2,443
java
package com.classifiers.algo; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import com.classifiers.model.DataItem; import com.classifiers.model.DataSet; public class DataPreProcessor { private float splitPercentage = 0.80f; public DataPreProcessor() { } public static void main(String[] args) { DataPreProcessor proc = new DataPreProcessor(); DataSet dataSet = proc.extractDataSet("E:\\Space\\titan\\hdpSpace\\kNN\\src\\main\\resources\\data/iris.csv"); System.out.println("Data set:"+ dataSet); } /** * Read the given file and split into lines * * */ public DataSet extractDataSet(String fileName){ DataSet dataSet = new DataSet(); if(fileName != ""){ List<CSVRecord> csvRecords = parseCsvFile(fileName); DataItem dataItem = new DataItem(); Float[] features = new Float[4]; for(CSVRecord csvRecord: csvRecords){ System.out.println(csvRecord); System.out.println(csvRecord.get(0)); features[0] = new Float(csvRecord.get(0)); features[1] = new Float(csvRecord.get(1)); features[2] = new Float(csvRecord.get(2)); features[3] = new Float(csvRecord.get(3)); dataItem.setFeatures(features); dataItem.setClassName(csvRecord.get(4)); // // Commented the code for MR implementation // dataSet.addTrainingSet(dataItem); /*if(Math.random() < splitPercentage){ dataSet.addToTrainingSet(dataItem); } else{ dataSet.addToTestSet(dataItem); }*/ } } return dataSet; } /** * Open a file and read the content * as lines of file * * */ private List<CSVRecord> parseCsvFile(String fileName){ // CSV parser File csvFile = new File(fileName); List<CSVRecord> csvRecords = new ArrayList<CSVRecord>(); try { CSVParser parser = CSVParser.parse(csvFile, Charset.defaultCharset(), CSVFormat.RFC4180); csvRecords = parser.getRecords(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return csvRecords; } }
52e13381c45195fefe1f5c9095590cf0b1bc7fca
c2522053a37310e23cf2e343f1f982f9557071dc
/src/main/java/DSA/leetcode/contest/biWeekly62/Q5871.java
5ace6c223fc6f16c7f158a630670002fb9322d1e
[]
no_license
ravikanthmp/DSA2
6003ee1f9bc1ad95fdadea4e79d9ab1ce6c3fe1a
a509a90ab1b7dedb5d3fd3b344f8d7b3bad03a55
refs/heads/main
2023-08-30T00:48:00.981408
2021-10-26T17:55:53
2021-10-26T17:55:53
386,459,073
0
0
null
2021-10-20T17:47:06
2021-07-16T00:20:22
Java
UTF-8
Java
false
false
763
java
package DSA.leetcode.contest.biWeekly62; import java.util.Arrays; public class Q5871 { public int[][] construct2DArray(int[] original, int m, int n) { if (original.length != m * n){ return new int[0][0]; }else { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { arr[i] = Arrays.copyOfRange(original, i*n, (i+1)*n); } return arr; } } public static void main(String[] args) { Q5871 test = new Q5871(); int[] orig = {3}; int m = 1; int n = 2; int[][] ints = test.construct2DArray(orig, m, n); for (int[] arr : ints) { System.out.println(Arrays.toString(arr)); } } }
0e14e4ee3164978b1de03d784cf684ad28c00064
a825d55e288e788bc5064a3917e4d7884fde1519
/app/src/main/java/com/example/mikie/moviereview/adapter/HorizontalTrailerAdapter.java
0800697e9a3d7bf7ff3646c5b4257e06bbe4577b
[]
no_license
melkikun/MovieReview
2e594531a65ad69e33f5bae49b00a9def55865f6
cec628a60f31b303963411f1d379151c7cb78b4c
refs/heads/master
2021-01-20T11:01:17.939157
2017-09-14T09:17:38
2017-09-14T09:17:38
101,662,828
0
0
null
null
null
null
UTF-8
Java
false
false
2,067
java
package com.example.mikie.moviereview.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.example.mikie.moviereview.R; import com.example.mikie.moviereview.model.CategoryInfo; import com.example.mikie.moviereview.model.Video; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by IT01 on 9/11/2017. */ public class HorizontalTrailerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ private List<Video> list = new ArrayList<>(); private Context context; private final String IMG = "https://img.youtube.com/vi/"; public HorizontalTrailerAdapter(List<Video> list, Context context) { this.list = list; this.context = context; } @Override public DataHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.horizontal_trailer, parent, false); return new DataHolder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { DataHolder holder1 = (DataHolder) holder; Glide.with(this.context) .load(IMG+list.get(position).getKey()+"/mqdefault.jpg") .thumbnail(0.5f) .crossFade() .diskCacheStrategy(DiskCacheStrategy.ALL) .into(holder1.img_trailer); } @Override public int getItemCount() { return list.size(); } public class DataHolder extends RecyclerView.ViewHolder { @BindView(R.id.img_trailer) ImageView img_trailer; public DataHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
11b71029ed46fc19adcc54cf15fe89588cfe1aa0
ccebc11981cbf811d61ad7e55866753986a02052
/src/de/mb/infinity/DiceState.java
8fd5d28da9fcda3ffce1a92644b6f84995631684
[]
no_license
firegate666/Infinity-Tabletop-Stat-Calculator
f73ba0f329501795d00db2da25347bf0adfd896e
740d61f8e61e23b20e15db5aa6b9c5b5f46defe8
refs/heads/master
2021-01-20T05:31:10.839566
2011-11-25T02:03:36
2011-11-25T02:03:36
2,847,056
1
1
null
null
null
null
UTF-8
Java
false
false
561
java
package de.mb.infinity; public enum DiceState { CRITICAL, HIT, MISS; public static String stateToName(DiceState state) { if(state == DiceState.MISS) return "Misserfolg"; else if(state == DiceState.HIT) return "Treffer"; else if(state == DiceState.CRITICAL) return "kritischer Treffer"; return "undef."; } public static DiceRoll calc_dice_state(byte ew, byte dv, byte num) { if (ew == dv) return new DiceRoll(dv, CRITICAL, num); else if (ew > dv) return new DiceRoll(dv, HIT, num); return new DiceRoll(dv, MISS, num); } }
[ "root" ]
root
de4bf41bd7c4c6dc69d22f24bd86849b1c4d200d
2169d09dcc9166e1e4fed97ba0aece4b1c5f42fa
/app/models/TagType.java
cd0bf710fc735f10570e8f6364881dfc0d0b6a91
[]
no_license
remylab/play2-demoapp
154c44b2d245025771713262aebe73e0e6d17ba5
06bf7e63a0ca71ad218343a34122d02f7c075a3f
refs/heads/master
2021-01-20T05:52:45.864418
2014-04-24T18:24:27
2014-04-24T18:24:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
213
java
package models; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class TagType { @Id public String type; public TagType(String type) { this.type = type; } }
5e94ff0cec609a5026d605dcd30ffc152c7130ef
e05601c738733d197307466c1fb61a307a39ce1f
/core/src/main/java/it/cavallium/warppi/device/KeyboardAWTValues.java
083d0531fa8d0c9e513d628a8c603c08836a25cd
[ "Apache-2.0" ]
permissive
W-Mai/WarpPI
1dc2ed479474cc7165e894639aba308758f5eb0e
17d1bddbf18e8607e86b34552ce438a5e0096013
refs/heads/master
2020-06-18T06:53:38.186575
2019-04-29T21:07:24
2019-04-29T21:07:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
18,589
java
package it.cavallium.warppi.device; public interface KeyboardAWTValues { /** * The first number in the range of ids used for key events. */ int KEY_FIRST = 400; /** * The last number in the range of ids used for key events. */ int KEY_LAST = 402; /** * The "key typed" event. This event is generated when a character is * entered. In the simplest case, it is produced by a single key press. * Often, however, characters are produced by series of key presses, and * the mapping from key pressed events to key typed events may be * many-to-one or many-to-many. */ int KEY_TYPED = KEY_FIRST; /** * The "key pressed" event. This event is generated when a key * is pushed down. */ int KEY_PRESSED = 1 + KEY_FIRST; //Event.KEY_PRESS /** * The "key released" event. This event is generated when a key * is let up. */ int KEY_RELEASED = 2 + KEY_FIRST; //Event.KEY_RELEASE /* Virtual key codes. */ int VK_ENTER = '\n'; int VK_BACK_SPACE = '\b'; int VK_TAB = '\t'; int VK_CANCEL = 0x03; int VK_CLEAR = 0x0C; int VK_SHIFT = 0x10; int VK_CONTROL = 0x11; int VK_ALT = 0x12; int VK_PAUSE = 0x13; int VK_CAPS_LOCK = 0x14; int VK_ESCAPE = 0x1B; int VK_SPACE = 0x20; int VK_PAGE_UP = 0x21; int VK_PAGE_DOWN = 0x22; int VK_END = 0x23; int VK_HOME = 0x24; /** * Constant for the non-numpad <b>left</b> arrow key. * @see #VK_KP_LEFT */ int VK_LEFT = 0x25; /** * Constant for the non-numpad <b>up</b> arrow key. * @see #VK_KP_UP */ int VK_UP = 0x26; /** * Constant for the non-numpad <b>right</b> arrow key. * @see #VK_KP_RIGHT */ int VK_RIGHT = 0x27; /** * Constant for the non-numpad <b>down</b> arrow key. * @see #VK_KP_DOWN */ int VK_DOWN = 0x28; /** * Constant for the comma key, "," */ int VK_COMMA = 0x2C; /** * Constant for the minus key, "-" * @since 1.2 */ int VK_MINUS = 0x2D; /** * Constant for the period key, "." */ int VK_PERIOD = 0x2E; /** * Constant for the forward slash key, "/" */ int VK_SLASH = 0x2F; /** VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */ int VK_0 = 0x30; int VK_1 = 0x31; int VK_2 = 0x32; int VK_3 = 0x33; int VK_4 = 0x34; int VK_5 = 0x35; int VK_6 = 0x36; int VK_7 = 0x37; int VK_8 = 0x38; int VK_9 = 0x39; /** * Constant for the semicolon key, ";" */ int VK_SEMICOLON = 0x3B; /** * Constant for the equals key, "=" */ int VK_EQUALS = 0x3D; /** VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */ int VK_A = 0x41; int VK_B = 0x42; int VK_C = 0x43; int VK_D = 0x44; int VK_E = 0x45; int VK_F = 0x46; int VK_G = 0x47; int VK_H = 0x48; int VK_I = 0x49; int VK_J = 0x4A; int VK_K = 0x4B; int VK_L = 0x4C; int VK_M = 0x4D; int VK_N = 0x4E; int VK_O = 0x4F; int VK_P = 0x50; int VK_Q = 0x51; int VK_R = 0x52; int VK_S = 0x53; int VK_T = 0x54; int VK_U = 0x55; int VK_V = 0x56; int VK_W = 0x57; int VK_X = 0x58; int VK_Y = 0x59; int VK_Z = 0x5A; /** * Constant for the open bracket key, "[" */ int VK_OPEN_BRACKET = 0x5B; /** * Constant for the back slash key, "\" */ int VK_BACK_SLASH = 0x5C; /** * Constant for the close bracket key, "]" */ int VK_CLOSE_BRACKET = 0x5D; int VK_NUMPAD0 = 0x60; int VK_NUMPAD1 = 0x61; int VK_NUMPAD2 = 0x62; int VK_NUMPAD3 = 0x63; int VK_NUMPAD4 = 0x64; int VK_NUMPAD5 = 0x65; int VK_NUMPAD6 = 0x66; int VK_NUMPAD7 = 0x67; int VK_NUMPAD8 = 0x68; int VK_NUMPAD9 = 0x69; int VK_MULTIPLY = 0x6A; int VK_ADD = 0x6B; /** * This constant is obsolete, and is included only for backwards * compatibility. * @see #VK_SEPARATOR */ int VK_SEPARATER = 0x6C; /** * Constant for the Numpad Separator key. * @since 1.4 */ int VK_SEPARATOR = VK_SEPARATER; int VK_SUBTRACT = 0x6D; int VK_DECIMAL = 0x6E; int VK_DIVIDE = 0x6F; int VK_DELETE = 0x7F; /* ASCII DEL */ int VK_NUM_LOCK = 0x90; int VK_SCROLL_LOCK = 0x91; /** Constant for the F1 function key. */ int VK_F1 = 0x70; /** Constant for the F2 function key. */ int VK_F2 = 0x71; /** Constant for the F3 function key. */ int VK_F3 = 0x72; /** Constant for the F4 function key. */ int VK_F4 = 0x73; /** Constant for the F5 function key. */ int VK_F5 = 0x74; /** Constant for the F6 function key. */ int VK_F6 = 0x75; /** Constant for the F7 function key. */ int VK_F7 = 0x76; /** Constant for the F8 function key. */ int VK_F8 = 0x77; /** Constant for the F9 function key. */ int VK_F9 = 0x78; /** Constant for the F10 function key. */ int VK_F10 = 0x79; /** Constant for the F11 function key. */ int VK_F11 = 0x7A; /** Constant for the F12 function key. */ int VK_F12 = 0x7B; /** * Constant for the F13 function key. * @since 1.2 */ /* F13 - F24 are used on IBM 3270 keyboard; use random range for constants. */ int VK_F13 = 0xF000; /** * Constant for the F14 function key. * @since 1.2 */ int VK_F14 = 0xF001; /** * Constant for the F15 function key. * @since 1.2 */ int VK_F15 = 0xF002; /** * Constant for the F16 function key. * @since 1.2 */ int VK_F16 = 0xF003; /** * Constant for the F17 function key. * @since 1.2 */ int VK_F17 = 0xF004; /** * Constant for the F18 function key. * @since 1.2 */ int VK_F18 = 0xF005; /** * Constant for the F19 function key. * @since 1.2 */ int VK_F19 = 0xF006; /** * Constant for the F20 function key. * @since 1.2 */ int VK_F20 = 0xF007; /** * Constant for the F21 function key. * @since 1.2 */ int VK_F21 = 0xF008; /** * Constant for the F22 function key. * @since 1.2 */ int VK_F22 = 0xF009; /** * Constant for the F23 function key. * @since 1.2 */ int VK_F23 = 0xF00A; /** * Constant for the F24 function key. * @since 1.2 */ int VK_F24 = 0xF00B; int VK_PRINTSCREEN = 0x9A; int VK_INSERT = 0x9B; int VK_HELP = 0x9C; int VK_META = 0x9D; int VK_BACK_QUOTE = 0xC0; int VK_QUOTE = 0xDE; /** * Constant for the numeric keypad <b>up</b> arrow key. * @see #VK_UP * @since 1.2 */ int VK_KP_UP = 0xE0; /** * Constant for the numeric keypad <b>down</b> arrow key. * @see #VK_DOWN * @since 1.2 */ int VK_KP_DOWN = 0xE1; /** * Constant for the numeric keypad <b>left</b> arrow key. * @see #VK_LEFT * @since 1.2 */ int VK_KP_LEFT = 0xE2; /** * Constant for the numeric keypad <b>right</b> arrow key. * @see #VK_RIGHT * @since 1.2 */ int VK_KP_RIGHT = 0xE3; /* For European keyboards */ /** @since 1.2 */ int VK_DEAD_GRAVE = 0x80; /** @since 1.2 */ int VK_DEAD_ACUTE = 0x81; /** @since 1.2 */ int VK_DEAD_CIRCUMFLEX = 0x82; /** @since 1.2 */ int VK_DEAD_TILDE = 0x83; /** @since 1.2 */ int VK_DEAD_MACRON = 0x84; /** @since 1.2 */ int VK_DEAD_BREVE = 0x85; /** @since 1.2 */ int VK_DEAD_ABOVEDOT = 0x86; /** @since 1.2 */ int VK_DEAD_DIAERESIS = 0x87; /** @since 1.2 */ int VK_DEAD_ABOVERING = 0x88; /** @since 1.2 */ int VK_DEAD_DOUBLEACUTE = 0x89; /** @since 1.2 */ int VK_DEAD_CARON = 0x8a; /** @since 1.2 */ int VK_DEAD_CEDILLA = 0x8b; /** @since 1.2 */ int VK_DEAD_OGONEK = 0x8c; /** @since 1.2 */ int VK_DEAD_IOTA = 0x8d; /** @since 1.2 */ int VK_DEAD_VOICED_SOUND = 0x8e; /** @since 1.2 */ int VK_DEAD_SEMIVOICED_SOUND = 0x8f; /** @since 1.2 */ int VK_AMPERSAND = 0x96; /** @since 1.2 */ int VK_ASTERISK = 0x97; /** @since 1.2 */ int VK_QUOTEDBL = 0x98; /** @since 1.2 */ int VK_LESS = 0x99; /** @since 1.2 */ int VK_GREATER = 0xa0; /** @since 1.2 */ int VK_BRACELEFT = 0xa1; /** @since 1.2 */ int VK_BRACERIGHT = 0xa2; /** * Constant for the "@" key. * @since 1.2 */ int VK_AT = 0x0200; /** * Constant for the ":" key. * @since 1.2 */ int VK_COLON = 0x0201; /** * Constant for the "^" key. * @since 1.2 */ int VK_CIRCUMFLEX = 0x0202; /** * Constant for the "$" key. * @since 1.2 */ int VK_DOLLAR = 0x0203; /** * Constant for the Euro currency sign key. * @since 1.2 */ int VK_EURO_SIGN = 0x0204; /** * Constant for the "!" key. * @since 1.2 */ int VK_EXCLAMATION_MARK = 0x0205; /** * Constant for the inverted exclamation mark key. * @since 1.2 */ int VK_INVERTED_EXCLAMATION_MARK = 0x0206; /** * Constant for the "(" key. * @since 1.2 */ int VK_LEFT_PARENTHESIS = 0x0207; /** * Constant for the "#" key. * @since 1.2 */ int VK_NUMBER_SIGN = 0x0208; /** * Constant for the "+" key. * @since 1.2 */ int VK_PLUS = 0x0209; /** * Constant for the ")" key. * @since 1.2 */ int VK_RIGHT_PARENTHESIS = 0x020A; /** * Constant for the "_" key. * @since 1.2 */ int VK_UNDERSCORE = 0x020B; /** * Constant for the Microsoft Windows "Windows" key. * It is used for both the left and right version of the key. * @see #getKeyLocation() * @since 1.5 */ int VK_WINDOWS = 0x020C; /** * Constant for the Microsoft Windows Context Menu key. * @since 1.5 */ int VK_CONTEXT_MENU = 0x020D; /* for input method support on Asian Keyboards */ /* not clear what this means - listed in Microsoft Windows API */ int VK_FINAL = 0x0018; /** Constant for the Convert function key. */ /* Japanese PC 106 keyboard, Japanese Solaris keyboard: henkan */ int VK_CONVERT = 0x001C; /** Constant for the Don't Convert function key. */ /* Japanese PC 106 keyboard: muhenkan */ int VK_NONCONVERT = 0x001D; /** Constant for the Accept or Commit function key. */ /* Japanese Solaris keyboard: kakutei */ int VK_ACCEPT = 0x001E; /* not clear what this means - listed in Microsoft Windows API */ int VK_MODECHANGE = 0x001F; /* replaced by VK_KANA_LOCK for Microsoft Windows and Solaris; might still be used on other platforms */ int VK_KANA = 0x0015; /* replaced by VK_INPUT_METHOD_ON_OFF for Microsoft Windows and Solaris; might still be used for other platforms */ int VK_KANJI = 0x0019; /** * Constant for the Alphanumeric function key. * @since 1.2 */ /* Japanese PC 106 keyboard: eisuu */ int VK_ALPHANUMERIC = 0x00F0; /** * Constant for the Katakana function key. * @since 1.2 */ /* Japanese PC 106 keyboard: katakana */ int VK_KATAKANA = 0x00F1; /** * Constant for the Hiragana function key. * @since 1.2 */ /* Japanese PC 106 keyboard: hiragana */ int VK_HIRAGANA = 0x00F2; /** * Constant for the Full-Width Characters function key. * @since 1.2 */ /* Japanese PC 106 keyboard: zenkaku */ int VK_FULL_WIDTH = 0x00F3; /** * Constant for the Half-Width Characters function key. * @since 1.2 */ /* Japanese PC 106 keyboard: hankaku */ int VK_HALF_WIDTH = 0x00F4; /** * Constant for the Roman Characters function key. * @since 1.2 */ /* Japanese PC 106 keyboard: roumaji */ int VK_ROMAN_CHARACTERS = 0x00F5; /** * Constant for the All Candidates function key. * @since 1.2 */ /* Japanese PC 106 keyboard - VK_CONVERT + ALT: zenkouho */ int VK_ALL_CANDIDATES = 0x0100; /** * Constant for the Previous Candidate function key. * @since 1.2 */ /* Japanese PC 106 keyboard - VK_CONVERT + SHIFT: maekouho */ int VK_PREVIOUS_CANDIDATE = 0x0101; /** * Constant for the Code Input function key. * @since 1.2 */ /* Japanese PC 106 keyboard - VK_ALPHANUMERIC + ALT: kanji bangou */ int VK_CODE_INPUT = 0x0102; /** * Constant for the Japanese-Katakana function key. * This key switches to a Japanese input method and selects its Katakana input mode. * @since 1.2 */ /* Japanese Macintosh keyboard - VK_JAPANESE_HIRAGANA + SHIFT */ int VK_JAPANESE_KATAKANA = 0x0103; /** * Constant for the Japanese-Hiragana function key. * This key switches to a Japanese input method and selects its Hiragana input mode. * @since 1.2 */ /* Japanese Macintosh keyboard */ int VK_JAPANESE_HIRAGANA = 0x0104; /** * Constant for the Japanese-Roman function key. * This key switches to a Japanese input method and selects its Roman-Direct input mode. * @since 1.2 */ /* Japanese Macintosh keyboard */ int VK_JAPANESE_ROMAN = 0x0105; /** * Constant for the locking Kana function key. * This key locks the keyboard into a Kana layout. * @since 1.3 */ /* Japanese PC 106 keyboard with special Windows driver - eisuu + Control; Japanese Solaris keyboard: kana */ int VK_KANA_LOCK = 0x0106; /** * Constant for the input method on/off key. * @since 1.3 */ /* Japanese PC 106 keyboard: kanji. Japanese Solaris keyboard: nihongo */ int VK_INPUT_METHOD_ON_OFF = 0x0107; /* for Sun keyboards */ /** @since 1.2 */ int VK_CUT = 0xFFD1; /** @since 1.2 */ int VK_COPY = 0xFFCD; /** @since 1.2 */ int VK_PASTE = 0xFFCF; /** @since 1.2 */ int VK_UNDO = 0xFFCB; /** @since 1.2 */ int VK_AGAIN = 0xFFC9; /** @since 1.2 */ int VK_FIND = 0xFFD0; /** @since 1.2 */ int VK_PROPS = 0xFFCA; /** @since 1.2 */ int VK_STOP = 0xFFC8; /** * Constant for the Compose function key. * @since 1.2 */ int VK_COMPOSE = 0xFF20; /** * Constant for the AltGraph function key. * @since 1.2 */ int VK_ALT_GRAPH = 0xFF7E; /** * Constant for the Begin key. * @since 1.5 */ int VK_BEGIN = 0xFF58; /** * This value is used to indicate that the keyCode is unknown. * KEY_TYPED events do not have a keyCode value; this value * is used instead. */ int VK_UNDEFINED = 0x0; /** * KEY_PRESSED and KEY_RELEASED events which do not map to a * valid Unicode character use this for the keyChar value. */ char CHAR_UNDEFINED = 0xFFFF; /** * A constant indicating that the keyLocation is indeterminate * or not relevant. * <code>KEY_TYPED</code> events do not have a keyLocation; this value * is used instead. * @since 1.4 */ int KEY_LOCATION_UNKNOWN = 0; /** * A constant indicating that the key pressed or released * is not distinguished as the left or right version of a key, * and did not originate on the numeric keypad (or did not * originate with a virtual key corresponding to the numeric * keypad). * @since 1.4 */ int KEY_LOCATION_STANDARD = 1; /** * A constant indicating that the key pressed or released is in * the left key location (there is more than one possible location * for this key). Example: the left shift key. * @since 1.4 */ int KEY_LOCATION_LEFT = 2; /** * A constant indicating that the key pressed or released is in * the right key location (there is more than one possible location * for this key). Example: the right shift key. * @since 1.4 */ int KEY_LOCATION_RIGHT = 3; /** * A constant indicating that the key event originated on the * numeric keypad or with a virtual key corresponding to the * numeric keypad. * @since 1.4 */ int KEY_LOCATION_NUMPAD = 4; }
1a4b14abfb3c17716bbb48abe48c641e43683acf
6b5d12449aee532f626ca09ec32e10e0862928e0
/src/main/java/com/romsel/memcached/defaults/MemcachedConstants.java
55efa12e66d45979aae603007a34b937eae38c8e
[]
no_license
rselvanathan/completable-memcached
c3ec793d416783c11946abac6e8b9c3eed88fc41
9d773f8f2f521e00ecac8454ec4fbf5dc885917a
refs/heads/master
2021-01-11T16:08:28.327016
2017-02-07T11:58:53
2017-02-07T11:58:53
80,015,349
0
0
null
null
null
null
UTF-8
Java
false
false
758
java
package com.romsel.memcached.defaults; import java.util.concurrent.TimeUnit; /** * @author Romesh Selvan */ public class MemcachedConstants { /** * Constant values used for key and word separator */ public static final String KEY_SEPARATOR = "|"; public static final String WORD_SEPARATOR = "-"; public static final Long ONE_MONTH = TimeUnit.SECONDS.convert(30L, TimeUnit.DAYS); public static final Long ONE_WEEK = TimeUnit.SECONDS.convert(7L, TimeUnit.DAYS); public static final Long ONE_DAY = TimeUnit.SECONDS.convert(24L, TimeUnit.HOURS); public static final Long ONE_HOUR = TimeUnit.SECONDS.convert(1L, TimeUnit.HOURS); public static final Long ONE_MINUTE = TimeUnit.SECONDS.convert(1L, TimeUnit.MINUTES); }
03232f011eaace9fc060b3196899c2e37a89f074
0be10da7ca5ae6697a7efab8ce12d2a08d3b8fdd
/hl-framework-model/src/main/java/com/haili/framework/domain/basic/Printer.java
f14cefd0a72ad14058ef420a50bd3945ff12ce58
[]
no_license
izhoutao/hlMesService
82bd1f6b33c868efeb74d63d3b2071376091b361
3f9518c4c9add7f6536c11b70dea9deb4cde3317
refs/heads/master
2022-11-29T14:03:52.767810
2020-07-07T11:47:49
2020-07-07T11:47:49
221,719,794
0
0
null
2022-11-24T06:27:09
2019-11-14T14:44:16
Java
UTF-8
Java
false
false
1,228
java
package com.haili.framework.domain.basic; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDateTime; /** * <p> * * </p> * * @author Zhou Tao * @since 2019-12-03 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("tb_printer") public class Printer implements Serializable { private static final long serialVersionUID = 1L; private String id; /** * 打印机名称 */ private String name; /** * 打印机路径 */ private String path; /** * 字符编码 */ private String characterCode; /** * 访问用户名 */ private String username; /** * 访问密码 */ private String password; /** * 打印文件路径 */ private String filePath; @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime; }
270863866ea9ccbfd9ee016dc63ca53359e7ee00
142e38fc66fa74fb96891223110ed96b5103ba2e
/JavaRushTasks/4.JavaCollections/src/com/javarush/task/task34/task3413/SoftCache.java
3103a5b91db2a46935179d1c650112ec98470af8
[]
no_license
sanke46/JavaRushTasks
2d433c10040109a80f49c1f8393f7f25f911d387
8069ca71754ad66cc32a496c5d524b86d219124a
refs/heads/master
2020-04-05T11:00:39.111560
2018-01-12T13:59:52
2018-01-12T13:59:52
81,456,881
0
0
null
null
null
null
UTF-8
Java
false
false
1,129
java
package com.javarush.task.task34.task3413; import java.lang.ref.SoftReference; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class SoftCache { private Map<Long, SoftReference<AnyObject>> cacheMap = new ConcurrentHashMap<>(); public AnyObject get(Long key) { SoftReference<AnyObject> softReference = cacheMap.get(key); if (softReference == null) { return null; } return softReference.get(); } public AnyObject put(Long key, AnyObject value) { AnyObject last = null; if (cacheMap.containsKey(key)){ last = cacheMap.get(key).get(); cacheMap.get(key).clear(); } SoftReference<AnyObject> softReference = cacheMap.put(key, new SoftReference<>(value)); return last; } public AnyObject remove(Long key) { AnyObject last = null; if (cacheMap.containsKey(key)){ last = cacheMap.get(key).get(); cacheMap.get(key).clear(); } SoftReference<AnyObject> softReference = cacheMap.remove(key); return last; } }
c3c69f457cf4dc827d6abee09a920dae50aad9b2
1d7dd00d366936232bc5ac3b398616906affb882
/src/main/java/com/mj/spider/utils/AgentUtils.java
c6295327216371436b7bb82d9c1f77fa395f750b
[]
no_license
mj1828/MJ_WebMagic
5675295464620033222a68997747196d87d48b59
1b1c892805d73ac19ec6e1d89acc129a4f665e5b
refs/heads/master
2020-03-29T18:48:28.020879
2018-09-29T08:26:12
2018-09-29T08:26:12
150,232,550
0
0
null
null
null
null
UTF-8
Java
false
false
2,506
java
package com.mj.spider.utils; import java.util.Random; /** * Agent 随机获取工具类 * * @author MJ * @mail [email protected] * @date 2018年9月29日 */ public class AgentUtils { private static String[] AGENTS = new String[] { "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.04", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/4.0; InfoPath.2; SV1; .NET CLR 2.0.50727; WOW64)", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko", "Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1)", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0", "Mozilla/5.0 (X11; Linux i686; rv:40.0) Gecko/20100101 Firefox/40.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)", "Opera/9.80 (X11; Linux i686; U; ru) Presto/2.8.131 Version/11.11", "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25", "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB7.4; InfoPath.2; SV1; .NET CLR 3.3.69573; WOW64; en-US)", "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0.1", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2471.2 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36" }; public static String randomAgent() { return AGENTS[new Random().nextInt(AGENTS.length)]; } }
028613a1143f26f06221793f88ccebd2ae40cfb3
1b28e293d6c89d37d6a6daac70279d1b64deacc7
/Notas/app/src/main/java/com/example/notas/NotasAdapter.java
9e902b2a51c8146932df2b93635498011b1bdafc
[]
no_license
marcelom1/DDM054705
aec60f89f22c99dbf5f55409df2bac4dceac452a
fe14ba09ca19a68438d9436be7dde4c905281f25
refs/heads/master
2021-01-06T20:09:52.129563
2020-10-12T15:47:07
2020-10-12T15:47:07
241,473,982
0
0
null
null
null
null
UTF-8
Java
false
false
2,116
java
package com.example.notas; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.notas.models.Nota; import java.util.ArrayList; public class NotasAdapter extends RecyclerView.Adapter<NotasAdapter.MyViewHolder> { Context mContext; int mResource; ArrayList<Nota> mNota; public NotasAdapter(Context c, int template, ArrayList<Nota> notas) { this.mContext = c; this.mResource = template; this.mNota = notas; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(mContext); View convertView = layoutInflater.inflate(mResource,parent,false); MyViewHolder myViewHolder = new MyViewHolder(convertView); return myViewHolder; } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) { final Nota nota = mNota.get(position); holder.editText.setText(nota.getText()); holder.editText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(mContext,ActivityEditNotas.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("position",nota.getId()); mContext.startActivity(i); } }); } @Override public int getItemCount() { return mNota.size(); } public class MyViewHolder extends RecyclerView.ViewHolder{ TextView editText; public MyViewHolder(@NonNull View convertView) { super(convertView); editText = convertView.findViewById(R.id.editText); } } }
f2a7dca7558c5a8a92f4286c142d7909af897b72
10e796b4795590da812193e9454647ffd3ad08cb
/app/src/androidTest/java/com/example/android/bakingrecipes/MainActivityTest.java
02700cd3cc7e65fd09f4f5cdcf78e3ffe84eb83a
[]
no_license
engy-eleraky/Baking-App
c7fd5605b798ddb1cd2efcc70a4846871e83ed04
22ce59790078fe4d1f24b3e1c843ada4e68c945e
refs/heads/master
2021-09-13T05:33:42.404152
2018-04-25T23:50:23
2018-04-25T23:50:23
112,727,780
0
0
null
null
null
null
UTF-8
Java
false
false
2,287
java
package com.example.android.bakingrecipes; import android.support.test.espresso.Espresso; import android.support.test.espresso.IdlingResource; import android.support.test.espresso.contrib.RecyclerViewActions; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; /** * Created by Noga on 12/7/2017. */ @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public ActivityTestRule<MainActivity> mainActivityTest = new ActivityTestRule<>(MainActivity.class) ; private IdlingResource idlingResource ; @Before public void registerIdlingResource() { idlingResource = mainActivityTest.getActivity().getIdlingResource(); Espresso.registerIdlingResources(idlingResource); } @Test public void testClickonRecipeRecyclerview_OpenDetailsActivity(){ onView(withId(R.id.recyclerView)).check(matches(isDisplayed())); onView(withId(R.id.recyclerView)) .perform(RecyclerViewActions.actionOnItemAtPosition(0,click())); onView(withId(R.id.list_steps)).check(matches(withText("Steps :"))); onView(withId(R.id.recyclerView2)) .perform(RecyclerViewActions.actionOnItemAtPosition(0,click())); onView(withId(R.id.recipe_description)).check(matches(withText("Recipe Introduction"))); onView((withId(R.id.nextStep))).perform(click()); onView(withId(R.id.recipe_description)).check(matches(withText("1. Preheat the oven to 350°F. Butter a 9\" deep dish pie pan."))); } @After public void unregisterIdlingResource() { if(idlingResource != null ) Espresso.unregisterIdlingResources(idlingResource); } }
6d7b8b8efbee7cae4a70272443b3881b634ab65e
f8c1bd871e84468784e2a8a1b37478fa2ca9059d
/utils/src/main/java/com/hl/utils/ConstUtils.java
9d9d92091994142897b448b7dfb54e04e8cbbdd1
[]
no_license
sherlockhouse/hl
2471ef21e66f0611fba34604c45ddf93d583d01d
9a37fb15113a438fd57a751de5007ab4f1234e27
refs/heads/master
2023-02-14T23:38:40.829580
2021-01-04T09:54:30
2021-01-04T09:54:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,916
java
package com.hl.utils; /** * 常量相关工具类 */ public class ConstUtils { private ConstUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /******************** 存储相关常量 ********************/ /** * KB与Byte的倍数 */ public static final int KB = 1024; /** * MB与Byte的倍数 */ public static final int MB = 1048576; /** * GB与Byte的倍数 */ public static final int GB = 1073741824; public enum MemoryUnit { BYTE, KB, MB, GB } /******************** 时间相关常量 ********************/ /** * 秒与毫秒的倍数 */ public static final int SEC = 1000; /** * 分与毫秒的倍数 */ public static final int MIN = 60000; /** * 时与毫秒的倍数 */ public static final int HOUR = 3600000; /** * 天与毫秒的倍数 */ public static final int DAY = 86400000; public enum TimeUnit { MSEC, SEC, MIN, HOUR, DAY } /******************** 正则相关常量 ********************/ /** * 正则:手机号(简单) */ public static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$"; /** * 正则:手机号(精确) * <p>移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188</p> * <p>联通:130、131、132、145、155、156、175、176、185、186</p> * <p>电信:133、153、173、177、180、181、189</p> * <p>全球星:1349</p> * <p>虚拟运营商:170</p> */ public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$"; /** * 正则:电话号码 */ public static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}"; /** * 正则:身份证号码15位 */ public static final String REGEX_ID_CARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$"; /** * 正则:身份证号码18位 */ public static final String REGEX_ID_CARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$"; /** * 正则:邮箱 */ public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; /** * 正则:URL */ public static final String REGEX_URL = "[a-zA-z]+://[^\\s]*"; /** * 正则:汉字 */ public static final String REGEX_ZH = "^[\\u4e00-\\u9fa5]+$"; /** * 正则:用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位 */ public static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$"; /** * 正则:yyyy-MM-dd格式的日期校验,已考虑平闰年 */ public static final String REGEX_DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$"; /** * 正则:IP地址 */ public static final String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"; /************** 以下摘自http://tool.oschina.net/regex **************/ /** * 正则:双字节字符(包括汉字在内) */ public static final String REGEX_DOUBLE_BYTE_CHAR = "[^\\x00-\\xff]"; /** * 正则:空白行 */ public static final String REGEX_BLANK_LINE = "\\n\\s*\\r"; /** * 正则:QQ号 */ public static final String REGEX_TENCENT_NUM = "[1-9][0-9]{4,}"; /** * 正则:中国邮政编码 */ public static final String REGEX_ZIP_CODE = "[1-9]\\d{5}(?!\\d)"; /** * 正则:正整数 */ public static final String REGEX_POSITIVE_INTEGER = "^[1-9]\\d*$"; /** * 正则:负整数 */ public static final String REGEX_NEGATIVE_INTEGER = "^-[1-9]\\d*$"; /** * 正则:整数 */ public static final String REGEX_INTEGER = "^-?[1-9]\\d*$"; /** * 正则:非负整数(正整数 + 0) */ public static final String REGEX_NOT_NEGATIVE_INTEGER = "^[1-9]\\d*|0$"; /** * 正则:非正整数(负整数 + 0) */ public static final String REGEX_NOT_POSITIVE_INTEGER = "^-[1-9]\\d*|0$"; /** * 正则:正浮点数 */ public static final String REGEX_POSITIVE_FLOAT = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$"; /** * 正则:负浮点数 */ public static final String REGEX_NEGATIVE_FLOAT = "^-[1-9]\\d*\\.\\d*|-0\\.\\d*[1-9]\\d*$"; /************** If u want more please visit http://toutiao.com/i6231678548520731137/ **************/ }
ccb3219e4acb9efcf3b9db87bfb5348aa178fc9f
f020c15f0b64af45686e2836a2e97743f0e1021a
/src/main/java/javabot/web/resources/BotResource.java
fce674e1598abc993c996ca9a4236689baf82e19
[ "BSD-3-Clause" ]
permissive
zhanghongzhitou/javabot
10931d78e236dae1a42a72926a3ff43dd374276f
64eb6bf677e6921e64db5cb77c458a1c0dbbf064
refs/heads/master
2021-01-12T21:05:41.109998
2015-07-04T03:19:02
2015-07-04T03:19:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,873
java
package javabot.web.resources; import com.google.inject.Injector; import io.dropwizard.views.View; import javabot.model.Change; import javabot.model.Factoid; import javabot.web.views.ChangesView; import javabot.web.views.FactoidsView; import javabot.web.views.IndexView; import javabot.web.views.KarmaView; import javabot.web.views.LogsView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class BotResource { private static final Logger LOG = LoggerFactory.getLogger(BotResource.class); private static final String PATTERN = "yyyy-MM-dd"; public static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern(PATTERN); @Inject private Injector injector; @GET @Produces("text/html;charset=ISO-8859-1") public View index(@Context HttpServletRequest request) { if (request.getParameter("test.exception") != null) { throw new RuntimeException("Testing 500 pages"); } return new IndexView(BotResource.this.injector, request); } @GET @Path("/index") @Produces("text/html;charset=ISO-8859-1") public View indexHtml(@Context HttpServletRequest request) { return index(request); } @GET @Path("/factoids") @Produces("text/html;charset=ISO-8859-1") public View factoids(@Context HttpServletRequest request, @QueryParam("page") Integer page, @QueryParam("name") String name, @QueryParam("value") String value, @QueryParam("userName") String userName) { return new FactoidsView(BotResource.this.injector, request, page == null ? 1 : page, new Factoid(name, value, userName)); } @GET @Path("/karma") @Produces("text/html;charset=ISO-8859-1") public View karma(@Context HttpServletRequest request, @QueryParam("page") Integer page, @QueryParam("name") String name, @QueryParam("value") Integer value, @QueryParam("userName") String userName) { return new KarmaView(BotResource.this.injector, request, page == null ? 1 : page); } @GET @Path("/changes") @Produces("text/html;charset=ISO-8859-1") public View changes(@Context HttpServletRequest request, @QueryParam("page") Integer page, @QueryParam("message") String message) { return new ChangesView(BotResource.this.injector, request, page == null ? 1 : page, new Change(message)); } @GET @Path("/logs/{channel}/{date}") @Produces("text/html;charset=ISO-8859-1") public View logs(@Context HttpServletRequest request, @PathParam("channel") String channel, @PathParam("date") String dateString) { LocalDateTime date; String channelName; try { channelName = URLDecoder.decode(channel, "UTF-8"); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } try { if ("today".equals(dateString)) { date = LocalDate.now().atStartOfDay(); } else { date = LocalDate.parse(dateString, FORMAT).atStartOfDay(); } } catch (Exception e) { date = LocalDate.now().atStartOfDay(); } return new LogsView(injector, request, channelName, date); } }
8a215ae65b8a929c569967f5d236484ce83baa41
c69b09fe89c06e1d83ae8c1d87a46678288d0eda
/_extend/solon.socketd.client.smartsocket/src/main/java/org/noear/solon/socketd/client/smartsocket/AioSocketSession.java
891fb44e4fe34631c56389e956f715e5f7957096
[ "Apache-2.0" ]
permissive
dongatsh/solon
fb9d3da2ce67746dd8cfe1fef288e2de1bc3d1a2
4c3a074e8e4db7f367f75603ea8347d2c501c69d
refs/heads/master
2023-08-28T18:16:44.023899
2021-10-31T16:21:03
2021-10-31T16:21:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,184
java
package org.noear.solon.socketd.client.smartsocket; import org.noear.solon.Utils; import org.noear.solon.core.handle.MethodType; import org.noear.solon.core.message.Message; import org.noear.solon.core.message.Session; import org.noear.solon.socketd.Connector; import org.noear.solon.socketd.ProtocolManager; import org.noear.solon.socketd.SessionBase; import org.smartboot.socket.transport.AioSession; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.util.*; public class AioSocketSession extends SessionBase { public static Map<AioSession, Session> sessions = new HashMap<>(); public static Session get(AioSession real) { Session tmp = sessions.get(real); if (tmp == null) { synchronized (real) { tmp = sessions.get(real); if (tmp == null) { tmp = new AioSocketSession(real); sessions.put(real, tmp); } } } return tmp; } public static void remove(AioSession real) { sessions.remove(real); } AioSession real; public AioSocketSession(AioSession real) { this.real = real; } Connector<AioSession> connector; boolean autoReconnect; public AioSocketSession(Connector<AioSession> connector) { this.connector = connector; this.autoReconnect = connector.autoReconnect(); } /** * @return 是否为新链接 */ private boolean prepareNew() throws IOException { if (real == null) { real = connector.open(this); onOpen(); return true; } else { if (autoReconnect) { if (real.isInvalid()) { real = connector.open(this); onOpen(); return true; } } } return false; } @Override public Object real() { return real; } private String _sessionId = Utils.guid(); @Override public String sessionId() { return _sessionId; } @Override public MethodType method() { return MethodType.SOCKET; } @Override public URI uri() { if(connector == null){ return null; }else { return connector.uri(); } } @Override public String path() { if (connector == null) { return ""; } else { return connector.uri().getPath(); } } @Override public void send(String message) { send(Message.wrap(message)); } // @Override // public void send(byte[] message) { // send(MessageUtils.wrap(message)); // } @Override public void send(Message message) { try { super.send(message); synchronized (this) { if (prepareNew()) { send0(handshakeMessage); } // // 转包为Message,再转byte[] // send0(message); } } catch (ClosedChannelException ex) { if (autoReconnect) { real = null; } else { throw new RuntimeException(ex); } } catch (Exception ex) { throw new RuntimeException(ex); } } private void send0(Message message) throws IOException { if (message == null) { return; } ByteBuffer buffer = ProtocolManager.encode(message); if (buffer != null) { real.writeBuffer().writeAndFlush(buffer.array()); } } @Override public void close() throws IOException { real.close(); sessions.remove(real); } @Override public boolean isValid() { return real.isInvalid() == false; } @Override public boolean isSecure() { return false; } @Override public InetSocketAddress getRemoteAddress() { try { return real.getRemoteAddress(); } catch (Throwable ex) { throw new RuntimeException(ex); } } @Override public InetSocketAddress getLocalAddress() { try { return real.getLocalAddress(); } catch (Throwable ex) { throw new RuntimeException(ex); } } @Override public void setAttachment(Object obj) { real.setAttachment(obj); } @Override public <T> T getAttachment() { return real.getAttachment(); } @Override public Collection<Session> getOpenSessions() { return new ArrayList<>(sessions.values()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AioSocketSession that = (AioSocketSession) o; return Objects.equals(real, that.real); } @Override public int hashCode() { return Objects.hash(real); } }
5baad12667d11eca984965b9bf17b8049f2753a3
006f4862ad619bfe9f7edb7fb458bde99b1275e3
/jcr-oak-rpc-core/src/main/java/org/jumlabs/jcr/oak/rpc/util/RepositoryUtils.java
c1d104aac074f16e9b1eedcf8eb318c320a20da4
[ "MIT" ]
permissive
ottogiron/jcr-oak-rpc
13dfcc36fac176fadce00bcb7807200de118fc75
2d89278ebdfec083a8e25900a8f9028b24d65f1d
refs/heads/master
2016-09-06T01:23:49.772591
2015-01-19T02:35:05
2015-01-19T02:35:05
22,048,326
3
0
null
null
null
null
UTF-8
Java
false
false
2,605
java
/* * 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 org.jumlabs.jcr.oak.rpc.util; import javax.jcr.NoSuchWorkspaceException; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; import javax.security.auth.login.LoginException; import org.apache.jackrabbit.oak.api.ContentSession; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.api.Tree; import org.jumlabs.jcr.oak.rpc.api.JRepository; import org.jumlabs.jcr.oak.rpc.thrift.api.TTree; import org.jumlabs.jcr.oak.rpc.thrift.api.TTreeStatus; import org.jumlabs.jcr.oak.rpc.thrift.nodetype.TNodeType; import org.springframework.beans.BeanUtils; /** * * @author otto */ public class RepositoryUtils { public static Tree getTree(JRepository repository,String path) throws LoginException, NoSuchWorkspaceException{ Tree tree = null; if(path != null){ ContentSession session = repository.loginAdministrative(null); tree = session.getLatestRoot().getTree(path); } return tree; } public static Tree getTree(JRepository repository,TTree ttree) throws LoginException, NoSuchWorkspaceException{ Tree tree = getTree(repository, ttree.getPath()); return tree; } public static Root getJCRRoot(JRepository repository) throws LoginException, NoSuchWorkspaceException{ ContentSession session = repository.loginAdministrative(null); return session.getLatestRoot(); } public static TTree toTTree(Tree tree){ TTree ttree = new TTree(); BeanUtils.copyProperties(tree, ttree); ttree.setExists(tree.exists()); switch (tree.getStatus()) { case MODIFIED: ttree.setStatus(TTreeStatus.MODIFIED); break; case NEW: ttree.setStatus(TTreeStatus.NEW); break; case UNCHANGED: ttree.setStatus(TTreeStatus.UNCHANGED); break; } return ttree; } public static NodeType getNodeType(Session session, TNodeType tnodeType) throws RepositoryException{ NodeTypeManager jcrNodeTypeManager = session.getWorkspace().getNodeTypeManager(); NodeType nodeType = jcrNodeTypeManager.getNodeType(tnodeType.getName()); return nodeType; } }
10d8d65728d8a08f0b721a0aa5ec446fe28a0daa
a6944acff1dd69c3acc654105c973ca98ecfb502
/Portals/branches/Engage_REL2.0_03_05Aug14/EngageFusionApplication/EngageModel/src/com/sfr/engage/model/queries/rvo/PrtHomeTransactionsRVORowImpl.java
a49dc3219574bc35a987108a9e2130630cd17a40
[]
no_license
sunsu18/testSvnSync
c00b2a2b9fce07b8eceda1620bfb730a104909eb
332f85c0684f8d5dea786a28f71cb4b3e8e39f65
refs/heads/master
2020-05-20T09:17:10.981932
2014-11-06T08:30:23
2014-11-06T08:30:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
18,728
java
package com.sfr.engage.model.queries.rvo; import com.sfr.engage.core.PartnerInfo; import java.util.List; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import oracle.jbo.domain.Date; import oracle.jbo.domain.Number; import oracle.jbo.domain.Timestamp; import oracle.jbo.server.AttributeDefImpl; import oracle.jbo.server.ViewRowImpl; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Mon Jun 30 12:43:16 IST 2014 // --- Custom code may be added to this class. // --- Warning: Do not modify method signatures of generated methods. // --------------------------------------------------------------------- public class PrtHomeTransactionsRVORowImpl extends ViewRowImpl { /** * AttributesEnum: generated enum for identifying attributes and accessors. Do not modify. */ private ExternalContext ectx=FacesContext.getCurrentInstance().getExternalContext(); private HttpServletRequest request=(HttpServletRequest)ectx.getRequest(); private HttpSession session=request.getSession(false); private List<PartnerInfo> partnerInfoList; public enum AttributesEnum { PurchaseCurrency { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getPurchaseCurrency(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setPurchaseCurrency((String)value); } } , PartnerId { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getPartnerId(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setPartnerId((String)value); } } , Ksid { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getKsid(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setKsid((String)value); } } , TransactionTime { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getTransactionTime(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setTransactionTime((Timestamp)value); } } , TransactionDt { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getTransactionDt(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setTransactionDt((Date)value); } } , TransactionType { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getTransactionType(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setTransactionType((String)value); } } , Card1Id { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getCard1Id(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setCard1Id((String)value); } } , StationName { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getStationName(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setStationName((String)value); } } , ProductName { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getProductName(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setProductName((String)value); } } , CurrencyGrossAmount { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getCurrencyGrossAmount(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setCurrencyGrossAmount((Number)value); } } , Quantity { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getQuantity(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setQuantity((Number)value); } } , UnitOfMeasure { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getUnitOfMeasure(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setUnitOfMeasure((String)value); } } , Card { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getCard(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setCard((String)value); } } , CardTextLine2 { public Object get(PrtHomeTransactionsRVORowImpl obj) { return obj.getCardTextLine2(); } public void put(PrtHomeTransactionsRVORowImpl obj, Object value) { obj.setCardTextLine2((String)value); } } ; private static AttributesEnum[] vals = null; private static int firstIndex = 0; public abstract Object get(PrtHomeTransactionsRVORowImpl object); public abstract void put(PrtHomeTransactionsRVORowImpl object, Object value); public int index() { return AttributesEnum.firstIndex() + ordinal(); } public static int firstIndex() { return firstIndex; } public static int count() { return AttributesEnum.firstIndex() + AttributesEnum.staticValues().length; } public static AttributesEnum[] staticValues() { if (vals == null) { vals = AttributesEnum.values(); } return vals; } } public static final int PURCHASECURRENCY = AttributesEnum.PurchaseCurrency.index(); public static final int PARTNERID = AttributesEnum.PartnerId.index(); public static final int KSID = AttributesEnum.Ksid.index(); public static final int TRANSACTIONTIME = AttributesEnum.TransactionTime.index(); public static final int TRANSACTIONDT = AttributesEnum.TransactionDt.index(); public static final int TRANSACTIONTYPE = AttributesEnum.TransactionType.index(); public static final int CARD1ID = AttributesEnum.Card1Id.index(); public static final int STATIONNAME = AttributesEnum.StationName.index(); public static final int PRODUCTNAME = AttributesEnum.ProductName.index(); public static final int CURRENCYGROSSAMOUNT = AttributesEnum.CurrencyGrossAmount.index(); public static final int QUANTITY = AttributesEnum.Quantity.index(); public static final int UNITOFMEASURE = AttributesEnum.UnitOfMeasure.index(); public static final int CARD = AttributesEnum.Card.index(); public static final int CARDTEXTLINE2 = AttributesEnum.CardTextLine2.index(); /** * This is the default constructor (do not remove). */ public PrtHomeTransactionsRVORowImpl() { } /** * Gets the attribute value for the calculated attribute PurchaseCurrency. * @return the PurchaseCurrency */ public String getPurchaseCurrency() { return (String) getAttributeInternal(PURCHASECURRENCY); } /** * Sets <code>value</code> as the attribute value for the calculated attribute PurchaseCurrency. * @param value value to set the PurchaseCurrency */ public void setPurchaseCurrency(String value) { setAttributeInternal(PURCHASECURRENCY, value); } /** * Gets the attribute value for the calculated attribute PartnerId. * @return the PartnerId */ public String getPartnerId() { return (String) getAttributeInternal(PARTNERID); } /** * Sets <code>value</code> as the attribute value for the calculated attribute PartnerId. * @param value value to set the PartnerId */ public void setPartnerId(String value) { setAttributeInternal(PARTNERID, value); } /** * Gets the attribute value for the calculated attribute Ksid. * @return the Ksid */ public String getKsid() { return (String) getAttributeInternal(KSID); } /** * Sets <code>value</code> as the attribute value for the calculated attribute Ksid. * @param value value to set the Ksid */ public void setKsid(String value) { setAttributeInternal(KSID, value); } /** * Gets the attribute value for the calculated attribute TransactionTime. * @return the TransactionTime */ public Timestamp getTransactionTime() { return (Timestamp) getAttributeInternal(TRANSACTIONTIME); } /** * Sets <code>value</code> as the attribute value for the calculated attribute TransactionTime. * @param value value to set the TransactionTime */ public void setTransactionTime(Timestamp value) { setAttributeInternal(TRANSACTIONTIME, value); } /** * Gets the attribute value for the calculated attribute TransactionDt. * @return the TransactionDt */ public Date getTransactionDt() { return (Date) getAttributeInternal(TRANSACTIONDT); } /** * Sets <code>value</code> as the attribute value for the calculated attribute TransactionDt. * @param value value to set the TransactionDt */ public void setTransactionDt(Date value) { setAttributeInternal(TRANSACTIONDT, value); } /** * Gets the attribute value for the calculated attribute TransactionType. * @return the TransactionType */ public String getTransactionType() { return (String) getAttributeInternal(TRANSACTIONTYPE); } /** * Sets <code>value</code> as the attribute value for the calculated attribute TransactionType. * @param value value to set the TransactionType */ public void setTransactionType(String value) { setAttributeInternal(TRANSACTIONTYPE, value); } /** * Gets the attribute value for the calculated attribute Card1Id. * @return the Card1Id */ public String getCard1Id() { return (String) getAttributeInternal(CARD1ID); } /** * Sets <code>value</code> as the attribute value for the calculated attribute Card1Id. * @param value value to set the Card1Id */ public void setCard1Id(String value) { setAttributeInternal(CARD1ID, value); } /** * Gets the attribute value for the calculated attribute StationName. * @return the StationName */ public String getStationName() { return (String) getAttributeInternal(STATIONNAME); } /** * Sets <code>value</code> as the attribute value for the calculated attribute StationName. * @param value value to set the StationName */ public void setStationName(String value) { setAttributeInternal(STATIONNAME, value); } /** * Gets the attribute value for the calculated attribute ProductName. * @return the ProductName */ public String getProductName() { return (String) getAttributeInternal(PRODUCTNAME); } /** * Sets <code>value</code> as the attribute value for the calculated attribute ProductName. * @param value value to set the ProductName */ public void setProductName(String value) { setAttributeInternal(PRODUCTNAME, value); } /** * Gets the attribute value for the calculated attribute CurrencyGrossAmount. * @return the CurrencyGrossAmount */ public Number getCurrencyGrossAmount() { return (Number) getAttributeInternal(CURRENCYGROSSAMOUNT); } /** * Sets <code>value</code> as the attribute value for the calculated attribute CurrencyGrossAmount. * @param value value to set the CurrencyGrossAmount */ public void setCurrencyGrossAmount(Number value) { setAttributeInternal(CURRENCYGROSSAMOUNT, value); } /** * Gets the attribute value for the calculated attribute Quantity. * @return the Quantity */ public Number getQuantity() { if(getUnitOfMeasure() != null && ("STK").equalsIgnoreCase(getUnitOfMeasure())){ oracle.jbo.domain.Number num; return new oracle.jbo.domain.Number(1); } else{ return (Number) getAttributeInternal(QUANTITY); } } /** * Sets <code>value</code> as the attribute value for the calculated attribute Quantity. * @param value value to set the Quantity */ public void setQuantity(Number value) { setAttributeInternal(QUANTITY, value); } /** * Gets the attribute value for the calculated attribute UnitOfMeasure. * @return the UnitOfMeasure */ public String getUnitOfMeasure() { return (String) getAttributeInternal(UNITOFMEASURE); } /** * Sets <code>value</code> as the attribute value for the calculated attribute UnitOfMeasure. * @param value value to set the UnitOfMeasure */ public void setUnitOfMeasure(String value) { setAttributeInternal(UNITOFMEASURE, value); } /** * Gets the attribute value for the calculated attribute Card. * @return the Card */ public String getCard() { String result=""; result = "XXXX" + getCard1Id().toString().substring(getCard1Id().length()-4, getCard1Id().toString().length()); return result; } /** * Sets <code>value</code> as the attribute value for the calculated attribute Card. * @param value value to set the Card */ public void setCard(String value) { setAttributeInternal(CARD, value); } /** * Gets the attribute value for the calculated attribute CardTextLine2. * @return the CardTextLine2 */ public String getCardTextLine2() { String cardTextLine=""; if(session!=null) { if (session.getAttribute("Partner_Object_List") != null) { partnerInfoList = (List<PartnerInfo>)session.getAttribute("Partner_Object_List"); String partnerId=getPartnerId(); String cardId=getKsid().toString().trim(); if (partnerInfoList != null) { for (int k = 0; k < partnerInfoList.size(); k++) { if (partnerId.equalsIgnoreCase(partnerInfoList.get(k).getPartnerValue().toString())) { for (int ac = 0;ac < partnerInfoList.get(k).getAccountList().size();ac++) { for (int cg = 0;cg < partnerInfoList.get(k).getAccountList().get(ac).getCardGroup().size();cg++) { for (int cd = 0;cd < partnerInfoList.get(k).getAccountList().get(ac).getCardGroup().get(cg).getCard().size();cd++) { if(cardId.equalsIgnoreCase(partnerInfoList.get(k).getAccountList().get(ac).getCardGroup().get(cg).getCard().get(cd).getCardID())) { if(partnerInfoList.get(k).getAccountList().get(ac).getCardGroup().get(cg).getCard().get(cd).getCardTextline2() != null) { cardTextLine= partnerInfoList.get(k).getAccountList().get(ac).getCardGroup().get(cg).getCard().get(cd).getCardTextline2().toString(); } } } } } } } } } } return cardTextLine; } /** * Sets <code>value</code> as the attribute value for the calculated attribute CardTextLine2. * @param value value to set the CardTextLine2 */ public void setCardTextLine2(String value) { setAttributeInternal(CARDTEXTLINE2, value); } /** * getAttrInvokeAccessor: generated method. Do not modify. * @param index the index identifying the attribute * @param attrDef the attribute * @return the attribute value * @throws Exception */ protected Object getAttrInvokeAccessor(int index, AttributeDefImpl attrDef) throws Exception { if ((index >= AttributesEnum.firstIndex()) && (index < AttributesEnum.count())) { return AttributesEnum.staticValues()[index - AttributesEnum.firstIndex()].get(this); } return super.getAttrInvokeAccessor(index, attrDef); } /** * setAttrInvokeAccessor: generated method. Do not modify. * @param index the index identifying the attribute * @param value the value to assign to the attribute * @param attrDef the attribute * @throws Exception */ protected void setAttrInvokeAccessor(int index, Object value, AttributeDefImpl attrDef) throws Exception { if ((index >= AttributesEnum.firstIndex()) && (index < AttributesEnum.count())) { AttributesEnum.staticValues()[index - AttributesEnum.firstIndex()].put(this, value); return; } super.setAttrInvokeAccessor(index, value, attrDef); } }
[ "pdee@f308e16d-57e9-4fa7-a310-9aba3baf408f" ]
pdee@f308e16d-57e9-4fa7-a310-9aba3baf408f
f55725bbb5cd260a88fdfa16efa377974104e3a2
65cab19bc4a8c2d7e34aaac2b91e4a870edcf523
/src/day16_forLoop/ContinueStatement.java
9431d4d6e377655fc576ee67714e934a04250b81
[]
no_license
acikmaz/Spring2020JavaPractice
57ed459e997582a11e03f8f5c666ecef9b2d11c2
cab29949e58943179ab1ce5d98ca20053bb73745
refs/heads/master
2023-01-15T21:56:59.283081
2020-11-23T20:34:11
2020-11-23T20:34:11
257,927,026
0
0
null
null
null
null
UTF-8
Java
false
false
613
java
package day16_forLoop; public class ContinueStatement { public static void main(String[] args) { for (int i = 1; i <= 5; i++){ if (i == 3){ continue; } System.out.println(i); } for (int i = 0; i <= 20; i++){ if (i % 2 != 0){ //skips all the odd numbers continue; } System.out.println(i + ""); } for (int i = 0; i <= 20; i++){ if (i % 2 == 0){ continue; } System.out.println(i + ""); } } }
b2ebfaf5e5e308e514629227c8ae21b7df3248e0
8a67a7ac041c1213872b19fa24d9b077e9b7d0da
/pippo-demo-basic/src/main/java/ro/pippo/demo/basic/HelloWorld.java
b636bd1793c4ad40fa73c338d3f82d6daea7acc9
[]
no_license
junlapong/pippo-demo
d7238281b7f27e88aa2bd7fe0b94b40412c08027
ea2ac07ee32f165eb5c107199c12bb09dcc7685f
refs/heads/master
2021-01-15T07:56:57.431957
2016-04-30T19:56:20
2016-04-30T19:56:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,067
java
/* * Copyright (C) 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.pippo.demo.basic; import ro.pippo.core.Pippo; /** * @author Decebal Suiu */ public class HelloWorld { public static void main(String[] args) { // the super short version Pippo.send("Hello World!"); /* // the "clean" approach Pippo pippo = new Pippo(); pippo.getApplication().GET("/", routeContext -> routeContext.send("Hello World!")); pippo.start(); */ } }
b0e17f6e34f636de963515f59a1a57efb20dc6f5
e72267e4c674dc3857dc91db556572534ecf6d29
/mybatis-3-master/src/test/java/org/apache/ibatis/submitted/results_id/User.java
1fe84c84661c68f2f41d787880cd97ebfd559505
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-3-Clause" ]
permissive
lydon-GH/mybatis-study
4be7f279529a33ead3efa9cd79d60cd44d2184a9
a8a89940bfa6bb790e78e1c28b0c7c0a5d69e491
refs/heads/main
2023-07-29T06:55:56.549751
2021-09-04T09:08:25
2021-09-04T09:08:25
403,011,812
0
0
null
null
null
null
UTF-8
Java
false
false
1,139
java
/* * Copyright ${license.git.copyrightYears} the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.submitted.results_id; public class User { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User() { super(); } public User(Integer id, String name) { super(); this.id = id; this.name = name; } }
a39a29302048aedb253752a0983ab74e2ec7128a
d3ff6e6afb81af0a307a97f5e63e05aafbde813d
/client/app/src/main/java/com/theah64/soundclouddownloader/utils/APIRequestBuilder.java
66ea09568137afb887b957f7a180a89b5cbd0cf8
[ "Apache-2.0" ]
permissive
emtee40/SoundCloud-Downloader-3
53578a06d7ce9a86107bd3d83a404395203b718d
c82481a20cb5c41b32b4322ba021a5116fe0335a
refs/heads/master
2023-01-08T18:52:38.200478
2018-11-30T14:40:37
2018-11-30T14:40:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,387
java
package com.theah64.soundclouddownloader.utils; import android.support.annotation.Nullable; import android.util.Log; import com.theah64.bugmailer.core.BugMailerNode; import com.theah64.bugmailer.core.NodeBuilder; import com.theah64.bugmailer.models.Node; import java.util.List; import okhttp3.FormBody; import okhttp3.Request; /** * Created by shifar on 29/7/16. * Utility class to create API request object. */ public class APIRequestBuilder implements BugMailerNode { public static final String BASE_URL = App.IS_DEBUG_MODE ? "http://192.168.0.107:8080/v1" : "http://theapache64.com/scd/v1"; private static final String X = APIRequestBuilder.class.getSimpleName(); private static final String CURL_DATA_KEY = " --data \""; private static final String KEY_AUTHORIZATION = "Authorization"; private final Request.Builder requestBuilder = new Request.Builder(); private final StringBuilder logBuilder = new StringBuilder(); private final StringBuilder curlBuilder = new StringBuilder(); private final String url; private FormBody.Builder params = new FormBody.Builder(); public APIRequestBuilder(String route, @Nullable final String apiKey) { this.url = BASE_URL + route; appendLog("URL", url); curlBuilder.append("curl ").append(url); if (apiKey != null) { requestBuilder.addHeader(KEY_AUTHORIZATION, apiKey); appendLog(KEY_AUTHORIZATION, apiKey); curlBuilder.append(String.format(" --header \"%s: %s\" ", KEY_AUTHORIZATION, apiKey)); } logBuilder.append("--------------------------------\n"); } private static boolean isReady(String route) { /*if (route.equals("/get_latest_version_details")) { return false; }*/ //All routes are ready return true; } private void appendLog(String key, String value) { logBuilder.append(String.format("%s:%s\n", key, value)); } private APIRequestBuilder addParam(final boolean isAllowNull, final String key, String value) { if (isAllowNull) { this.params.add(key, value); appendLog(key, value); addParamToCurlBuilder(key, value); } else { //value must not be null. if (value != null) { this.params.add(key, value); addParamToCurlBuilder(key, value); appendLog(key, value); } } return this; } private void addParamToCurlBuilder(String key, String value) { if (curlBuilder.indexOf(CURL_DATA_KEY) == -1) { curlBuilder.append(CURL_DATA_KEY); } curlBuilder.append(key).append("=").append(value).append("&"); } public APIRequestBuilder addParam(final String key, final String value) { return addParam(true, key, value); } public APIRequestBuilder addParam(final String key, final int value) { return addParam(true, key, String.valueOf(value)); } public APIRequestBuilder addParam(final String key, final boolean value) { return addParam(true, key, value ? "1" : "0"); } /** * Used to build the OkHttpRequest. */ public Request build() { logBuilder.append("CURL: ").append(getCompleteCurlCommand()); logBuilder.append("\nCURL (ubuntu): ").append(getCompleteCurlCommand()).append(" | jq '.'"); logBuilder.append("\n--------------------------------\n"); requestBuilder .url(url) .post(params.build()); Log.d(X, "Request : " + logBuilder.toString()); return requestBuilder.build(); } public APIRequestBuilder addOptionalParam(String key, String value) { return addParam(false, key, value); } @Override public List<Node> getNodes() { return new NodeBuilder() .add("API Request", logBuilder.toString()) .add("cURL command", getCompleteCurlCommand()) .add("cURL command (ubuntu-jq)", getCompleteCurlCommand() + " | jq '.'") .build(); } private String getCompleteCurlCommand() { final String curlCommand = curlBuilder.toString(); return curlCommand.contains(CURL_DATA_KEY) && !curlCommand.endsWith("\"") ? curlBuilder.toString() + "\"" : curlCommand; } }
b172bccfc1bc147f8ca3e619a8204c6db39b102b
79dba01294d9a50e89d6233e406b8ea6c3171554
/exonum-java-binding/core/src/test/java/com/exonum/binding/core/storage/indices/ImmutableModificationCounterTest.java
5d7e77a39a71e11b3b6c92c80bbbd22c7a662be7
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
alekseysidorov/exonum-java-binding
8e78b831cbe988f6b7f3b76c57bfdf332aca3544
78ac515edece79f6227e0dcbd56f8173bad7864c
refs/heads/master
2020-12-23T21:57:35.488253
2020-01-30T11:44:51
2020-01-30T11:44:51
237,287,473
0
0
Apache-2.0
2020-01-30T19:20:07
2020-01-30T19:20:06
null
UTF-8
Java
false
false
1,010
java
/* * Copyright 2019 The Exonum Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exonum.binding.core.storage.indices; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; class ImmutableModificationCounterTest { private static final ImmutableModificationCounter COUNTER = ImmutableModificationCounter.INSTANCE; @Test void forbidsModifications() { assertThrows(IllegalStateException.class, COUNTER::notifyModified); } }
4446885e130493ff72016ea01443f3a1163e97df
5b9fe5339a689c09edfc37c228bdf4229205809d
/Acme-Demos-2.0/src/main/java/repositories/DeveloperRepository.java
88fa969e15e895881f8517e5fce5e0903faf79eb
[]
no_license
rrodriguezos/Demos-2.0
220d46b8ee36766e1340733b56c38217c216ee3c
b0661549c71a1ac00422d745c6dce0ebc2909fa9
refs/heads/master
2021-01-13T02:51:19.357769
2017-01-03T12:03:25
2017-01-03T12:03:25
77,135,594
0
0
null
null
null
null
UTF-8
Java
false
false
778
java
package repositories; import java.util.Collection; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import domain.Developer; @Repository public interface DeveloperRepository extends JpaRepository<Developer, Integer> { @Query("select d from Developer d where d.userAccount.id=?1") Developer findByDeveloperAccountId(int userAccountId); @Query("select a from Administrator a where a.userAccount.id=?1") Developer findByUserAccountId(int userAccountId); @Query("select distinct(d.developer) from Demo d where d.comments.size > (select avg(d.comments.size) from Demo d)") Collection<Developer> developersMoreCommentsThanAvg(); }
[ "fragilsan@ac1cdb4f-9ad0-4dce-b5c6-dc97fe644ee3" ]
fragilsan@ac1cdb4f-9ad0-4dce-b5c6-dc97fe644ee3
83405303ec1e0aabc7a5e2ee96c37dfbc9855b4b
7206d0f150e3d64abea022fa76223cb19b17e271
/src/main/java/com/epam/am/entity/Airliner.java
e5ea9311f71cd84fbb50934958b40d5bcf8b31e8
[]
no_license
marushkaalex/SimpleAirlines
a41fde8744b98c9699cf8ce85f979c0908952d4e
99185db6e32241f3ccb11741394bc9e347971d89
refs/heads/master
2021-01-20T10:38:41.350671
2014-06-23T10:42:03
2014-06-23T10:42:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,123
java
package com.epam.am.entity; import com.sun.istack.internal.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.*; import java.util.ArrayList; import java.util.List; public class Airliner extends Plane implements Cloneable { private final static Logger LOG = LoggerFactory.getLogger(Airliner.class); private int seatingCapacity; private List<Passenger> passengers; public Airliner(Airliner.Builder builder) { super(builder); seatingCapacity = builder.seatingCapacity; passengers = builder.passengers; } public int getSeatingCapacity() { return seatingCapacity; } public List<Passenger> getPassengers() { return passengers; } public boolean addPassenger(Passenger passenger) { if (passengers.size() < seatingCapacity) { for (Passenger passenger1 : passengers) { if (passenger.getId() == passenger1.getId()) { return false; } } passengers.add(passenger); LOG.info("{}: passenger {} has been added", getBriefInfo(), passenger); return true; } LOG.info("{}: passenger {} hasn't been added", getBriefInfo(), passenger); return false; } public Passenger getPassenger(long id) { for (Passenger passenger : passengers) { if (passenger.getId() == id) { return passenger; } } throw new IllegalArgumentException("no passenger with id = " + id); } public Passenger getPassenger(String lastName) { for (Passenger passenger : passengers) { if (passenger.getLastName().equals(lastName)) { return passenger; } } throw new IllegalArgumentException("no passenger with lastname \"" + lastName + "\""); } public void removePassenger(Passenger passenger) { passengers.remove(passenger); LOG.info("{}: passenger {} has been removed", getBriefInfo(), passenger); } public void removePassenger(long id) { for (Passenger passenger : passengers) { if (passenger.getId() == id) { passengers.remove(passenger); LOG.info("{}: passenger {} has been removed", getBriefInfo(), passenger); break; } } } public void removePassenger(String lastName) { for (Passenger passenger : passengers) { if (passenger.getLastName().equals(lastName)) { passengers.remove(passenger); LOG.info("{}: passenger {} has been removed", getBriefInfo(), passenger); break; } } } @Override public String toString() { return super.toString() + "Airliner{" + "seatingCapacity=" + seatingCapacity + ", passengers=" + passengers + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Airliner airliner = (Airliner) o; return seatingCapacity == airliner.seatingCapacity; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + seatingCapacity; return result; } public Airliner deepClone() { List<Passenger> pas = new ArrayList<>(); for (Passenger passenger : passengers) { pas.add(passenger); } return new Builder().id(getId()) .model(getModel()) .currentLocation(new Point(getCurrentLocation().x, getCurrentLocation().y)) .seatingCapacity(seatingCapacity) .passengers(pas) .build(); } public static class Builder extends Plane.Builder<Builder> { private int seatingCapacity = 0; private List<Passenger> passengers; public Builder seatingCapacity(int val) { seatingCapacity = numberCheck(val); return this; } public Builder passengers(@NotNull List<Passenger> val) { if (val == null) throw new IllegalArgumentException("Passengers list must not be null"); if (val.size() > seatingCapacity) throw new IllegalArgumentException("Too much passengers"); passengers = val; return this; } public Airliner build() { return new Airliner(this); } } /** * Compares by */ public static class Comparator implements java.util.Comparator<Airliner> { @Override public int compare(Airliner o1, Airliner o2) { if (o1.getSeatingCapacity() == o2.getSeatingCapacity()) { return 0; } return o1.getSeatingCapacity() > o2.getSeatingCapacity() ? 1 : -1; } } }
622e39da3ff3bf8ff6f006fdd5c9e34c2f9da791
2cb6310167c7a8619005214390bdd4a428c96f3e
/src/com/ruiping/BankApp/ui/YearMiddleXiashuActivity.java
2babed85c6c2842f32b7fc410de93e82b10dc8ff
[]
no_license
eryiyi/BankApp
24619dc691b37f626fe9c6cab6b9afef1ca89dd6
faf70fd7d9de9188900dd6bf2d9b1def360e5f7f
refs/heads/master
2020-05-21T16:23:42.040848
2017-05-27T08:43:56
2017-05-27T08:43:56
62,428,333
0
0
null
null
null
null
UTF-8
Java
false
false
8,008
java
package com.ruiping.BankApp.ui; import android.content.Intent; import android.os.Bundle; import android.text.format.DateUtils; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.ruiping.BankApp.R; import com.ruiping.BankApp.adapter.ItemWeeklyAdapter; import com.ruiping.BankApp.base.BaseActivity; import com.ruiping.BankApp.base.InternetURL; import com.ruiping.BankApp.data.BankJobReportData; import com.ruiping.BankApp.entiy.BankJobReport; import com.ruiping.BankApp.library.PullToRefreshBase; import com.ruiping.BankApp.library.PullToRefreshListView; import com.ruiping.BankApp.util.Contance; import com.ruiping.BankApp.util.StringUtil; import com.ruiping.BankApp.widget.CustomProgressDialog; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by zhl on 2016/7/2. * 下属年中报告 */ public class YearMiddleXiashuActivity extends BaseActivity implements View.OnClickListener { private TextView title; private TextView back; private TextView right_btn; private TextView no_data; private PullToRefreshListView lstv; private ItemWeeklyAdapter adapter; private List<BankJobReport> lists = new ArrayList<BankJobReport>(); private int pageIndex = 1; private static boolean IS_REFRESH = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.weekly_list_activity); initView(); progressDialog = new CustomProgressDialog(YearMiddleXiashuActivity.this, "正在加载中",R.anim.custom_dialog_frame); progressDialog.setCancelable(true); progressDialog.setIndeterminate(true); progressDialog.show(); getWeekDate(); } private void initView() { no_data = (TextView) this.findViewById(R.id.no_data); lstv = (PullToRefreshListView) this.findViewById(R.id.lstv); title = (TextView) this.findViewById(R.id.title); back = (TextView) this.findViewById(R.id.back); right_btn = (TextView) this.findViewById(R.id.right_btn); right_btn.setText("添加"); back.setOnClickListener(this); right_btn.setOnClickListener(this); title.setText("下属年中报告"); adapter = new ItemWeeklyAdapter(lists, YearMiddleXiashuActivity.this); lstv.setAdapter(adapter); lstv.setMode(PullToRefreshBase.Mode.BOTH); lstv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL); refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); IS_REFRESH = true; pageIndex = 1; getWeekDate(); } @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) { String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL); refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); IS_REFRESH = false; pageIndex++; getWeekDate(); } }); no_data.setVisibility(View.GONE); lstv.setVisibility(View.VISIBLE); lstv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { BankJobReport bankJobReport = lists.get(position-1); Intent intent = new Intent(YearMiddleXiashuActivity.this, YearMiddleDetailActivtiy.class); intent.putExtra("bankJobReport", bankJobReport); startActivity(intent); } }); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.back: finish(); break; case R.id.right_btn: //添加年中报告 { Intent intent = new Intent(YearMiddleXiashuActivity.this, AddYearMiddleActivtiy.class); startActivity(intent); } break; } } //查询下属年中报告 private void getWeekDate() { StringRequest request = new StringRequest( Request.Method.POST, InternetURL.WEEK_ALL_SUBORDINATE_URL, new Response.Listener<String>() { @Override public void onResponse(String s) { if (StringUtil.isJson(s)) { try { JSONObject jo = new JSONObject(s); String code1 = jo.getString("code"); if (Integer.parseInt(code1) == 200) { BankJobReportData data = getGson().fromJson(s, BankJobReportData.class); if (IS_REFRESH) { lists.clear(); } lists.addAll(data.getData()); lstv.onRefreshComplete(); adapter.notifyDataSetChanged(); } else { Toast.makeText(YearMiddleXiashuActivity.this, R.string.get_data_error, Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(YearMiddleXiashuActivity.this, R.string.get_data_error, Toast.LENGTH_SHORT).show(); } if(progressDialog != null){ progressDialog.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if(progressDialog != null){ progressDialog.dismiss(); } Toast.makeText(YearMiddleXiashuActivity.this, R.string.get_data_error, Toast.LENGTH_SHORT).show(); } } ) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("empId", getGson().fromJson(getSp().getString(Contance.EMP_ID, ""), String.class)); params.put("reportType", "5"); params.put("pagecurrent", String.valueOf(pageIndex)); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Content-Type", "application/x-www-form-urlencoded"); return params; } }; getRequestQueue().add(request); } }
35e52e17fee35899fec0b52c54df813fb06a7ef6
3000194e6964a2d490c943cb23457e4159824dbd
/backend/src/main/java/com/luxoft/horizon/dir/service/app/ScreenshotRepository.java
b83a784609476d52b0da7ca7fb4c09cadd328c02
[]
no_license
PavelBogatyrev/directorate
f3e683b289d3e37cc6004bbcca74c3eb9ee5c2d8
1b9ddbc29f562edfef09f13dcb01806fea25b391
refs/heads/master
2021-01-19T11:38:54.691900
2017-04-11T22:23:18
2017-04-11T22:23:18
87,984,241
0
0
null
null
null
null
UTF-8
Java
false
false
1,498
java
package com.luxoft.horizon.dir.service.app; import com.luxoft.horizon.dir.entities.app.Screenshot; import com.luxoft.horizon.dir.entities.app.ScreenshotStatus; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; /** * Created by bogatp on 19.04.16. */ @Service public interface ScreenshotRepository extends CrudRepository<Screenshot, Long> { List<Screenshot> findByStatus(ScreenshotStatus status); List<Screenshot> findByPeriodAndViewAndStatus(String period, String view, ScreenshotStatus status); @Query(value = "select count(s.id) from Screenshot s WHERE s.period = ?1 and s.status = ?2") int findNumByPeriodAndStatus(String period, ScreenshotStatus status); @Query(value = "select count(s.id) from Screenshot s WHERE s.period = ?1") int findNumByPeriod(String period); @Modifying @Transactional @Query(value = "update Screenshot s set s.status=?1 WHERE s.period = ?2") int updateStatus(ScreenshotStatus status, String period); @Modifying @Transactional @Query(value = "update Screenshot s set s.status=?1") int updateStatusAll(ScreenshotStatus status ); @Modifying @Transactional @Query(value = "delete from Screenshot s where s.period = ?1") int deleteByPeriod(String period); }
7167e404d79b3a8c34025c30292105a58b3f6ae0
0967b83fa31fb02d59271248afa06f4aab0db0e1
/pinyougou-sellergoods-service/src/main/java/com/pinyougou/sellergoods/service/impl/ItemServiceImpl.java
4ba8eebbf2e53fe38594696bd9d1cfb19143d8c6
[]
no_license
issueDriver/pinyougou
9e26b8b84f5b0fe40d766002cebb5ac1b3259b2d
5f9a0716d99eb3f94d568808ef09568aa00262e2
refs/heads/master
2020-05-02T14:19:38.429440
2019-04-18T02:21:20
2019-04-18T02:21:20
178,007,133
0
0
null
null
null
null
UTF-8
Java
false
false
3,611
java
package com.pinyougou.sellergoods.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.pinyougou.entity.PageResult; import com.pinyougou.mapper.TbItemMapper; import com.pinyougou.pojo.TbItem; import com.pinyougou.pojo.TbItemExample; import com.pinyougou.pojo.TbItemExample.Criteria; import com.pinyougou.sellergoods.service.ItemService; /** * 服务实现层 * @author zuojie * */ @Service public class ItemServiceImpl implements ItemService { @Autowired private TbItemMapper itemMapper; /** * 查询全部 */ @Override public List<TbItem> findAll() { return itemMapper.selectByExample(null); } /** * 按分页查询 */ @Override public PageResult findPage(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); Page<TbItem> page= (Page<TbItem>) itemMapper.selectByExample(null); return new PageResult(page.getTotal(), page.getResult()); } /** * 增加 */ @Override public void add(TbItem item) { itemMapper.insert(item); } /** * 修改 */ @Override public void update(TbItem item){ itemMapper.updateByPrimaryKey(item); } /** * 根据ID获取实体 * @param id * @return */ @Override public TbItem findOne(Long id){ return itemMapper.selectByPrimaryKey(id); } /** * 批量删除 */ @Override public void delete(Long[] ids) { for(Long id:ids){ itemMapper.deleteByPrimaryKey(id); } } @Override public PageResult findPage(TbItem item, int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); TbItemExample example=new TbItemExample(); Criteria criteria = example.createCriteria(); if(item!=null){ if(item.getTitle()!=null && item.getTitle().length()>0){ criteria.andTitleLike("%"+item.getTitle()+"%"); } if(item.getSellPoint()!=null && item.getSellPoint().length()>0){ criteria.andSellPointLike("%"+item.getSellPoint()+"%"); } if(item.getBarcode()!=null && item.getBarcode().length()>0){ criteria.andBarcodeLike("%"+item.getBarcode()+"%"); } if(item.getImage()!=null && item.getImage().length()>0){ criteria.andImageLike("%"+item.getImage()+"%"); } if(item.getStatus()!=null && item.getStatus().length()>0){ criteria.andStatusLike("%"+item.getStatus()+"%"); } if(item.getItemSn()!=null && item.getItemSn().length()>0){ criteria.andItemSnLike("%"+item.getItemSn()+"%"); } if(item.getIsDefault()!=null && item.getIsDefault().length()>0){ criteria.andIsDefaultLike("%"+item.getIsDefault()+"%"); } if(item.getSellerId()!=null && item.getSellerId().length()>0){ criteria.andSellerIdLike("%"+item.getSellerId()+"%"); } if(item.getCartThumbnail()!=null && item.getCartThumbnail().length()>0){ criteria.andCartThumbnailLike("%"+item.getCartThumbnail()+"%"); } if(item.getCategory()!=null && item.getCategory().length()>0){ criteria.andCategoryLike("%"+item.getCategory()+"%"); } if(item.getBrand()!=null && item.getBrand().length()>0){ criteria.andBrandLike("%"+item.getBrand()+"%"); } if(item.getSpec()!=null && item.getSpec().length()>0){ criteria.andSpecLike("%"+item.getSpec()+"%"); } if(item.getSeller()!=null && item.getSeller().length()>0){ criteria.andSellerLike("%"+item.getSeller()+"%"); } } Page<TbItem> page= (Page<TbItem>)itemMapper.selectByExample(example); return new PageResult(page.getTotal(), page.getResult()); } }
5170e6b51b7f4a969078b3c5956ec2d504a3a254
0a532b9d7ebc356ab684a094b3cf840b6b6a17cd
/java-source/src/main/com/sun/org/apache/xerces/internal/impl/dtd/XMLSimpleType.java
3cc04d9fa8599520c03adf9ad999c498f8289cd0
[ "Apache-2.0" ]
permissive
XWxiaowei/JavaCode
ac70d87cdb0dfc6b7468acf46c84565f9d198e74
a7e7cd7a49c36db3ee479216728dd500eab9ebb2
refs/heads/master
2022-12-24T10:21:28.144227
2020-08-22T08:01:43
2020-08-22T08:01:43
98,070,624
10
4
Apache-2.0
2022-12-16T04:23:38
2017-07-23T02:51:51
Java
UTF-8
Java
false
false
6,982
java
/* * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package com.sun.org.apache.xerces.internal.impl.dtd; import com.sun.org.apache.xerces.internal.impl.dv.DatatypeValidator; /** */ public class XMLSimpleType { // // Constants // /** TYPE_CDATA */ public static final short TYPE_CDATA = 0; /** TYPE_ENTITY */ public static final short TYPE_ENTITY = 1; /** TYPE_ENUMERATION */ public static final short TYPE_ENUMERATION = 2; /** TYPE_ID */ public static final short TYPE_ID = 3; /** TYPE_IDREF */ public static final short TYPE_IDREF = 4; /** TYPE_NMTOKEN */ public static final short TYPE_NMTOKEN = 5; /** TYPE_NOTATION */ public static final short TYPE_NOTATION = 6; /** TYPE_NAMED */ public static final short TYPE_NAMED = 7; /** DEFAULT_TYPE_DEFAULT */ public static final short DEFAULT_TYPE_DEFAULT = 3; /** DEFAULT_TYPE_FIXED */ public static final short DEFAULT_TYPE_FIXED = 1; /** DEFAULT_TYPE_IMPLIED */ public static final short DEFAULT_TYPE_IMPLIED = 0; /** DEFAULT_TYPE_REQUIRED */ public static final short DEFAULT_TYPE_REQUIRED = 2; // // Data // /** type */ public short type; /** name */ public String name; /** enumeration */ public String[] enumeration; /** list */ public boolean list; /** defaultType */ public short defaultType; /** defaultValue */ public String defaultValue; /** non-normalized defaultValue */ public String nonNormalizedDefaultValue; /** datatypeValidator */ public DatatypeValidator datatypeValidator; // // Methods // /** * setValues * * @param type * @param name * @param enumeration * @param list * @param defaultType * @param defaultValue * @param nonNormalizedDefaultValue * @param datatypeValidator */ public void setValues(short type, String name, String[] enumeration, boolean list, short defaultType, String defaultValue, String nonNormalizedDefaultValue, DatatypeValidator datatypeValidator) { this.type = type; this.name = name; // REVISIT: Should this be a copy? -Ac if (enumeration != null && enumeration.length > 0) { this.enumeration = new String[enumeration.length]; System.arraycopy(enumeration, 0, this.enumeration, 0, this.enumeration.length); } else { this.enumeration = null; } this.list = list; this.defaultType = defaultType; this.defaultValue = defaultValue; this.nonNormalizedDefaultValue = nonNormalizedDefaultValue; this.datatypeValidator = datatypeValidator; } // setValues(short,String,String[],boolean,short,String,String,DatatypeValidator) /** Set values. */ public void setValues(XMLSimpleType simpleType) { type = simpleType.type; name = simpleType.name; // REVISIT: Should this be a copy? -Ac if (simpleType.enumeration != null && simpleType.enumeration.length > 0) { enumeration = new String[simpleType.enumeration.length]; System.arraycopy(simpleType.enumeration, 0, enumeration, 0, enumeration.length); } else { enumeration = null; } list = simpleType.list; defaultType = simpleType.defaultType; defaultValue = simpleType.defaultValue; nonNormalizedDefaultValue = simpleType.nonNormalizedDefaultValue; datatypeValidator = simpleType.datatypeValidator; } // setValues(XMLSimpleType) /** * clear */ public void clear() { this.type = -1; this.name = null; this.enumeration = null; this.list = false; this.defaultType = -1; this.defaultValue = null; this.nonNormalizedDefaultValue = null; this.datatypeValidator = null; } // clear } // class XMLSimpleType
583278ba8d9921ee23802ef3750a4f0d7dd67e55
180e78725121de49801e34de358c32cf7148b0a2
/dataset/protocol1/repairnator/learning/6608/Repository.java
c5cc678b3603a0b686e898029e892056ee3bf6b4
[]
no_license
ASSERT-KTH/synthetic-checkstyle-error-dataset
40e8d1e0a7ebe7f7711def96a390891a6922f7bd
40c057e1669584bfc6fecf789b5b2854660222f3
refs/heads/master
2023-03-18T12:50:55.410343
2019-01-25T09:54:39
2019-01-25T09:54:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,363
java
package fr.inria.spirals.repairnator.process.inspectors.properties.repository; public class Repository { private String name; private long githubId; private String url; private boolean isFork; private Original original; private boolean isPullRequest; private int pullRequestId; public Repository() { this.original = new Original(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getGithubId() { return githubId; } public void setGithubId(long githubId) { this.githubId = githubId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public boolean getIsFork() { return isFork; } public void setIsFork(boolean isFork) { this.isFork = isFork; } public Original getOriginal() { return original; } public boolean getIsPullRequest() { return isPullRequest; } public void setIsPullRequest(boolean isPullRequest) { this.isPullRequest = isPullRequest; } public int getPullRequestId() { return pullRequestId; } public void setPullRequestId(int pullRequestId) { this.pullRequestId = pullRequestId; } }
d9a22eb9dd567de617b3df289b78a0d6015bac84
5f789b8f26478f88b1452f17971b80324da1ad64
/src/main/java/com/study/spring/sample/factory/LoveServiceFactoryBean.java
403f1bc6b29f08e87785289a48682286846faa77
[]
no_license
hecj/spring-source-study
c29d5c4c399bed36d511dd012147f1054ddca932
17dd061ea62a5967a2929a92224774d9ecc4807f
refs/heads/master
2022-07-13T17:54:13.647534
2019-06-20T11:02:30
2019-06-20T11:02:30
192,904,283
0
0
null
2022-06-21T01:19:12
2019-06-20T11:02:12
Java
UTF-8
Java
false
false
509
java
package com.study.spring.sample.factory; import com.study.spring.service.LoveService; import com.study.spring.service.LoveServiceImpl; import org.springframework.beans.factory.FactoryBean; public class LoveServiceFactoryBean implements FactoryBean<LoveService> { @Override public LoveService getObject() throws Exception { return new LoveServiceImpl(); } @Override public Class<?> getObjectType() { return LoveService.class; } @Override public boolean isSingleton() { return false; } }
3ec475d742f987602d2cf9e4dfe19bd2979822d3
bd830599987abe58db2b63c3ec3d5212c4420f4c
/crm-eim/src/main/java/com/ywc/eim/service/impl/OrdersServiceImpl.java
d67744343d51c2b12fe0be42d7669ca6b63311c4
[]
no_license
13078263112/crm-parent
97e4077e30025d3f591e8e4ad96e669c1406afe2
9936c73e9ce842143ad9cd89c96660b4ddbd8c2a
refs/heads/master
2023-08-10T04:21:08.236683
2020-05-06T01:28:22
2020-05-06T01:28:22
251,350,828
0
0
null
2023-07-23T10:21:45
2020-03-30T15:40:59
HTML
UTF-8
Java
false
false
473
java
package com.ywc.eim.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ywc.crm.eim.entity.Orders; import com.ywc.crm.eim.service.OrdersService; import com.ywc.eim.mapper.OrdersMapper; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author 嘟嘟~ * @since 2020-03-30 */ @Service public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService { }
3d88a41b59a692e8b8229944455f8b69f765548a
f99f27be74a052b0a8cc25233544e2aa16f55809
/kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/challenges/Food2Door/OrderRetriever.java
89dcfdb9c25e6e645c38e991c836e47cd5077729
[]
no_license
TheEnAa/Dawid-Heyn-kodilla-java
8dbb5745878dc647c0d2deaf027b015d401c026d
c51d365419de8be36613eae2393f580145863458
refs/heads/master
2021-01-01T19:19:14.854573
2017-11-08T00:50:34
2017-11-08T00:50:34
98,567,283
0
0
null
null
null
null
UTF-8
Java
false
false
445
java
package com.kodilla.good.patterns.challenges.Food2Door; import java.time.LocalDateTime; public class OrderRetriever { public Order retrieve() { Product productOne = new Product("Carrot",1.01,true); double quantity = 2.0; Customer customerOne = new Customer("Jan","Jankowski"); LocalDateTime date = LocalDateTime.of(2017,9,7,16,20); return new Order(productOne,quantity,customerOne,date); } }
0f15fb78e016578fea877a778a2bc0c063749abc
c84088fed6a7b4f392810bb166e66dbfe3df4286
/kycrm/src/main/java/com/yongjun/tdms/presentation/webwork/action/PersonnelFiles/contractadministrator/EditContractAdministratorAction.java
c561d641910f80e3ab81f79a8c988efb6d493020
[]
no_license
1Will/Work1
4c419b9013d2989c4bbe6721c155de609e5ce9b5
16e707588da13e9dede5f7de97ca53e15a7d5a78
refs/heads/master
2020-05-22T16:52:56.501596
2018-03-20T01:21:01
2018-03-20T01:21:01
84,697,600
0
0
null
null
null
null
UTF-8
Java
false
false
11,430
java
/* */ package com.yongjun.tdms.presentation.webwork.action.PersonnelFiles.contractadministrator; /* */ /* */ import com.yongjun.pluto.exception.DaoException; /* */ import com.yongjun.pluto.model.codevalue.CodeValue; /* */ import com.yongjun.pluto.model.security.Department; /* */ import com.yongjun.pluto.service.codevalue.CodeValueManager; /* */ import com.yongjun.pluto.webwork.action.PrepareAction; /* */ import com.yongjun.tdms.model.base.duty.Duty; /* */ import com.yongjun.tdms.model.base.jobs.Jobs; /* */ import com.yongjun.tdms.model.personnelFiles.PersonnelFiles; /* */ import com.yongjun.tdms.model.personnelFiles.contractadministrator.ContractAdministrator; /* */ import com.yongjun.tdms.service.base.duty.DutyManager; /* */ import com.yongjun.tdms.service.base.institution.InstitutionManager; /* */ import com.yongjun.tdms.service.base.jobs.JobsManager; /* */ import com.yongjun.tdms.service.base.org.DepartmentManager; /* */ import com.yongjun.tdms.service.personnelFiles.contractadministrator.ContractAdministratorManager; /* */ import com.yongjun.tdms.service.personnelFiles.personnel.PersonnelFilesManager; /* */ import java.io.PrintStream; /* */ import java.util.ArrayList; /* */ import java.util.List; /* */ import javax.servlet.http.HttpServletRequest; /* */ import org.apache.commons.lang.StringUtils; /* */ /* */ public class EditContractAdministratorAction extends PrepareAction /* */ { /* */ private static final long serialVersionUID = 8833243999062386287L; /* */ private final DepartmentManager departmentManager; /* */ private final DutyManager dutyManager; /* */ private final CodeValueManager codeValueManager; /* */ private final ContractAdministratorManager contractAdministratorManager; /* */ private final PersonnelFilesManager personnelFilesManager; /* */ private final JobsManager jobsManager; /* */ private final InstitutionManager institutionManager; /* */ private ContractAdministrator contractAdministrator; /* */ /* */ public EditContractAdministratorAction(DepartmentManager departmentManager, DutyManager dutyManager, CodeValueManager codeValueManager, ContractAdministratorManager contractAdministratorManager, PersonnelFilesManager personnelFilesManager, JobsManager jobsManager, InstitutionManager institutionManager) /* */ { /* 83 */ this.departmentManager = departmentManager; /* 84 */ this.dutyManager = dutyManager; /* 85 */ this.codeValueManager = codeValueManager; /* 86 */ this.contractAdministratorManager = contractAdministratorManager; /* 87 */ this.personnelFilesManager = personnelFilesManager; /* 88 */ this.jobsManager = jobsManager; /* 89 */ this.institutionManager = institutionManager; /* */ } /* */ /* */ public void prepare() /* */ throws Exception /* */ { /* 97 */ if (hasId("contractAdministrator.id")) { /* 98 */ this.contractAdministrator = this.contractAdministratorManager.loadContractAdministrator(getId("contractAdministrator.id")); /* */ } /* */ else /* 101 */ this.contractAdministrator = new ContractAdministrator(); /* */ } /* */ /* */ public String save() /* */ throws Exception /* */ { /* 111 */ System.out.println(this.contractAdministrator.getPayAccount()); /* 112 */ boolean isNew = this.contractAdministrator.isNew(); /* */ /* 114 */ if (!StringUtils.isEmpty(this.request.getParameter("personnelName.id"))) { /* 115 */ PersonnelFiles emplyee = this.personnelFilesManager.loadPersonnel(Long.valueOf(this.request.getParameter("personnelName.id"))); /* */ /* 117 */ if (null != emplyee) { /* 118 */ this.contractAdministrator.setPersonnelName(emplyee); /* */ } /* */ } /* */ /* 122 */ if (!StringUtils.isEmpty(this.request.getParameter("dept.id"))) { /* 123 */ this.contractAdministrator.setDept(this.departmentManager.loadDepartment(Long.valueOf(this.request.getParameter("dept.id")))); /* */ } /* */ /* 133 */ if (!StringUtils.isEmpty(this.request.getParameter("duty.id"))) { /* 134 */ this.contractAdministrator.setDuty(this.dutyManager.loadDuty(Long.valueOf(this.request.getParameter("duty.id")))); /* */ } /* */ /* 149 */ if (!StringUtils.isEmpty(this.request.getParameter("contractType.id"))) { /* 150 */ this.contractAdministrator.setContractType(this.codeValueManager.loadCodeValue(Long.valueOf(this.request.getParameter("contractType.id")))); /* */ } /* */ /* 165 */ if (!StringUtils.isEmpty(this.request.getParameter("principalName.id"))) { /* 166 */ this.contractAdministrator.setPrincipalName(this.personnelFilesManager.loadPersonnel(Long.valueOf(this.request.getParameter("principalName.id")))); /* */ } /* */ /* 171 */ if (!StringUtils.isEmpty(this.request.getParameter("institution.id"))) { /* 172 */ this.contractAdministrator.setInstitustion(this.institutionManager.loadInstitution(Long.valueOf(this.request.getParameter("institution.id")))); /* */ } /* */ /* 175 */ if (isNew) { /* 176 */ /* String newCode = autoCompleteCode(); 177 this.contractAdministrator.setContractCode(newCode);*/ /* 178 */ this.contractAdministratorManager.storeContractAdministrator(this.contractAdministrator); /* 179 */ addActionMessage(getText("contractAdministrator.save.success")); /* 180 */ return "new"; /* */ } /* 182 */ this.contractAdministratorManager.storeContractAdministrator(this.contractAdministrator); /* 183 */ addActionMessage(getText("contractAdministrator.edit.success")); /* 184 */ return "success"; /* */ } /* */ /* */ public List<Department> getAllDepts() /* */ { /* 193 */ List list = this.departmentManager.loadAllDepartments(); /* 194 */ return list; /* */ } /* */ /* */ public List<Duty> getAllDutys() /* */ { /* 201 */ List list = this.dutyManager.loadAllDuty(); /* 202 */ return list; /* */ } /* */ /* */ public List<Jobs> getAllJobs() /* */ { /* 209 */ List list = this.jobsManager.loadAllJobs(); /* 210 */ return list; /* */ } /* */ /* */ public List<CodeValue> getAllCrfts() /* */ { /* 217 */ List codes = null; /* */ try { /* 219 */ codes = new ArrayList(); /* 220 */ List one = this.codeValueManager.loadByKey("code", "055551"); /* */ /* 222 */ if ((null != one) && (one.size() > 0)) /* */ { /* 224 */ List list = this.codeValueManager.loadByKey("parentCV.id", ((CodeValue)one.get(0)).getId()); /* */ /* 226 */ if ((null != list) && (list.size() > 0)) { /* 227 */ codes.addAll(list); /* */ } /* */ } /* 230 */ return codes; /* */ } catch (DaoException e) { /* 232 */ e.printStackTrace(); /* */ } /* 234 */ return codes; /* */ } /* */ /* */ public List<CodeValue> getAllLevels() /* */ { /* 241 */ List codes = null; /* */ try { /* 243 */ codes = new ArrayList(); /* 244 */ List one = this.codeValueManager.loadByKey("code", "055552"); /* */ /* 246 */ if ((null != one) && (one.size() > 0)) /* */ { /* 248 */ List list = this.codeValueManager.loadByKey("parentCV.id", ((CodeValue)one.get(0)).getId()); /* */ /* 250 */ if ((null != list) && (list.size() > 0)) { /* 251 */ codes.addAll(list); /* */ } /* */ } /* 254 */ return codes; /* */ } catch (DaoException e) { /* 256 */ e.printStackTrace(); /* */ } /* 258 */ return codes; /* */ } /* */ /* */ public List<CodeValue> getAllContractType() /* */ { /* 265 */ List codes = null; /* */ try { /* 267 */ codes = new ArrayList(); /* 268 */ List one = this.codeValueManager.loadByKey("code", "055555"); /* */ /* 270 */ if ((null != one) && (one.size() > 0)) /* */ { /* 272 */ List list = this.codeValueManager.loadByKey("parentCV.id", ((CodeValue)one.get(0)).getId()); /* */ /* 274 */ if ((null != list) && (list.size() > 0)) { /* 275 */ codes.addAll(list); /* */ } /* */ } /* 278 */ return codes; /* */ } catch (DaoException e) { /* 280 */ e.printStackTrace(); /* */ } /* 282 */ return codes; /* */ } /* */ /* */ public List<CodeValue> getAllVntu() /* */ { /* 289 */ List codes = null; /* */ try { /* 291 */ codes = new ArrayList(); /* 292 */ List one = this.codeValueManager.loadByKey("code", "055553"); /* */ /* 294 */ if ((null != one) && (one.size() > 0)) /* */ { /* 296 */ List list = this.codeValueManager.loadByKey("parentCV.id", ((CodeValue)one.get(0)).getId()); /* */ /* 298 */ if ((null != list) && (list.size() > 0)) { /* 299 */ codes.addAll(list); /* */ } /* */ } /* 302 */ return codes; /* */ } catch (DaoException e) { /* 304 */ e.printStackTrace(); /* */ } /* 306 */ return codes; /* */ } /* */ /* */ public List<CodeValue> getAllBecomes() /* */ { /* 313 */ List codes = null; /* */ try { /* 315 */ codes = new ArrayList(); /* 316 */ List one = this.codeValueManager.loadByKey("code", "055554"); /* */ /* 318 */ if ((null != one) && (one.size() > 0)) /* */ { /* 320 */ List list = this.codeValueManager.loadByKey("parentCV.id", ((CodeValue)one.get(0)).getId()); /* */ /* 322 */ if ((null != list) && (list.size() > 0)) { /* 323 */ codes.addAll(list); /* */ } /* */ } /* 326 */ return codes; /* */ } catch (DaoException e) { /* 328 */ e.printStackTrace(); /* */ } /* 330 */ return codes; /* */ } /* */ /* */ public String autoCompleteCode() /* */ { /* 338 */ String maxCode = this.contractAdministratorManager.getMaxPFCode("CAM"); /* 339 */ if (null != maxCode) { /* 340 */ int num = Integer.parseInt(maxCode) + 1; /* 341 */ if (num < 10) /* 342 */ return "CAM-00" + num; /* 343 */ if (num < 100) { /* 344 */ return "CAM-0" + num; /* */ } /* 346 */ return "CAM-" + num; /* */ } /* */ /* 350 */ return "CAM-001"; /* */ } /* */ /* */ public ContractAdministrator getContractAdministrator() /* */ { /* 359 */ return this.contractAdministrator; /* */ } /* */ /* */ public void setContractAdministrator(ContractAdministrator contractAdministrator) /* */ { /* 368 */ this.contractAdministrator = contractAdministrator; /* */ } /* */ /* */ public List getInstitutions() /* */ { /* 376 */ return this.institutionManager.getInstitutions(); /* */ } /* */ } /* Location: E:\crm2010\110\crm2009\WEB-INF\classes\ * Qualified Name: com.yongjun.tdms.presentation.webwork.action.PersonnelFiles.contractadministrator.EditContractAdministratorAction * JD-Core Version: 0.6.2 */
ffa4c65f4161bc736af3de3f7a5fe908a0a903d1
88d3adf0d054afabe2bc16dc27d9e73adf2e7c61
/3rdparty/httpcore/src/test/java/org/apache/http/mockup/HttpEntityMockup.java
8182b9a1d5725700a09df8c872d3aef290865e38
[ "Apache-2.0" ]
permissive
nntoan/vietspider
5afc8d53653a1bb3fc2e20fb12a918ecf31fdcdc
79d563afea3abd93f7fdff5bcecb5bac2162d622
refs/heads/master
2021-01-10T06:23:20.588974
2020-05-06T09:44:32
2020-05-06T09:44:32
54,641,132
0
2
null
2020-05-06T07:52:29
2016-03-24T12:45:02
Java
UTF-8
Java
false
false
1,971
java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.mockup; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.entity.AbstractHttpEntity; /** * {@link AbstractHttpEntity} mockup implementation. * */ public class HttpEntityMockup extends AbstractHttpEntity { private boolean stream; public InputStream getContent() throws IOException, IllegalStateException { return null; } public long getContentLength() { return 0; } public boolean isRepeatable() { return false; } public void setStreaming(final boolean b) { this.stream = b; } public boolean isStreaming() { return this.stream; } public void writeTo(OutputStream outstream) throws IOException { } }
a1bd840f8b5a707b10c685409bfefdc8a21fcdaf
7898a903efc51797da7ca8430dba65a20e5e708f
/impl/src/main/java/com/sevenbridges/apiclient/impl/api/ClientApiKeyBuilder.java
9712ec59036f2dbd956cc42fa4066e0db961488a
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
sbg/sevenbridges-java
011786c770f647ef3793550e0cb058096a7d8389
76cd7ea605b0a4a2e0e9c000e9f48ec5eb0be199
refs/heads/develop
2020-12-02T19:24:38.314712
2017-07-16T01:25:04
2017-07-16T01:25:04
96,336,229
2
2
Apache-2.0
2018-05-22T12:57:44
2017-07-05T15:49:53
Java
UTF-8
Java
false
false
6,361
java
/* * Copyright 2017 Seven Bridges Genomics, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sevenbridges.apiclient.impl.api; import com.sevenbridges.apiclient.client.ApiKey; import com.sevenbridges.apiclient.client.ApiKeyBuilder; import com.sevenbridges.apiclient.impl.io.DefaultResourceFactory; import com.sevenbridges.apiclient.impl.io.ResourceFactory; import com.sevenbridges.apiclient.lang.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Properties; public class ClientApiKeyBuilder implements ApiKeyBuilder { private static final Logger log = LoggerFactory.getLogger(ClientApiKeyBuilder.class); private String apiKeyId; private String apiKeySecret; private String apiKeyFileLocation; private InputStream apiKeyInputStream; private Reader apiKeyReader; private Properties apiKeyProperties; private String apiKeyIdPropertyName = DEFAULT_ID_PROPERTY_NAME; private String apiKeySecretPropertyName = DEFAULT_SECRET_PROPERTY_NAME; private ResourceFactory resourceFactory = new DefaultResourceFactory(); @Override public ApiKeyBuilder setId(String id) { this.apiKeyId = id; return this; } @Override public ApiKeyBuilder setSecret(String secret) { this.apiKeySecret = secret; return this; } @Override public ApiKeyBuilder setProperties(Properties properties) { this.apiKeyProperties = properties; return this; } @Override public ApiKeyBuilder setReader(Reader reader) { this.apiKeyReader = reader; return this; } @Override public ApiKeyBuilder setInputStream(InputStream is) { this.apiKeyInputStream = is; return this; } @Override public ApiKeyBuilder setFileLocation(String location) { this.apiKeyFileLocation = location; return this; } @Override public ApiKey build() { String id = null; String secret = null; Properties props; //1. Try any configured properties files: if (Strings.hasText(this.apiKeyFileLocation)) { try { Reader reader = createFileReader(this.apiKeyFileLocation); props = toProperties(reader); } catch (IOException e) { String msg = "Unable to read properties from specified apiKeyFileLocation [" + this.apiKeyFileLocation + "]."; throw new IllegalArgumentException(msg, e); } id = getPropertyValue(props, this.apiKeyIdPropertyName, id); secret = getPropertyValue(props, this.apiKeySecretPropertyName, secret); } //2. Try any configured input stream if (this.apiKeyInputStream != null) { try { Reader reader = toReader(this.apiKeyInputStream); props = toProperties(reader); } catch (IOException e) { throw new IllegalArgumentException("Unable to read properties from specified apiKeyInputStream.", e); } id = getPropertyValue(props, this.apiKeyIdPropertyName, id); secret = getPropertyValue(props, this.apiKeySecretPropertyName, secret); } //3. Try any configured reader if (this.apiKeyReader != null) { try { props = toProperties(this.apiKeyReader); } catch (IOException e) { throw new IllegalArgumentException("Unable to read properties from specified apiKeyReader.", e); } id = getPropertyValue(props, this.apiKeyIdPropertyName, id); secret = getPropertyValue(props, this.apiKeySecretPropertyName, secret); } //4. Try any configured properties if (this.apiKeyProperties != null && !this.apiKeyProperties.isEmpty()) { id = getPropertyValue(this.apiKeyProperties, this.apiKeyIdPropertyName, id); secret = getPropertyValue(this.apiKeyProperties, this.apiKeySecretPropertyName, secret); } //5. Explicitly-configured values always take precedence: id = valueOf(this.apiKeyId, id); secret = valueOf(this.apiKeySecret, secret); if (!Strings.hasText(secret)) { String msg = "Unable to find an API Key 'secret' from explicit configuration " + "Please ensure you manually configure an API Key Secret or ensure that it exists in one of " + "these fallback locations."; throw new IllegalStateException(msg); } if (!Strings.hasText(id)) { return createTokenApiKey(secret); } return createApiKey(id, secret); } protected ApiKey createApiKey(String id, String secret) { return new ClientApiKey(id, secret); } protected ApiKey createTokenApiKey(String secret) { return new ClientTokenApiKey(secret); } private static String getPropertyValue(Properties properties, String propName) { String value = properties.getProperty(propName); if (value != null) { value = value.trim(); if ("".equals(value)) { value = null; } } return value; } private static String valueOf(String discoveredValue, String defaultValue) { if (!Strings.hasText(discoveredValue)) { return defaultValue; } return discoveredValue; } private static String getPropertyValue(Properties properties, String propName, String defaultValue) { String value = getPropertyValue(properties, propName); return valueOf(value, defaultValue); } protected Reader createFileReader(String apiKeyFileLocation) throws IOException { InputStream is = this.resourceFactory.createResource(apiKeyFileLocation).getInputStream(); return toReader(is); } private static Reader toReader(InputStream is) throws IOException { return new InputStreamReader(is, "ISO-8859-1"); } private static Properties toProperties(Reader reader) throws IOException { Properties properties = new Properties(); properties.load(reader); return properties; } }
38401a016708aecb4df44f9d17f64ef9d9ae32ad
d6ee86155d211e3b349ede61366d9a18ba2bd029
/src/exercise9/RegularPolygon.java
a056121d7519edd49b919087e5fcf1c86cd71218
[]
no_license
d9nchik/Section9
afb1b0ddeff73c9df7beffebb0a49ab430056123
cd72f3d99133d86c0f9b5b29da06919fdce727d2
refs/heads/master
2022-04-15T19:28:53.067757
2020-03-04T17:23:09
2020-03-04T17:23:09
244,471,357
0
0
null
null
null
null
UTF-8
Java
false
false
1,064
java
package exercise9; public class RegularPolygon { private int n = 3; private double side = 1; private double x = 0; private double y = 0; public RegularPolygon() { } public RegularPolygon(int n, int side) { this.n = n; this.side = side; } public RegularPolygon(int n, int side, double x, double y) { this.n = n; this.side = side; this.x = x; this.y = y; } public double getSide() { return side; } public double getX() { return x; } public double getY() { return y; } public int getN() { return n; } public void setN(int n) { this.n = n; } public void setSide(double side) { this.side = side; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public double getPerimeter(){ return n*side; } public double getArea(){ return n*side*side/(4*Math.tan(Math.PI/n)); } }
bb4da17c06e9aaeb83432d415f5f60d57666e143
c5b5461b51bd56b688a6880f4aeffad45c80d044
/app/src/main/java/com/christianlopez/hwk_4_bank_ver_2/BankAccount.java
71312bbb117e69a40c89954a5bb0906911d84988
[]
no_license
CodingClinician/HWK_4_Bank_Ver_2
4e69395051856056c0d7a8ba1284ad2d433d81b2
da1456c17149cbfd6b346deb9bd5d87c0cf119da
refs/heads/master
2020-11-25T14:11:41.560054
2019-12-17T20:31:43
2019-12-17T20:31:43
228,708,001
0
0
null
null
null
null
UTF-8
Java
false
false
898
java
package com.christianlopez.hwk_4_bank_ver_2; /** * Created by toby6969 on 4/3/2018. */ public class BankAccount { private String acctName =""; private String acctBalance = ""; public BankAccount() { // default constructor } public BankAccount(String acctName, String acctBalance) { // parametized constructor this.acctName = acctName; this.acctBalance = acctBalance; } // account name public String getAcctName() { return acctName; } public void setAcctName(String acctName) { this.acctName = acctName; } // balance public String getAcctBalance() { return acctBalance; } public void setAcctBalance(String bal) { this.acctBalance = acctBalance; } // deposit @Override public String toString() { return acctName; } }
51c26ab91b501d6e9efa8b09dc9bceda80fc8419
498dd2daff74247c83a698135e4fe728de93585a
/clients/google-api-services-cloudasset/v1/1.29.2/com/google/api/services/cloudasset/v1/model/GoogleCloudOrgpolicyV1Policy.java
4aef95e9bec8bbd2e8068cc1d1790f9044f51351
[ "Apache-2.0" ]
permissive
googleapis/google-api-java-client-services
0e2d474988d9b692c2404d444c248ea57b1f453d
eb359dd2ad555431c5bc7deaeafca11af08eee43
refs/heads/main
2023-08-23T00:17:30.601626
2023-08-20T02:16:12
2023-08-20T02:16:12
147,399,159
545
390
Apache-2.0
2023-09-14T02:14:14
2018-09-04T19:11:33
null
UTF-8
Java
false
false
11,254
java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudasset.v1.model; /** * Defines a Cloud Organization `Policy` which is used to specify `Constraints` for configurations * of Cloud Platform resources. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Asset API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudOrgpolicyV1Policy extends com.google.api.client.json.GenericJson { /** * For boolean `Constraints`, whether to enforce the `Constraint` or not. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudOrgpolicyV1BooleanPolicy booleanPolicy; /** * The name of the `Constraint` the `Policy` is configuring, for example, * `constraints/serviceuser.services`. * * Immutable after creation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String constraint; /** * An opaque tag indicating the current version of the `Policy`, used for concurrency control. * * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write * loop. * * When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be unset. * * When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was returned * from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency control. Not * setting the `etag`in a `SetOrgPolicy` request will result in an unconditional write of the * `Policy`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String etag; /** * List of values either allowed or disallowed. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudOrgpolicyV1ListPolicy listPolicy; /** * Restores the default behavior of the constraint; independent of `Constraint` type. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudOrgpolicyV1RestoreDefault restoreDefault; /** * The time stamp the `Policy` was previously updated. This is set by the server, not specified by * the caller, and represents the last time a call to `SetOrgPolicy` was made for that `Policy`. * Any value set by the client will be ignored. * The value may be {@code null}. */ @com.google.api.client.util.Key private String updateTime; /** * Version of the `Policy`. Default version is 0; * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer version; /** * For boolean `Constraints`, whether to enforce the `Constraint` or not. * @return value or {@code null} for none */ public GoogleCloudOrgpolicyV1BooleanPolicy getBooleanPolicy() { return booleanPolicy; } /** * For boolean `Constraints`, whether to enforce the `Constraint` or not. * @param booleanPolicy booleanPolicy or {@code null} for none */ public GoogleCloudOrgpolicyV1Policy setBooleanPolicy(GoogleCloudOrgpolicyV1BooleanPolicy booleanPolicy) { this.booleanPolicy = booleanPolicy; return this; } /** * The name of the `Constraint` the `Policy` is configuring, for example, * `constraints/serviceuser.services`. * * Immutable after creation. * @return value or {@code null} for none */ public java.lang.String getConstraint() { return constraint; } /** * The name of the `Constraint` the `Policy` is configuring, for example, * `constraints/serviceuser.services`. * * Immutable after creation. * @param constraint constraint or {@code null} for none */ public GoogleCloudOrgpolicyV1Policy setConstraint(java.lang.String constraint) { this.constraint = constraint; return this; } /** * An opaque tag indicating the current version of the `Policy`, used for concurrency control. * * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write * loop. * * When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be unset. * * When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was returned * from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency control. Not * setting the `etag`in a `SetOrgPolicy` request will result in an unconditional write of the * `Policy`. * @see #decodeEtag() * @return value or {@code null} for none */ public java.lang.String getEtag() { return etag; } /** * An opaque tag indicating the current version of the `Policy`, used for concurrency control. * * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write * loop. * * When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be unset. * * When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was returned * from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency control. Not * setting the `etag`in a `SetOrgPolicy` request will result in an unconditional write of the * `Policy`. * @see #getEtag() * @return Base64 decoded value or {@code null} for none * * @since 1.14 */ public byte[] decodeEtag() { return com.google.api.client.util.Base64.decodeBase64(etag); } /** * An opaque tag indicating the current version of the `Policy`, used for concurrency control. * * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write * loop. * * When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be unset. * * When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was returned * from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency control. Not * setting the `etag`in a `SetOrgPolicy` request will result in an unconditional write of the * `Policy`. * @see #encodeEtag() * @param etag etag or {@code null} for none */ public GoogleCloudOrgpolicyV1Policy setEtag(java.lang.String etag) { this.etag = etag; return this; } /** * An opaque tag indicating the current version of the `Policy`, used for concurrency control. * * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write * loop. * * When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be unset. * * When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was returned * from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency control. Not * setting the `etag`in a `SetOrgPolicy` request will result in an unconditional write of the * `Policy`. * @see #setEtag() * * <p> * The value is encoded Base64 or {@code null} for none. * </p> * * @since 1.14 */ public GoogleCloudOrgpolicyV1Policy encodeEtag(byte[] etag) { this.etag = com.google.api.client.util.Base64.encodeBase64URLSafeString(etag); return this; } /** * List of values either allowed or disallowed. * @return value or {@code null} for none */ public GoogleCloudOrgpolicyV1ListPolicy getListPolicy() { return listPolicy; } /** * List of values either allowed or disallowed. * @param listPolicy listPolicy or {@code null} for none */ public GoogleCloudOrgpolicyV1Policy setListPolicy(GoogleCloudOrgpolicyV1ListPolicy listPolicy) { this.listPolicy = listPolicy; return this; } /** * Restores the default behavior of the constraint; independent of `Constraint` type. * @return value or {@code null} for none */ public GoogleCloudOrgpolicyV1RestoreDefault getRestoreDefault() { return restoreDefault; } /** * Restores the default behavior of the constraint; independent of `Constraint` type. * @param restoreDefault restoreDefault or {@code null} for none */ public GoogleCloudOrgpolicyV1Policy setRestoreDefault(GoogleCloudOrgpolicyV1RestoreDefault restoreDefault) { this.restoreDefault = restoreDefault; return this; } /** * The time stamp the `Policy` was previously updated. This is set by the server, not specified by * the caller, and represents the last time a call to `SetOrgPolicy` was made for that `Policy`. * Any value set by the client will be ignored. * @return value or {@code null} for none */ public String getUpdateTime() { return updateTime; } /** * The time stamp the `Policy` was previously updated. This is set by the server, not specified by * the caller, and represents the last time a call to `SetOrgPolicy` was made for that `Policy`. * Any value set by the client will be ignored. * @param updateTime updateTime or {@code null} for none */ public GoogleCloudOrgpolicyV1Policy setUpdateTime(String updateTime) { this.updateTime = updateTime; return this; } /** * Version of the `Policy`. Default version is 0; * @return value or {@code null} for none */ public java.lang.Integer getVersion() { return version; } /** * Version of the `Policy`. Default version is 0; * @param version version or {@code null} for none */ public GoogleCloudOrgpolicyV1Policy setVersion(java.lang.Integer version) { this.version = version; return this; } @Override public GoogleCloudOrgpolicyV1Policy set(String fieldName, Object value) { return (GoogleCloudOrgpolicyV1Policy) super.set(fieldName, value); } @Override public GoogleCloudOrgpolicyV1Policy clone() { return (GoogleCloudOrgpolicyV1Policy) super.clone(); } }
5c70c3c38d318616574f8d1bf2dea755a36cf637
63672504035ac3c9984950b4e8a9acd813783922
/MapReduce/java/mapreduce/lib/partition/TotalOrderPartitioner.java
ccc20f06c4571ba42620d59fb2330cac7f9f5f66
[]
no_license
ameet20/MapReduce
aa68b12fba4483216364de24bf16517cf6c403c0
3553bfd965f51668dbeeb3d71efa4f5f21887c8b
refs/heads/master
2021-07-20T21:09:19.852918
2021-07-09T11:31:47
2021-07-09T11:31:47
162,818,675
1
2
null
null
null
null
UTF-8
Java
false
false
14,212
java
package org.apache.hadoop.mapreduce.lib.partition; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BinaryComparable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Partitioner; import org.apache.hadoop.util.ReflectionUtils; /** * Partitioner effecting a total order by reading split points from * an externally generated source. */ @InterfaceAudience.Public @InterfaceStability.Stable public class TotalOrderPartitioner<K extends WritableComparable<?>,V> extends Partitioner<K,V> implements Configurable { private Node partitions; public static final String DEFAULT_PATH = "_partition.lst"; public static final String PARTITIONER_PATH = "mapreduce.totalorderpartitioner.path"; public static final String MAX_TRIE_DEPTH = "mapreduce.totalorderpartitioner.trie.maxdepth"; public static final String NATURAL_ORDER = "mapreduce.totalorderpartitioner.naturalorder"; Configuration conf; public TotalOrderPartitioner() { } /** * Read in the partition file and build indexing data structures. * If the keytype is {@link org.apache.hadoop.io.BinaryComparable} and * <tt>total.order.partitioner.natural.order</tt> is not false, a trie * of the first <tt>total.order.partitioner.max.trie.depth</tt>(2) + 1 bytes * will be built. Otherwise, keys will be located using a binary search of * the partition keyset using the {@link org.apache.hadoop.io.RawComparator} * defined for this job. The input file must be sorted with the same * comparator and contain {@link Job#getNumReduceTasks()} - 1 keys. */ @SuppressWarnings("unchecked") // keytype from conf not static public void setConf(Configuration conf) { try { this.conf = conf; String parts = getPartitionFile(conf); final Path partFile = new Path(parts); final FileSystem fs = (DEFAULT_PATH.equals(parts)) ? FileSystem.getLocal(conf) // assume in DistributedCache : partFile.getFileSystem(conf); Job job = new Job(conf); Class<K> keyClass = (Class<K>)job.getMapOutputKeyClass(); K[] splitPoints = readPartitions(fs, partFile, keyClass, conf); if (splitPoints.length != job.getNumReduceTasks() - 1) { throw new IOException("Wrong number of partitions in keyset"); } RawComparator<K> comparator = (RawComparator<K>) job.getSortComparator(); for (int i = 0; i < splitPoints.length - 1; ++i) { if (comparator.compare(splitPoints[i], splitPoints[i+1]) >= 0) { throw new IOException("Split points are out of order"); } } boolean natOrder = conf.getBoolean(NATURAL_ORDER, true); if (natOrder && BinaryComparable.class.isAssignableFrom(keyClass)) { partitions = buildTrie((BinaryComparable[])splitPoints, 0, splitPoints.length, new byte[0], // Now that blocks of identical splitless trie nodes are // represented reentrantly, and we develop a leaf for any trie // node with only one split point, the only reason for a depth // limit is to refute stack overflow or bloat in the pathological // case where the split points are long and mostly look like bytes // iii...iixii...iii . Therefore, we make the default depth // limit large but not huge. conf.getInt(MAX_TRIE_DEPTH, 200)); } else { partitions = new BinarySearchNode(splitPoints, comparator); } } catch (IOException e) { throw new IllegalArgumentException("Can't read partitions file", e); } } public Configuration getConf() { return conf; } // by construction, we know if our keytype @SuppressWarnings("unchecked") // is memcmp-able and uses the trie public int getPartition(K key, V value, int numPartitions) { return partitions.findPartition(key); } /** * Set the path to the SequenceFile storing the sorted partition keyset. * It must be the case that for <tt>R</tt> reduces, there are <tt>R-1</tt> * keys in the SequenceFile. */ public static void setPartitionFile(Configuration conf, Path p) { conf.set(PARTITIONER_PATH, p.toString()); } /** * Get the path to the SequenceFile storing the sorted partition keyset. * @see #setPartitionFile(Configuration, Path) */ public static String getPartitionFile(Configuration conf) { return conf.get(PARTITIONER_PATH, DEFAULT_PATH); } /** * Interface to the partitioner to locate a key in the partition keyset. */ interface Node<T> { /** * Locate partition in keyset K, st [Ki..Ki+1) defines a partition, * with implicit K0 = -inf, Kn = +inf, and |K| = #partitions - 1. */ int findPartition(T key); } /** * Base class for trie nodes. If the keytype is memcomp-able, this builds * tries of the first <tt>total.order.partitioner.max.trie.depth</tt> * bytes. */ static abstract class TrieNode implements Node<BinaryComparable> { private final int level; TrieNode(int level) { this.level = level; } int getLevel() { return level; } } /** * For types that are not {@link org.apache.hadoop.io.BinaryComparable} or * where disabled by <tt>total.order.partitioner.natural.order</tt>, * search the partition keyset with a binary search. */ class BinarySearchNode implements Node<K> { private final K[] splitPoints; private final RawComparator<K> comparator; BinarySearchNode(K[] splitPoints, RawComparator<K> comparator) { this.splitPoints = splitPoints; this.comparator = comparator; } public int findPartition(K key) { final int pos = Arrays.binarySearch(splitPoints, key, comparator) + 1; return (pos < 0) ? -pos : pos; } } /** * An inner trie node that contains 256 children based on the next * character. */ class InnerTrieNode extends TrieNode { private TrieNode[] child = new TrieNode[256]; InnerTrieNode(int level) { super(level); } public int findPartition(BinaryComparable key) { int level = getLevel(); if (key.getLength() <= level) { return child[0].findPartition(key); } return child[0xFF & key.getBytes()[level]].findPartition(key); } } /** * @param level the tree depth at this node * @param splitPoints the full split point vector, which holds * the split point or points this leaf node * should contain * @param lower first INcluded element of splitPoints * @param upper first EXcluded element of splitPoints * @return a leaf node. They come in three kinds: no split points * [and the findParttion returns a canned index], one split * point [and we compare with a single comparand], or more * than one [and we do a binary search]. The last case is * rare. */ private TrieNode LeafTrieNodeFactory (int level, BinaryComparable[] splitPoints, int lower, int upper) { switch (upper - lower) { case 0: return new UnsplitTrieNode(level, lower); case 1: return new SinglySplitTrieNode(level, splitPoints, lower); default: return new LeafTrieNode(level, splitPoints, lower, upper); } } /** * A leaf trie node that scans for the key between lower..upper. * * We don't generate many of these now, since we usually continue trie-ing * when more than one split point remains at this level. and we make different * objects for nodes with 0 or 1 split point. */ private class LeafTrieNode extends TrieNode { final int lower; final int upper; final BinaryComparable[] splitPoints; LeafTrieNode(int level, BinaryComparable[] splitPoints, int lower, int upper) { super(level); this.lower = lower; this.upper = upper; this.splitPoints = splitPoints; } public int findPartition(BinaryComparable key) { final int pos = Arrays.binarySearch(splitPoints, lower, upper, key) + 1; return (pos < 0) ? -pos : pos; } } private class UnsplitTrieNode extends TrieNode { final int result; UnsplitTrieNode(int level, int value) { super(level); this.result = value; } public int findPartition(BinaryComparable key) { return result; } } private class SinglySplitTrieNode extends TrieNode { final int lower; final BinaryComparable mySplitPoint; SinglySplitTrieNode(int level, BinaryComparable[] splitPoints, int lower) { super(level); this.lower = lower; this.mySplitPoint = splitPoints[lower]; } public int findPartition(BinaryComparable key) { return lower + (key.compareTo(mySplitPoint) < 0 ? 0 : 1); } } /** * Read the cut points from the given IFile. * @param fs The file system * @param p The path to read * @param keyClass The map output key class * @param job The job config * @throws IOException */ // matching key types enforced by passing in @SuppressWarnings("unchecked") // map output key class private K[] readPartitions(FileSystem fs, Path p, Class<K> keyClass, Configuration conf) throws IOException { SequenceFile.Reader reader = new SequenceFile.Reader(fs, p, conf); ArrayList<K> parts = new ArrayList<K>(); K key = ReflectionUtils.newInstance(keyClass, conf); NullWritable value = NullWritable.get(); while (reader.next(key, value)) { parts.add(key); key = ReflectionUtils.newInstance(keyClass, conf); } reader.close(); return parts.toArray((K[])Array.newInstance(keyClass, parts.size())); } /** * * This object contains a TrieNodeRef if there is such a thing that * can be repeated. Two adjacent trie node slots that contain no * split points can be filled with the same trie node, even if they * are not on the same level. See buildTreeRec, below. * */ private class CarriedTrieNodeRef { TrieNode content; CarriedTrieNodeRef() { content = null; } } /** * Given a sorted set of cut points, build a trie that will find the correct * partition quickly. * @param splits the list of cut points * @param lower the lower bound of partitions 0..numPartitions-1 * @param upper the upper bound of partitions 0..numPartitions-1 * @param prefix the prefix that we have already checked against * @param maxDepth the maximum depth we will build a trie for * @return the trie node that will divide the splits correctly */ private TrieNode buildTrie(BinaryComparable[] splits, int lower, int upper, byte[] prefix, int maxDepth) { return buildTrieRec (splits, lower, upper, prefix, maxDepth, new CarriedTrieNodeRef()); } /** * This is the core of buildTrie. The interface, and stub, above, just adds * an empty CarriedTrieNodeRef. * * We build trie nodes in depth first order, which is also in key space * order. Every leaf node is referenced as a slot in a parent internal * node. If two adjacent slots [in the DFO] hold leaf nodes that have * no split point, then they are not separated by a split point either, * because there's no place in key space for that split point to exist. * * When that happens, the leaf nodes would be semantically identical, and * we reuse the object. A single CarriedTrieNodeRef "ref" lives for the * duration of the tree-walk. ref carries a potentially reusable, unsplit * leaf node for such reuse until a leaf node with a split arises, which * breaks the chain until we need to make a new unsplit leaf node. * * Note that this use of CarriedTrieNodeRef means that for internal nodes, * for internal nodes if this code is modified in any way we still need * to make or fill in the subnodes in key space order. */ private TrieNode buildTrieRec(BinaryComparable[] splits, int lower, int upper, byte[] prefix, int maxDepth, CarriedTrieNodeRef ref) { final int depth = prefix.length; // We generate leaves for a single split point as well as for // no split points. if (depth >= maxDepth || lower >= upper - 1) { // If we have two consecutive requests for an unsplit trie node, we // can deliver the same one the second time. if (lower == upper && ref.content != null) { return ref.content; } TrieNode result = LeafTrieNodeFactory(depth, splits, lower, upper); ref.content = lower == upper ? result : null; return result; } InnerTrieNode result = new InnerTrieNode(depth); byte[] trial = Arrays.copyOf(prefix, prefix.length + 1); // append an extra byte on to the prefix int currentBound = lower; for(int ch = 0; ch < 0xFF; ++ch) { trial[depth] = (byte) (ch + 1); lower = currentBound; while (currentBound < upper) { if (splits[currentBound].compareTo(trial, 0, trial.length) >= 0) { break; } currentBound += 1; } trial[depth] = (byte) ch; result.child[0xFF & ch] = buildTrieRec(splits, lower, currentBound, trial, maxDepth, ref); } // pick up the rest trial[depth] = (byte)0xFF; result.child[0xFF] = buildTrieRec(splits, lower, currentBound, trial, maxDepth, ref); return result; } }
2e55418458fe38117be63b607afb95e48719764a
38242dd121ca34ff642d7e01f0875656c94e60bf
/MyGame.java
a5168640795425b9f76f25232cf5f3c835d7eca9
[ "WTFPL" ]
permissive
nate00/shapes
67747954079976244c75f1d6336d3c3d179138d0
e6bfabeaf18fcb5de9a4b1f3c8e35d1feecaf7d1
refs/heads/master
2021-01-10T07:03:09.553970
2013-04-14T16:15:32
2013-04-14T16:15:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
630
java
import shapes.*; import java.awt.Color; public class MyGame extends Game { // Put variables here! @Override public void setup() { // Put code here! // This code will be executed when the game begins. This is where you // can make the initial shapes, set the background color, etc. } @Override public void update() { // Put code here! // This code will be executed once per frame. This is where you can make // shapes move around, say things, etc. } public static void main(String[] args) { new MyGame(); } public MyGame() { super(false); setup(); ready(); } }
688894c2aa80f33468ead4d43d8fa9bcef3abfd2
0a064ee0fcba1dbe5cdd81c9e5289fcce18fc9ee
/swea/jeesoo/Harvesting.java
cf0c02cfee3fd629afbeff44bd767cbb7fcbae70
[]
no_license
ssafy-algoga/coding-study
96705fb327e40fb4a24f244bae08df106ea123c6
1c3113f085075907f61afbc1ee9b355c82520f53
refs/heads/main
2023-03-30T07:05:53.562801
2021-03-29T04:49:01
2021-03-29T04:49:01
352,594,063
0
1
null
2021-03-29T09:53:28
2021-03-29T09:53:28
null
UTF-8
Java
false
false
1,794
java
package swea; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Harvesting { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); /**테스트 케이스 횟수 입력 받기*/ int T = Integer.parseInt(br.readLine()); // StringTokenizer 쓰면 안됨! 숫자가 다 붙어서 오니까 for(int testCase=1;testCase<=T;testCase++) { /**농장 가로(세로)크기 N입력 받기*/ int N = Integer.parseInt(br.readLine()); /**농장 2차원 배열에 넣어주기*/ int[][] farm = new int[N][N]; for (int i = 0; i < N; i++) { String str = br.readLine(); for (int j = 0; j < N; j++) { farm[i][j] = str.charAt(j)-'0'; } } int point = N/2; int sumValue = 0; // 농작물 가치 합 for (int i = 0; i < N; i++) { if(i<=point) { sumValue += farm[i][point]; int move = 1; for (int j = 0; j < i; j++) { sumValue += farm[i][point-move]; sumValue += farm[i][point+move]; move++; } } else { sumValue += farm[i][point]; int move = 1; for (int j = N-i-1; j > 0; j--) { sumValue += farm[i][point-move]; sumValue += farm[i][point+move]; move++; } } }// 행 고정해서 N까지 아래로 내려가는 형태 /**각 테스트 케이스 마다의 결과값 출력*/ sb.append("#").append(testCase).append(" ").append(sumValue); System.out.println(sb); sb.setLength(0); } } }
4461e876eae95abe438213439280206b8dade180
984a2f6beadc87994576d88ff59b16554094432f
/src/javaprogramming1/oops/inheritance/Ferrari.java
ba05bf7d05db737fdd192aa3f84f28908166e6ce
[]
no_license
premaluu/JavaProgramming1
361f24dc946cba67f47d82fc21ff742aa2dd79f2
9c0df79d0cd081e65780046bd021f0417ef526d8
refs/heads/master
2022-12-29T01:31:06.320331
2020-10-08T18:45:40
2020-10-08T18:45:40
284,989,625
0
0
null
null
null
null
UTF-8
Java
false
false
253
java
package javaprogramming1.oops.inheritance; public class Ferrari implements Car { @Override public void run() { System.out.println("\nFerrari is running"); } @Override public void shiftGear() { System.out.println("\nFerrari gear shifted"); } }
3afba62f29f85db501f23afd85448abeabcbe2e4
d8bc877da7355045051bf3eb5cd4db457d024322
/myilpwearable/src/main/java/com/ilp/ilpschedule/utilities/DividerItemDecorator.java
e3fc6577d56047abee43d3eee381041da8fb642b
[]
no_license
robsinspirechange/MyILP_Abhishek
dc94a7b1791eb6e9c1a5589ffd69e328b8237ad2
6881218c0438fa4cf39b09f22b31b8c683d585e5
refs/heads/master
2021-06-15T16:05:22.085092
2017-02-28T04:46:23
2017-02-28T04:46:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,279
java
package com.ilp.ilpschedule.utilities; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Created by abhi on 2/20/2016. */ public class DividerItemDecorator extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[]{ android.R.attr.listDivider }; public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; private Drawable mDivider; private int mOrientation; public DividerItemDecorator(Context context, int orientation) { if (context != null) { final TypedArray a = context.obtainStyledAttributes(ATTRS); mDivider = a.getDrawable(0); a.recycle(); setOrientation(orientation); } } public void setOrientation(int orientation) { if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { throw new IllegalArgumentException("invalid orientation"); } mOrientation = orientation; } @Override public void onDraw(Canvas c, RecyclerView parent) { if (mOrientation == VERTICAL_LIST) { drawVertical(c, parent); } else { drawHorizontal(c, parent); } } public void drawVertical(Canvas c, RecyclerView parent) { final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } public void drawHorizontal(Canvas c, RecyclerView parent) { final int top = parent.getPaddingTop(); final int bottom = parent.getHeight() - parent.getPaddingBottom(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int left = child.getRight() + params.rightMargin; final int right = left + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { if (mOrientation == VERTICAL_LIST) { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); } } }
425751fdb8321481c1f2d0e27b9fb2493550bf28
d6b4fd03c14de2c52d2e2617f974b96bb6241740
/kls-reports/src/main/java/com/vsoftcorp/kls/report/dao/IBalanceListReportDAO.java
b6b7e98d0a1e77020bc7856bb71c5f8a2e9c3a51
[]
no_license
harivsoft/KLS
9abc57cb86001f36f9fbb8a5490e3b2f59cb3436
abc0394e7ba2925df130b94139791c12801e5bf4
refs/heads/master
2021-01-19T12:40:22.403041
2017-08-31T04:04:04
2017-08-31T04:04:04
100,795,258
0
0
null
null
null
null
UTF-8
Java
false
false
423
java
package com.vsoftcorp.kls.report.dao; import java.util.List; import com.vsoftcorp.kls.business.entity.account.LineOfCredit; import com.vsoftcorp.time.Date; /** * * @author a1605 * */ public interface IBalanceListReportDAO { List<LineOfCredit> getLineOfCreditByPacsAndCustomerId(Integer pacsId, Integer productId, Long customerId); List<Object[]> getBalanceListReportData(Long lineOfcreditId, Date asOnDate); }
f0d05830fa4b9de52ec1ff6a8cda1142bc7ba9ae
d8d965524b1d7e0fe17fcb90f62ca638e0e87793
/src/com/javacodegeeks/abstractdefaultinterface/Employee.java
b0113905039c85cc6254ddc1709de4d01dfad1a7
[]
no_license
EarnestMD/java-oops-concepts-tutorial
38dbfd1eda6044406ec9de53564e72eb18588991
2e59d7e78e8670a47cbc9ada54bee549bc2bc4a8
refs/heads/master
2023-04-10T07:29:33.730939
2019-03-23T09:01:47
2019-03-23T09:01:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
968
java
package com.javacodegeeks.abstractdefaultinterface; public class Employee implements EmployeeInterface { private String name; private double salary; private String department; private String role; public Employee(String name, double salary, String department, String role) { this.name = name; this.salary = salary; this.department = department; this.role = role; } @Override public String getName() { return name; } @Override public double getSalary() { return salary; } @Override public String getDepartment() { return department; } @Override public String getRole() { return role; } @Override public String toString() { return getName() + " is a " + getRole() + " at the " + getDepartment() + " department earning an annual salary of $" + salary + " with bonus $" + getBonus(); } }
0a3983c08a37566b189c5027fa2b5e72d5c1cb64
7740403c9cb5854fdc0feeaad7c188d797e66559
/src/exception/IncompleteInformationException.java
aebec69154c8a5378b250980c91e65c95e9702d1
[]
no_license
Dannasofiagarcia/Lab_ShiftControl
e279b150b0267730bee0c39e8fbaf7709bcb7e58
b0c1c52be9e259a46bb146240e0d9b729c359d7e
refs/heads/master
2022-06-17T01:00:58.953124
2020-05-07T21:19:46
2020-05-07T21:19:46
245,025,260
0
0
null
null
null
null
UTF-8
Java
false
false
185
java
package exception; public class IncompleteInformationException extends Exception { public IncompleteInformationException() { super("The information of the user is complete"); } }
4ba35e72d02569d52c6b016976188a2349e0a464
d23e05eee717ee2aff78603628f2c58a178178db
/Intents/src/com/jspiders/intents/MainActivity.java
68c5f50b76fd87f4606d76b6a51977a5f8673233
[]
no_license
ShanmugamSundaram/OECM-1
12b6ea9287e8a40bfd983f81861af670f8f625fa
80f45b7c935d7b1528c155419f998ea76c288139
refs/heads/master
2021-01-21T04:00:07.001085
2015-12-04T03:02:00
2015-12-04T03:02:00
45,091,401
0
0
null
2015-10-28T05:41:07
2015-10-28T05:41:07
null
UTF-8
Java
false
false
971
java
package com.jspiders.intents; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { Button startbutton; EditText inputedittext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startbutton = (Button) findViewById(R.id.buttonstart); inputedittext = (EditText) findViewById(R.id.editTextinput); startbutton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { String i1 = inputedittext.getText().toString(); Intent intent = new Intent(MainActivity.this,SecondActivity.class); intent.putExtra("Key2",i1); startActivity(intent); } }); } }
2ba99921b09df47cb8368607b268c59c135978bf
e1b3d176c02b9077cee9a971312e39a8dd06062e
/marketapp.ejb/src/main/java/com/enterprise/market/controller/MemberListProducer.java
0a73180c4077d12ddd502958e26efcd96b8f3904
[ "MIT" ]
permissive
mansoto8/MarketJee
ef70a8cee924cf7dd2895376b165a8e1d929bdc4
df4680fa907b905fa52a1bc9f3e962291f2c35cf
refs/heads/master
2020-03-31T04:27:34.020846
2018-10-07T04:49:38
2018-10-07T04:49:38
151,906,194
0
0
null
null
null
null
UTF-8
Java
false
false
2,612
java
/** * JEE6 gradle-based Demo App * * File: MemberListProducer.java, 24.07.2014, 10:19:55, mreinhardt * * @project https://github.com/hypery2k/gradleJEE * * @copyright 2014 Martin Reinhardt [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.enterprise.market.controller; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.enterprise.event.Observes; import javax.enterprise.event.Reception; import javax.enterprise.inject.Produces; import javax.inject.Inject; import javax.inject.Named; import java.util.List; import com.enterprise.market.domain.Member; import com.enterprise.market.services.MemberRepository; /** * Simple producer example which also utilize events observation * * @author mreinhardt * */ @RequestScoped public class MemberListProducer { @Inject private MemberRepository memberRepository; private List<Member> members; @PostConstruct public void retrieveAllMembersOrderedByName() { members = memberRepository.findAllOrderedByName(); } /** * usage of @Named provides access the return value via the EL variable name * "members" in the UI (e.g. Facelets or JSP view) */ @Produces @Named public List<Member> getMembers() { return members; } /** * Method is invoked when a new member is registered * * @param member * @see MemberRegistration#register(Member) */ public void onMemberListChanged( @Observes(notifyObserver = Reception.IF_EXISTS) final Member member) { retrieveAllMembersOrderedByName(); } }
45ec6b78a48dc3196c9f08ca215516ea5b4c48fa
bf6e650a84d148f6186335696717f5c89eeba2b6
/team1-code/src/main/TilePile.java
5039714aff95f3a090c7ff71ec3f01a34319378d
[]
no_license
jaydenrsoni/tsuro-game-implementation
afd858387c2042ab14c3e2439c7ee4d54239e979
b8ddfd3adb98e3b742373dff2b6bee0b16298545
refs/heads/master
2020-03-20T23:19:06.603506
2018-06-15T16:32:53
2018-06-15T16:32:53
137,840,501
0
0
null
null
null
null
UTF-8
Java
false
false
2,462
java
package main; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; /** * A collection of all Tiles in Tsuro * * Created by vyasalwar on 4/16/18. */ public class TilePile { final private String DEFAULT_FILE_PATH = "tiles.txt"; public TilePile(){ tiles = new LinkedList<>(); fillTiles(DEFAULT_FILE_PATH); } public TilePile(String filename){ tiles = new LinkedList<>(); fillTiles(filename); } //=====b=========================================================================== // Instance Variables //================================================================================ private Deque<Tile> tiles; //================================================================================ // Public methods //================================================================================ public Tile drawFromDeck(){ try { return tiles.removeFirst(); } catch (NoSuchElementException e) { return null; } } public void shuffleDeck(){ List<Tile> tileList = new ArrayList<Tile>(tiles); Collections.shuffle(tileList); tiles = new LinkedList<>(tileList); } public void shuffleDeck(int seed){ List<Tile> tileList = new ArrayList<Tile>(tiles); Collections.shuffle(tileList, new Random(seed)); tiles = new LinkedList<>(tileList); } public void returnToDeck(Tile tile){ tiles.addLast(tile); } public boolean isEmpty(){ return tiles.isEmpty(); } //================================================================================ // Private helpers //================================================================================ // Initialize the TilePile using the tiles specified in the given file private void fillTiles(String filename) { try { File file = new File(filename); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; while((line = bufferedReader.readLine()) != null){ Tile newTile = new Tile(line); tiles.addLast(newTile); } } catch (IOException e){ e.printStackTrace(); } } }
1cde7938011618181c5eda01488e1f3303c5ccc8
63207661a354327590b6ab7a8d1f6d8d6ef2e41c
/src/test/java/wingersworldwide/dome/studioman/application/repository/CustomAuditEventRepositoryIT.java
8b18de0da4c68cc3bd34413e62438d958715a24d
[]
no_license
Michuki/WWStudioMan
d921de87bf1c0dd8c7d3ad10a78001184cc371cc
efc5393e774880228332d5bec2e4ec69bd839d7c
refs/heads/master
2022-12-24T05:22:55.149213
2019-07-13T18:22:57
2019-07-13T18:22:57
196,753,317
0
0
null
2022-12-16T05:02:04
2019-07-13T18:22:42
Java
UTF-8
Java
false
false
8,001
java
package wingersworldwide.dome.studioman.application.repository; import wingersworldwide.dome.studioman.application.StudioManApp; import wingersworldwide.dome.studioman.application.config.Constants; import wingersworldwide.dome.studioman.application.config.TestSecurityConfiguration; import wingersworldwide.dome.studioman.application.config.audit.AuditEventConverter; import wingersworldwide.dome.studioman.application.domain.PersistentAuditEvent; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.kafka.test.context.EmbeddedKafka; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpSession; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static wingersworldwide.dome.studioman.application.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; /** * Integration tests for {@link CustomAuditEventRepository}. */ @EmbeddedKafka @SpringBootTest(classes = {StudioManApp.class, TestSecurityConfiguration.class}) @Transactional public class CustomAuditEventRepositoryIT { @Autowired private PersistenceAuditEventRepository persistenceAuditEventRepository; @Autowired private AuditEventConverter auditEventConverter; private CustomAuditEventRepository customAuditEventRepository; private PersistentAuditEvent testUserEvent; private PersistentAuditEvent testOtherUserEvent; private PersistentAuditEvent testOldUserEvent; @BeforeEach public void setup() { customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter); persistenceAuditEventRepository.deleteAll(); Instant oneHourAgo = Instant.now().minusSeconds(3600); testUserEvent = new PersistentAuditEvent(); testUserEvent.setPrincipal("test-user"); testUserEvent.setAuditEventType("test-type"); testUserEvent.setAuditEventDate(oneHourAgo); Map<String, String> data = new HashMap<>(); data.put("test-key", "test-value"); testUserEvent.setData(data); testOldUserEvent = new PersistentAuditEvent(); testOldUserEvent.setPrincipal("test-user"); testOldUserEvent.setAuditEventType("test-type"); testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000)); testOtherUserEvent = new PersistentAuditEvent(); testOtherUserEvent.setPrincipal("other-test-user"); testOtherUserEvent.setAuditEventType("test-type"); testOtherUserEvent.setAuditEventDate(oneHourAgo); } @Test public void addAuditEvent() { Map<String, Object> data = new HashMap<>(); data.put("test-key", "test-value"); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); assertThat(persistentAuditEvent.getData()).containsKey("test-key"); assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value"); assertThat(persistentAuditEvent.getAuditEventDate().truncatedTo(ChronoUnit.MILLIS)) .isEqualTo(event.getTimestamp().truncatedTo(ChronoUnit.MILLIS)); } @Test public void addAuditEventTruncateLargeData() { Map<String, Object> data = new HashMap<>(); StringBuilder largeData = new StringBuilder(); for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { largeData.append("a"); } data.put("test-key", largeData); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); assertThat(persistentAuditEvent.getData()).containsKey("test-key"); String actualData = persistentAuditEvent.getData().get("test-key"); assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH); assertThat(actualData).isSubstringOf(largeData); assertThat(persistentAuditEvent.getAuditEventDate().truncatedTo(ChronoUnit.MILLIS)) .isEqualTo(event.getTimestamp().truncatedTo(ChronoUnit.MILLIS)); } @Test public void testAddEventWithWebAuthenticationDetails() { HttpSession session = new MockHttpSession(null, "test-session-id"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); request.setRemoteAddr("1.2.3.4"); WebAuthenticationDetails details = new WebAuthenticationDetails(request); Map<String, Object> data = new HashMap<>(); data.put("test-key", details); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); } @Test public void testAddEventWithNullData() { Map<String, Object> data = new HashMap<>(); data.put("test-key", null); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null"); } @Test public void addAuditEventWithAnonymousUser() { Map<String, Object> data = new HashMap<>(); data.put("test-key", "test-value"); AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(0); } @Test public void addAuditEventWithAuthorizationFailureType() { Map<String, Object> data = new HashMap<>(); data.put("test-key", "test-value"); AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(0); } }
8f112089787e088f3cfd1c77638f98fca28692ea
9960150c78308e085b0521dde4d4100fcdf69b47
/source/Occluder.java
adbb199a9684cce456c1d3e3f51efc107b0c0eed
[]
no_license
Rune-Status/jordanabrahambaws-103-Refactor
c3671a54bfc7df95b9ed9eaf165757dcdb03eb0c
d4330a69c4818ebcdc35ca085545d5714ee81b0b
refs/heads/master
2021-06-18T06:29:20.121702
2017-06-14T05:34:31
2017-06-14T05:34:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
598
java
public final class Occluder { int maxZ; int maxTIleX; int minTileZ; int minNormalX; int type; int minX; int maxX; int minZ; int testDirection; int maxY; int maxTileZ; int anInt377; int minY; int anInt379; int maxNormalX; public static int gameWidth; int maxNormalY; int minNormalY; int minTileX; static CacheIndex skeletonsIndex; static final void method201() { if (Class30.soundSystem1 != null) { Class30.soundSystem1.method82(); } if (DualNode_Sub14.soundSystem0 != null) { DualNode_Sub14.soundSystem0.method82(); } } }
bcd11853061bc9f4b4ea1d9386dfd5a024e46fce
c1cde1163017a40adc5d2753c80667797594dcbd
/src/main/java/DataBase/Rim.java
92ae1cf693ba981c0dcf029a056c1f254d5e20ac
[]
no_license
Space-ace/CarPartsSales
7d6d1ca067857635991fdaad2f59f19a4088c95b
078d25e4578da52e3046aef4528438594b7c6fa0
refs/heads/master
2020-06-04T10:35:53.839450
2019-06-14T18:56:51
2019-06-14T18:56:51
191,987,003
0
0
null
null
null
null
UTF-8
Java
false
false
1,806
java
package DataBase; //Класс, содержащий модель из базы данных для таблицы дисков. Я делал как в лабах, но пришлось менять код и эта часть не сейчас не используется. Потом нужно будет просто всю инфу из базы сюда поместить public class Rim { private int id; private String name; private int manufacturer; private float diameter; private int autoId; private int count; private float price; public Rim() { this.name = ""; this.manufacturer = 0; this.diameter = 0; this.price = 0; } public Rim(String name, int ManufacturerId, float Diameter, float Price) { this.name = name; this.manufacturer = ManufacturerId; this.diameter = Diameter; this.price = Price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getAutoId() { return autoId; } public void setAutoId(int autoId) { this.autoId = autoId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getManufacturer() { return manufacturer; } public void setManufacturer(int ManufacturerId) { this.manufacturer = ManufacturerId; } public float getDiameter() { return diameter; } public void setDiameter(float Diameter) { this.diameter = Diameter; } public float getPrice() { return price; } public void setPrice(float Price) { this.price = Price; } }
b50ec2c60f8b81a70a54b4187e0da4584f02b72a
acc3e58763bec0f1ff8e0022b3b760c28ebe8097
/Tutorial6_Rabu/src/test/java/com/apap/tutorial6/repository/FlightDbTest.java
27cd792225df3f833f251ecea8de7a6dfd856138
[]
no_license
Apap-2018/tutorial6_1606876872
8e5443c900b2f4d9b1ec7ba8f88f2c95a032bab6
000e6dd588a4c0d2571a9d09796920cc8ced2dc9
refs/heads/master
2020-04-01T17:51:54.825203
2018-10-17T12:44:43
2018-10-17T12:44:43
153,455,222
0
0
null
null
null
null
UTF-8
Java
false
false
1,876
java
package com.apap.tutorial6.repository; import static org.junit.Assert.assertThat; import java.sql.Date; import java.util.Optional; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; import com.apap.tutorial6.model.FlightModel; import com.apap.tutorial6.model.PilotModel; @RunWith(SpringRunner.class) @DataJpaTest @AutoConfigureTestDatabase(replace = Replace.NONE) public class FlightDbTest { @Autowired private TestEntityManager entityManager; @Autowired private FlightDb flightDb; @Test public void whenFindByFlightNumber_thenReturnFlight() { // given PilotModel pilotModel = new PilotModel(); pilotModel.setLicenseNumber("4172"); pilotModel.setName("Coki"); pilotModel.setFlyHour(59); entityManager.persist(pilotModel); entityManager.flush(); FlightModel flightModel = new FlightModel(); flightModel.setFlightNumber("X550"); flightModel.setOrigin("Depok"); flightModel.setDestination("Bekasi"); flightModel.setTime(new Date(new java.util.Date().getTime())); flightModel.setPilot(pilotModel); entityManager.persist(flightModel); entityManager.flush(); // when Optional<FlightModel> found = flightDb.findByFlightNumber(flightModel.getFlightNumber()); // then assertThat(found.get(), Matchers.notNullValue()); // Check if Not Null assertThat(found.get(), Matchers.equalTo(flightModel)); // Check if Same } }
e1e643ea5a0748222603c1188ff4f2047e723459
bf66caa4e1568bc0b47cfc8791a0452422f2f7fd
/src/main/java/com/qf/manager/web/WatermarkAction.java
f25c289cc0377f2a01000d4bd854fb021a5d5e7d
[]
no_license
itmck/watermark-demo
f9d18d993e8838ecc17b37ae09eef89115a21566
873b3b664b236753d0f503cafe8c6c71b47220ec
refs/heads/master
2020-04-01T04:57:11.113337
2018-10-13T15:18:27
2018-10-13T15:18:27
152,883,320
0
0
null
null
null
null
UTF-8
Java
false
false
1,810
java
package com.qf.manager.web; import com.qf.manager.pojo.PicInfo; import com.qf.manager.service.MarkService; import com.qf.manager.service.UploadService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpSession; /** * Create by it_mck 2018/10/13 16:22 * * @Description: * @Version: 1.0 */ @Controller @RequestMapping("water") public class WatermarkAction { @Autowired private UploadService uploadService; @Autowired private MarkService markService; @RequestMapping("index") public String index() { return "index"; } @PostMapping("mark") public String watermark(@RequestParam("img") CommonsMultipartFile files, Model model, HttpSession session) { String uploadPath = "/imgs"; String realUploadPath = session.getServletContext().getRealPath(uploadPath); PicInfo pi = new PicInfo(); PicInfo pi3 = new PicInfo(); pi.setImgUrl(uploadService.UploadImage(files, uploadPath, realUploadPath)); pi.setLogoImgUrl(markService.watermark(files, uploadPath, realUploadPath)); pi3.setLogoImgUrl(markService.moreWatermark(files, uploadPath, realUploadPath)); model.addAttribute("pi1", pi.getImgUrl());//加上水印前 model.addAttribute("pi2", pi.getLogoImgUrl());//加上单文字水印后 model.addAttribute("pi3", pi3.getLogoImgUrl());//加上多文字水印后 return "watermark"; } }
ee90af6d3561ad30d94102e496d02555a6fbdc47
87431e82ce3dcde7da327d3b8d341f5f7acfa374
/src/messages/ResultReportMessage.java
7c1ef989c0621da65ff6090044cfb680170713ed
[]
no_license
SlobodanNikolic/DistributedQueens
04efba584e9d54b9a36dff2d8e203622e0c24ca5
38a429c40ada7e231b6c98c238c9b717c08336b0
refs/heads/master
2020-05-25T21:02:13.985221
2019-06-06T22:49:02
2019-06-06T22:49:02
187,988,893
0
0
null
null
null
null
UTF-8
Java
false
false
1,100
java
package messages; import java.util.ArrayList; import app.AppInfo; import bootstrap.BootstrapConfig; import node.NodeInfo; public class ResultReportMessage extends BasicMessage { private static final long serialVersionUID = -333251402058492901L; public ResultReportMessage(NodeInfo originalSender, NodeInfo sender, NodeInfo receiver, String jobResult) { super(MessageType.RESULT_REPORT, originalSender, sender, receiver, jobResult); } @Override public void sendEffect() { } @Override public String toString() { String mtype = getMessageType().toString(); String id = getMessageId() + ""; String info = getOriginalSenderInfo().getId() + ""; String info2 = getSenderInfo().getId() + ""; String rec = getReceiverInfo().getId() + ""; String txt = getMessageText(); return "Message: " + getMessageType() + "|" + getOriginalSenderInfo().getId() + "|" + getSenderInfo().getId() + "|" + getReceiverInfo().getId() + "|" + getMessageText() + "|"; } @Override public NodeInfo getResponseObject() { // TODO Auto-generated method stub return null; } }
3c264e0718b2e48ff1f4795bdd0136e329b62f1a
8752de68a07036d82a52faa3a7be6c82540a46a3
/PushNotification/app/src/test/java/com/example/honey/pushnotification/ExampleUnitTest.java
9c80b107ae46515cf8e942a5450a8bdf7045f423
[]
no_license
Honey14/Android_Honey
4dccbbe6dd0b1646ddebeb87c71746b1afa7b4f8
3f1d63b6d8e255d861b436fa897e3e0679ea04ae
refs/heads/master
2021-05-16T13:45:43.738419
2019-09-12T15:01:31
2019-09-12T15:01:31
105,436,892
0
1
null
2017-10-02T15:06:25
2017-10-01T11:16:20
Java
UTF-8
Java
false
false
412
java
package com.example.honey.pushnotification; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
d0adf41449154949413b9b9a219c6762c53d1ddb
3a6a0e7b3d507e5358023941b797815d11578cfb
/src/vistas/jefebodega/VAsignarRuta.java
f55430b72a61d40f6bd48d90e82193fb7b857fd6
[]
no_license
lesterdc/ProyectoFinalDise-o
8280e79747105daf69f2fc6c3b93a730a855a567
38143a7d9abb1d837bcd6b414324d463c5d94f39
refs/heads/master
2020-07-09T23:23:37.737029
2019-08-23T23:19:38
2019-08-23T23:19:38
204,107,431
0
0
null
null
null
null
UTF-8
Java
false
false
5,536
java
/* * 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 vistas.jefebodega; import controladores.jefebodega.ControladorJefeBodega; import modelos.Repartidor; /** * * @author Melanie Banchon */ public class VAsignarRuta extends javax.swing.JPanel { Repartidor r; /** * Creates new form VAsignarRuta */ public VAsignarRuta() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bRepartidor = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); cRepartidor = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); rutas = new javax.swing.JComboBox<>(); jLabel3 = new javax.swing.JLabel(); asignar = new javax.swing.JButton(); bRepartidor.setText("Obtener Repartidor"); bRepartidor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bRepartidorActionPerformed(evt); } }); jLabel1.setText("Asignar Repartidor"); jLabel2.setText("Repartidor: "); rutas.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jLabel3.setText("Rutas:"); asignar.setText("Asignar"); asignar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { asignarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(171, 171, 171) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(55, 55, 55) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(rutas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(cRepartidor, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(bRepartidor)) .addComponent(asignar)) .addContainerGap(123, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(57, 57, 57) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bRepartidor) .addComponent(cRepartidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(36, 36, 36) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rutas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addGap(49, 49, 49) .addComponent(asignar) .addContainerGap(129, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void asignarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_asignarActionPerformed System.err.print(evt.toString()); String nombre =cRepartidor.getText(); if(nombre.equals(r.getNombre())){ r.setRutaDeEntrega(new VEntregas().ruta); } }//GEN-LAST:event_asignarActionPerformed private void bRepartidorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRepartidorActionPerformed System.err.print(evt.toString()); r = ControladorJefeBodega.getCola().poll(); cRepartidor.setText(r.getNombre()); }//GEN-LAST:event_bRepartidorActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton asignar; private javax.swing.JButton bRepartidor; private javax.swing.JTextField cRepartidor; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JComboBox<String> rutas; // End of variables declaration//GEN-END:variables }
30b8cf9f6fa301f1e45f482f80e655203e5c8a13
80dc1f90553842a4a447f436d151b9ab6fab9154
/Sample_projects/05132011/pax-tests/src/test/java/geecon/osgi/paxtests/sandbox/UsesDirectivePositiveTest.java
b350356ebcf981093b1ede97a6d903cf2f760aeb
[]
no_license
osgi-forks/geecon2011.osgi
75a8fca25f2a4d5a75ce02420068f1ad781f0314
5bfed9d2bf42b5b2d750f3ec4b7bdba78f110811
refs/heads/master
2021-01-18T12:49:43.711660
2011-05-13T11:55:28
2011-05-13T11:55:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,151
java
package geecon.osgi.paxtests.sandbox; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.provision; import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.withBnd; import entities.Person; import geecon.osgi.paxtests.AbstractIntegrationTest; import java.io.InputStream; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Customizer; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.swissbox.tinybundles.core.TinyBundle; import org.ops4j.pax.swissbox.tinybundles.core.TinyBundles; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import store.Persister; /** * See slide No. 10. Bundles defined here are exactly the same as the ones shown in that slide. * * This test works - all bundles are active. It's because all bundles are deployed at the same time, so the container tries to find the best * possible configuration. Both the Persistence and the Client bundle get package 'entities' in version 1.0. * * @author Bartosz Kowalewski * */ @RunWith(JUnit4TestRunner.class) public class UsesDirectivePositiveTest extends AbstractIntegrationTest { public Option[] testSpecificConfiguration() { Option[] testSpecificOptions = options( // Bundle-SymbolicName: entities10 // Bundle-Name: entities10 // Bundle-Version: 1.0 // Export-Package: entities;version="1.0" // -noimport:=true : be careful, metadata is preprocessed during bundle generation; the tool (BND library) might add // a corresponding import statement to the export (entities); this might cause only a.a in ver. 1.1 to be present in // the env; provision( TinyBundles.newBundle() .set(Constants.BUNDLE_SYMBOLICNAME,"entities10") .set(Constants.BUNDLE_NAME, "entities10") .set(Constants.BUNDLE_VERSION, "1.0") .set(Constants.IMPORT_PACKAGE, "") .set(Constants.EXPORT_PACKAGE, "entities;version=\"1.0\";-noimport:=true") .add(Person.class) .build(withBnd()) ), // Bundle-SymbolicName: entities11 // Bundle-Name: entities11 // Bundle-Version: 1.1 // Export-Package: entities;version="1.1" provision( TinyBundles.newBundle() .set(Constants.BUNDLE_SYMBOLICNAME, "entities11") .set(Constants.BUNDLE_NAME, "entities11") .set(Constants.BUNDLE_VERSION, "1.1") .set(Constants.IMPORT_PACKAGE, "") .set(Constants.EXPORT_PACKAGE, "entities;version=\"1.1\";-noimport:=true") .add(Person.class) .build(withBnd()) ), // Bundle-SymbolicName: store20 // Bundle-Name: store20 // Bundle-Version: 2.0 // Import-Package: entities;version="[1.0,1.1]" // Export-Package: store;uses:=entities;version="2.0" provision( TinyBundles.newBundle() .set(Constants.BUNDLE_SYMBOLICNAME, "store20") .set(Constants.BUNDLE_NAME, "store20") .set(Constants.BUNDLE_VERSION, "2.0") .set(Constants.IMPORT_PACKAGE, "entities;version=\"[1.0,1.1]\"") .set(Constants.EXPORT_PACKAGE, "store;version=\"2.0\";uses:=\"entities\"") .add(Persister.class) .build(withBnd()) ), // Bundle-SymbolicName: client10 // Bundle-Name: client10 // Bundle-Version: 1.0 // Import-Package: entities;version="[1.0,1.0]",store;version="[2.0, 2.0]" provision( TinyBundles.newBundle() .set(Constants.BUNDLE_SYMBOLICNAME, "client10") .set(Constants.BUNDLE_NAME, "client10") .set(Constants.BUNDLE_VERSION, "1.0") .set(Constants.IMPORT_PACKAGE, "entities;version=\"[1.0,1.0]\", store;version=\"[2.0, 2.0]\"") .set(Constants.EXPORT_PACKAGE, "") .build(withBnd()) ), // Oh gosh, if you change order of the last two bundles, the test will fail under Felix, but it will pass when // Equinox is used:). new Customizer() { @Override public InputStream customizeTestProbe(InputStream testProbe) throws Exception { TinyBundle bundle = TinyBundles.modifyBundle(testProbe) .removeResource("entities/Person.class").removeResource("entities/") .removeResource("store/Persister.class").removeResource("store/") .removeHeader("Private-Package"); return bundle.build(); } } ); return testSpecificOptions; } @Test public void works() throws Exception { // verify if all bundles are active for (String symbolicName : new String[]{ "entities10", "entities11", "store20", "client10" }) { verifyBundleIsActive(symbolicName); } // the test is failing ? go to the super class (AbstractIntegrationTest), change the framework from equinox() to felix() and rerun // the test; detailed info related to package resolution problems should be printed now; } private void verifyBundleIsActive(String symbolicName) { Bundle aaprovider1 = getBundle(symbolicName); assertNotNull(aaprovider1); assertEquals("Bundle with symbolic name " + symbolicName + " is not active.", Bundle.ACTIVE, aaprovider1.getState()); } }
8a9ff890462322b48b84511dfa484421a2ee0704
f63355f87023bff79f8c406b8ec613e3b96587ca
/Main.java
ac82134d34cbba305c919a976284c0ed6d623a11
[]
no_license
christiannlam/Comparators
8770eaedc404afe51eac26962b57f70b153e6c61
57734dc5c9941aad3ec95e4888b620ac7e0c0f3a
refs/heads/main
2023-02-16T12:58:45.939981
2021-01-10T01:03:49
2021-01-10T01:03:49
328,277,243
0
0
null
null
null
null
UTF-8
Java
false
false
3,566
java
import java.util.*; public class Main { public static void main(String[] args) { Map<Employee,String> gradeMap = new HashMap<Employee,String>(); Map<Integer,Employee> employeeMap = new HashMap<Integer,Employee>(); Scanner input = new Scanner (System.in); int userInput = 0; printMenuAndGetChoice(); System.out.println("Enter An Option: "); while( userInput != 5) { userInput = input.nextInt(); if( userInput == 1) { addEmployee(employeeMap,gradeMap); } else if ( userInput == 2) { removeEmployee(employeeMap,gradeMap); } else if( userInput == 3) { modifyPerformance(employeeMap,gradeMap); } else if( userInput == 4) { print(gradeMap); } else if( userInput == 5) { break; } printMenuAndGetChoice(); } } public static void printMenuAndGetChoice() { System.out.println("1) Add Employee" + "\n2) Remove Employee" + "\n3) Modify Performance" + "\n4) Display" + "\n5) Quit"); } public static void addEmployee(Map<Integer,Employee> employee, Map<Employee,String> performance) { Scanner input = new Scanner(System.in); System.out.println("Enter First Name Of Employee: "); String firstName = input.next(); System.out.println("Enter Last Name Of Employee: "); String lastName = input.next(); System.out.println("Enter ID Num Of Employee: "); int id = input.nextInt(); System.out.println("Enter Performance Score Of Employee: "); String score = input.next(); while(employee.containsKey(id)) { System.out.println("Employee ID Already Exists. Enter New ID: "); id = input.nextInt(); } Employee newEmployee = new Employee(firstName,lastName,id); employee.put(newEmployee.getId(),newEmployee); performance.put(newEmployee,score); } public static void removeEmployee(Map<Integer,Employee> employee, Map<Employee,String> performance) { System.out.println("Enter An Employee ID To Be Removed: "); Scanner input = new Scanner(System.in); int id = input.nextInt(); performance.remove(employee.get(id)); employee.remove(id); } public static void modifyPerformance(Map<Integer,Employee> employeeMap, Map<Employee,String> gradeMap) { Scanner input = new Scanner(System.in); System.out.println("Enter ID Num To Modify Score: "); int id = input.nextInt(); while(!employeeMap.containsKey(id)) { System.out.println("Employee Does Not Exist. Enter New ID: "); id = input.nextInt(); } System.out.println("Enter New Score: "); String performance = input.next(); gradeMap.put(employeeMap.get(id),performance); } public static void print(Map<Employee,String> gradeMap) { Set<Employee> employees = gradeMap.keySet(); List<Employee> employeeList = new ArrayList<Employee>(employees); Collections.sort(employeeList,new lastNameComparator()); employees = new LinkedHashSet<>(employeeList); for (Employee em : employees) { System.out.println(em.toString() + gradeMap.get(em)); } } }
fbc2bfcfc19b72c8a26a8c92ff2f13e140da008d
743592757b5229f2dc1386d38146d323e46da967
/02 Java/Ex03/LogicalOperator04.java
c618190abc21d1f923070f7c05da72ad2d3d4694
[]
no_license
Sherlock20200304/fullstackdeveloper
74db1abbc9f5abecc53513349c711adc867fda9f
9cc949137a287719744ca106f568924a714d7ec3
refs/heads/master
2023-04-13T16:14:35.503222
2021-04-20T15:01:35
2021-04-20T15:01:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
972
java
class LogicalOperator04 { public static void main(String[] args) { int a = 10; int b = 20; System.out.println("Value of int a: "+a ); System.out.println("Value of int b: "+b ); System.out.println(a<11); System.out.println(b>11); System.out.println("Value of int a: "+ (a++) ); System.out.println("Value of int b: "+ (b++) ); System.out.println("Value of int a: "+a ); System.out.println("Value of int b: "+b ); System.out.println("a<12: "+(a<12)); System.out.println("b>11: "+(b>11)); System.out.println("a<12 & b>11: "+ (a<12 & b>11) ); System.out.println("a<12 | b>11: "+ (a<12 | b>11) ); System.out.println("Value of int a: "+a ); System.out.println("Value of int b: "+b ); System.out.println("(a++)<12 || (b++)>20: "+ ((a++)<12 || (b++)>20) );//Short System.out.println("Value of int a: "+a ); System.out.println("Value of int b: "+b ); } }
ca9fd8de02b2f2cc92cf3ee81257293ff2547e29
a577dbd46e492452888bba666181fad9eea70f15
/client/src/main/java/com/note/client/i18n/session/SessionConfig.java
7f7d7b68ee76985b6d7a6583aa132302495e9aff
[]
no_license
thinkal01/SpringCloud_Sell
4a563ca63908031685f513cda67c0cd5f992c6f4
88f0c79f6e23923819ca1e060d80a132496753ec
refs/heads/master
2022-06-28T09:51:51.408835
2020-04-26T02:31:50
2020-04-26T02:31:50
221,481,323
0
0
null
2022-06-17T02:48:00
2019-11-13T14:43:53
JavaScript
UTF-8
Java
false
false
1,573
java
package com.note.client.i18n.session; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import java.util.Locale; @Configuration public class SessionConfig implements WebMvcConfigurer { @Bean public LocaleResolver localeResolver() { SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); // 设置session attribute的key sessionLocaleResolver.setLocaleAttributeName("locale"); // 设置默认的Locale sessionLocaleResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); return sessionLocaleResolver; } /** * 该拦截器通过名为locale的参数来拦截HTTP请求,使其重新设置页面的区域化信息 */ @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); // 设置请求的参数名为locale localeChangeInterceptor.setParamName("locale"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } }
5e428d89836a7b8649f9c80f7f4dd97776618311
128c6de94e4d4d5e152bb49e6934f749cbb080c4
/src/main/groovy/com/wcecil/webservice/controller/GameWebController.java
cfc1ac997ed8d51f7db880cc420bae0ca25a21e5
[ "CC0-1.0" ]
permissive
ButtonMashTheater/deckBuildingGame
cd09f0ce1797b6d29f2ef0ea43b47c1f6911d550
048e5028ab7fd41fbfbc2a298ad4fce421ad60d5
refs/heads/master
2020-05-22T11:31:48.923924
2015-09-01T03:22:38
2015-09-01T03:22:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,138
java
package com.wcecil.webservice.controller; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.wcecil.beans.dto.GameAudit; import com.wcecil.beans.dto.GameState; import com.wcecil.beans.dto.User; import com.wcecil.beans.gameobjects.ActualCard; import com.wcecil.beans.gameobjects.Card; import com.wcecil.beans.gameobjects.Player; import com.wcecil.beans.io.GamePlayerState; import com.wcecil.common.settings.ApplicationComponent; import com.wcecil.data.repositiories.AuditRepository; import com.wcecil.data.repositiories.GameRepository; import com.wcecil.data.repositiories.GameSearchRepository; import com.wcecil.data.repositiories.UsersRepository; import com.wcecil.game.actions.Action; import com.wcecil.game.core.GameController; import com.wcecil.io.util.MaskingHelper; import com.wcecil.webservice.service.AuthenticationService; import com.wcecil.websocket.messanger.MessangerService; @RestController @RequestMapping("/game") public class GameWebController { private @Autowired GameRepository gamesRepo; private @Autowired AuditRepository auditRepo; private @Autowired AuthenticationService authService; private @Autowired UsersRepository usersRepo; private @Autowired GameSearchRepository gameSearchRepo; private @Autowired ApplicationComponent context; private @Autowired GameController gameController; private @Autowired MaskingHelper maskingHelper; private @Autowired MessangerService messangerService; public GameWebController() { System.out.print("Creating " + this); } @RequestMapping(value = "/list", method = { RequestMethod.GET }) public GamePlayerState listGames( @RequestParam(value = "token") String token, HttpServletResponse response) { String userId = authService.getUserFromToken(token, response); GamePlayerState state = gamesRepo.loadGamesForUser(userId); return state; } @RequestMapping(value = "/get", method = { RequestMethod.GET }) public GameState getGame(@RequestParam(value = "id") String gameId, @RequestParam(value = "token") String token, HttpServletResponse response) { String userId = authService.getUserFromToken(token, response); GameState g = gamesRepo.getGame(gameId, true); GameState retVal = maskingHelper.maskGame(gameId, userId, g); return retVal; } @RequestMapping(value = "/quit", method = { RequestMethod.GET }) public GamePlayerState quitGame(@RequestParam(value = "id") String gameId, @RequestParam(value = "token") String token, HttpServletResponse response) throws IOException { String userId = authService.getUserFromToken(token, response); GameState g = gamesRepo.getGame(gameId, true); User me = usersRepo.getUser(userId); boolean left = me.getGames().remove(gameId); //TODO AUTH USER IS STILL IN GAME if(!left){ response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unable to quit a game you are not in."); return null; } //TODO ACTUALLY END GAME, with 'me' losing usersRepo.saveUser(me); gamesRepo.save(g); messangerService.endGame(gameId); return listGames(token, response); } @RequestMapping(value = "/audit", method = { RequestMethod.GET }) public List<GameAudit> getGameAudits( @RequestParam(value = "id") String gameId, @RequestParam(value = "token") String token, HttpServletResponse response) { authService.getUserFromToken(token, response); return auditRepo.getAuditsForGame(gameId); } @RequestMapping(value = "/queue", method = { RequestMethod.GET, RequestMethod.POST }) public Boolean queueGame(@RequestParam(value = "token") String token, HttpServletResponse response) { String userId = authService.getUserFromToken(token, response); gameSearchRepo.enterSearch(userId); return true; } @RequestMapping(value = "/queueDebug", method = { RequestMethod.GET, RequestMethod.POST }) public Boolean queueDebugGame(@RequestParam(value = "token") String token, @RequestParam(value = "userId") String _userId, HttpServletResponse response) throws IOException { if (!context.getAllowDebug()) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not Authorized"); return null; } String userId = authService.getUserFromToken(token, response); gameSearchRepo.enterSearch(userId); gameSearchRepo.enterSearch(_userId); return true; } @RequestMapping(value = "/solo", method = { RequestMethod.GET, RequestMethod.POST }) public GameState newGame(@RequestParam(value = "token") String token, HttpServletResponse response) { String userId = authService.getUserFromToken(token, response); GameState g = gameController.createBaseGame(); gameController.addUserToGame(userId, g.getId()); return getGame(g.getId(), token, response); } @RequestMapping(value = "/move", method = { RequestMethod.GET, RequestMethod.POST }) public GameState move( @RequestParam(value = "id") String gameId, @RequestParam(value = "action") String action, @RequestParam(value = "sourceCard", required = false) Long sourceCard, @RequestParam(value = "targetCard", required = false) Long targetCard, @RequestParam(value = "targetPlayer", required = false) Long targetPlayer, @RequestParam(value = "token") String token, HttpServletResponse response) throws IOException { String userId = authService.getUserFromToken(token, response); GameState g = gamesRepo.getGame(gameId, true); if (!userId.equalsIgnoreCase(g.getCurrentPlayer().getUserId())) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "You are not the current player"); return null; } else { Action a = GameController.buildAction(g, action); if (targetPlayer != null) { for (Player p : g.getPlayers()) { if (p.getId().equals(targetPlayer)) { a.setTargetPlayer(p); break; } } if (a.getTargetPlayer() == null) { throw new IllegalStateException( "Unable to find target player"); } } if (sourceCard != null) { for (Card c : a.getSourcePlayer().getHand()) { if (c instanceof ActualCard) { ActualCard c2 = (ActualCard) c; if (sourceCard.equals(c2.getId())) { a.setSourceCard(c2); break; } } } if (a.getSourceCard() == null) { throw new IllegalStateException( "Unable to find source card"); } } if (targetCard != null) { for (Card c : g.getAllCards()) { if (c instanceof ActualCard) { ActualCard c2 = (ActualCard) c; if (targetCard.equals(c2.getId())) { a.setTargetCard(c2); break; } } } if (a.getTargetCard() == null) { throw new IllegalStateException( "Unable to find target card"); } } gameController.doAction(g, a); gamesRepo.save(g); return getGame(gameId, token, response); } } }
cf582a8459c9b09f761a30af31bac1d9a38b577a
d66deb13b115a9b1afea67cada5a0fe85b947afd
/src/com/openrubicon/items/classes/sockets/enchants/Reinforced.java
4ca185c8f81db7031e26863d4cc656f549967248
[ "MIT" ]
permissive
OpenRubiconProject/rrpg-items
df04fb96cd2ef68d59e48827dfe288caadac0eb7
b35259ec2b5da58893a2d92ceaeef64e8df31b5d
refs/heads/master
2021-08-23T03:29:14.317010
2017-12-02T22:36:31
2017-12-02T22:36:31
103,776,382
0
0
null
null
null
null
UTF-8
Java
false
false
1,480
java
package com.openrubicon.items.classes.sockets.enchants; import com.openrubicon.core.helpers.Helpers; import com.openrubicon.core.helpers.MaterialGroups; import com.openrubicon.items.classes.sockets.Socket; import org.bukkit.Material; import java.util.HashMap; import java.util.HashSet; public class Reinforced extends Socket { private int armor = 1; @Override public String getKey() { return "reinforced"; } @Override public HashSet<Material> getMaterials() { return MaterialGroups.ARMOR; } @Override public String getName() { return "Reinforced"; } @Override public String getDescription() { return "Increases your chance of blocking an attack"; } @Override public boolean generate() { super.generate(); double min = 0; double max = (this.getItemSpecs().getPower() / 2) * this.getItemSpecs().getRarity(); this.armor = (int)Helpers.scale(Helpers.randomDouble(min, max), min, max, 1, 8); if(this.armor < 1) this.armor = 1; return true; } @Override public boolean save() { this.getSocketProperties().addInteger("armor", this.armor); return super.save(); } @Override public boolean load() { super.load(); this.armor = this.getSocketProperties().getInteger("armor"); return true; } public int getArmor() { return armor; } }
e69a921cdf024cfc87ec154b8563b86d1a0330e1
03989945a3cf65cab1d37b59b2b43b4a321d2da4
/culcleasing/src/com/tenwa/culc/dao1/.svn/text-base/ConditionDao1.java.svn-base
c02d091e88f7f08d426711e0606da7edc5f17902
[]
no_license
kevinblue/culcleasing
304d5421dd5bc0f6a42db67ed6977900ad64bd39
f6e53f0d27184ae33fdd44088a3aca356437ab7a
refs/heads/master
2020-03-17T10:42:19.969881
2018-05-15T14:39:14
2018-05-15T14:39:14
133,522,317
0
0
null
null
null
null
GB18030
Java
false
false
31,419
/** * com.tenwa.culc.dao */ package com.tenwa.culc.dao1; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.log4j.Logger; import com.tenwa.culc.bean.ConditionBean; import com.tenwa.culc.service.SqlGenerateUtil; import com.tenwa.culc.service1.SqlGenerateUtil1; import com.tenwa.culc.util.ERPDataSource; import com.tenwa.log.LogWriter; /** * 交易结构Dao操作 * * @author Jaffe * * Date:Jun 27, 2011 2:33:39 PM Email:[email protected] */ public class ConditionDao1 { private static Logger log = Logger.getLogger(ConditionDao1.class); // 公共参数 private ResultSet rs = null; /** * 将商务条件Bean插入proj_condition_temp表 * * @param conditionBean * @return * @throws SQLException */ public int insertConditionBeanIntoTempTable(ConditionBean conditionBean) throws SQLException { int flag = 0; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = SqlGenerateUtil .generateInsertProjConditionTempSql(conditionBean); LogWriter.logDebug("保存上传ConditionBean:" + sqlStr); // log.debug("___________" + sqlStr); flag = erpDataSource.executeUpdate(sqlStr); if (log.isDebugEnabled()) { log.debug("ConditionDao执行操作,影响结果:" + flag + "___Sql:" + sqlStr); } // 3.关闭资源 erpDataSource.close(); // 5.返回 return flag; } /** * 更新proj_condition_temp里数据 * * @param conditionBean * @return * @throws SQLException */ public int updateConditionBeanInTempTable(ConditionBean conditionBean) throws SQLException { int flag = 0; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = SqlGenerateUtil .generateUpdateProjConditionTempSql(conditionBean); log.debug("___________" + sqlStr); flag = erpDataSource.executeUpdate(sqlStr); if (log.isDebugEnabled()) { log.debug("ConditionDao执行Update操作,影响结果:" + flag + "___Sql:" + sqlStr); } // 3.关闭资源 erpDataSource.close(); // 5.返回 return flag; } /** * 判断proj_id\doc_id 在proj_condition_temp是否存在,存在返回upd、不存在返回add * * @param proj_id * @param doc_id * @return * @throws SQLException */ public String judgeItemExist(String proj_id, String doc_id) throws SQLException { String resultVal = ""; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "select id from proj_condition_temp where proj_id='" + proj_id + "' and doc_id='" + doc_id + "'"; rs = erpDataSource.executeQuery(sqlStr); if (rs.next()) { resultVal = "upd"; } else { resultVal = "add"; } // 3.关闭资源 erpDataSource.close(); return resultVal; } /** * 根据proj_id\doc_id从proj_condition_temp查找属性加载到Bean * * @param proj_id * @param doc_id * @return * @throws SQLException */ public ConditionBean loadConditionBeanByKey(ConditionBean conditionBean) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = SqlGenerateUtil1.generateSelectCondTemp(conditionBean .getProj_id(), conditionBean.getDoc_id()); rs = erpDataSource.executeQuery(sqlStr); if (rs.next()) { conditionBean.setTax_type(rs.getString("tax_type")); conditionBean.setTax_type_invoice(rs.getString("tax_type_invoice")); } // 3.关闭资源 erpDataSource.close(); return conditionBean; } public ConditionBean loadConditionBeanByKey1(String proj_id) throws SQLException { ConditionBean conditionBean = new ConditionBean(); conditionBean.setProj_id(proj_id); // conditionBean.setDoc_id(doc_id); // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = SqlGenerateUtil.generateSelectCondTemp1(proj_id); rs = erpDataSource.executeQuery(sqlStr); if (rs.next()) { conditionBean.setEquip_amt(rs.getString("equip_amt")); conditionBean.setCurrency(rs.getString("currency")); conditionBean.setLease_money(rs.getString("lease_money")); conditionBean.setFirst_payment_ratio(rs .getString("first_payment_ratio")); conditionBean.setFirst_payment(rs.getString("first_payment")); conditionBean.setCaution_money_ratio(rs .getString("caution_money_ratio")); conditionBean.setCaution_money(rs.getString("caution_money")); conditionBean.setActual_fund(rs.getString("actual_fund")); conditionBean.setActual_fund_ratio(rs .getString("actual_fund_ratio")); conditionBean.setHandling_charge_ratio(rs .getString("handling_charge_ratio")); conditionBean.setHandling_charge(rs.getString("handling_charge")); // ===22== conditionBean.setManagement_fee(rs.getString("management_fee")); conditionBean.setNominalprice(rs.getString("nominalprice")); conditionBean.setReturn_ratio(rs.getString("return_ratio")); conditionBean.setReturn_amt(rs.getString("return_amt")); conditionBean.setRate_subsidy(rs.getString("rate_subsidy")); conditionBean.setBefore_interest(rs.getString("before_interest")); conditionBean.setBefore_interest_type(rs .getString("before_interest_type")); conditionBean.setDiscount_rate(rs.getString("discount_rate")); conditionBean.setConsulting_fee_out(rs .getString("consulting_fee_out")); // ==33== conditionBean.setConsulting_fee_in(rs .getString("consulting_fee_in")); conditionBean.setOther_income(rs.getString("other_income")); conditionBean.setOther_expenditure(rs .getString("other_expenditure")); conditionBean.setIncome_number(rs.getString("income_number")); conditionBean.setIncome_number_year(rs .getString("income_number_year")); conditionBean.setLease_term(rs.getString("lease_term")); conditionBean.setSettle_method(rs.getString("settle_method")); conditionBean.setPeriod_type(rs.getString("period_type")); // ==44== conditionBean.setRate_float_type(rs.getString("rate_float_type")); conditionBean.setRate_float_amt(rs.getString("rate_float_amt")); conditionBean.setAdjust_style(rs.getString("adjust_style")); conditionBean.setYear_rate(rs.getString("year_rate")); conditionBean.setPena_rate(rs.getString("pena_rate")); conditionBean.setStart_date(rs.getString("start_date")); conditionBean.setIncome_day(rs.getString("income_day")); // ==55== conditionBean.setEnd_date(rs.getString("end_date")); conditionBean.setRent_start_date(rs.getString("rent_start_date")); conditionBean.setIrr(rs.getString("irr")); conditionBean.setPlan_irr(rs.getString("plan_irr")); conditionBean.setInsure_type(rs.getString("insure_type")); conditionBean.setInto_batch(rs.getString("into_batch")); conditionBean.setInsure_money(rs.getString("insure_money")); conditionBean.setFree_defa_inter_day(rs .getString("free_defa_inter_day")); // ==66== conditionBean.setAssets_value(rs.getString("assets_value")); conditionBean.setAssess_adjust(rs.getString("assess_adjust")); conditionBean.setRatio_param(rs.getString("ratio_param")); // ==77== conditionBean.setInvoice_type(rs.getString("invoice_type")); conditionBean.setStandardF(rs.getString("StandardF")); conditionBean.setStandardIrr(rs.getString("StandardIrr")); // ==88== conditionBean.setInsure_pay_type(rs.getString("Insure_pay_type")); } // 3.关闭资源 erpDataSource.close(); return conditionBean; } /** * 更新proj_condition_temp表plan_irr * * @param proj_id * @param doc_id * @param markirr * @return * @throws SQLException */ public int updateConditionTempPlanIrrOper(String proj_id, String doc_id, String markirr) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "update proj_condition_temp set plan_irr=" + markirr + " where proj_id='" + proj_id + "' and doc_id = '" + doc_id + "' "; sqlStr += " update proj_condition_temp set irr=" + markirr + " where proj_id='" + proj_id + "' and doc_id = '" + doc_id + "' and isnull(irr,0)<=0"; int res = erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); return res; } /** * 删除指定的交易结构临时表数据 * * @param proj_id * @param doc_id * @throws SQLException */ public void delProjConditionTempData(String proj_id, String doc_id) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "delete from proj_condition_temp where proj_id='" + proj_id + "' and doc_id='" + doc_id + "'"; erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); } /** * 流程初始化判断数据是否存在 * * @param proj_id * @param doc_id * @return * @throws SQLException */ public boolean judgeDataExist(String proj_id, String doc_id) throws SQLException { boolean flag = false; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "select id from proj_condition_temp where proj_id='" + proj_id + "' and doc_id='" + doc_id + "'"; rs = erpDataSource.executeQuery(sqlStr); flag = rs.next(); // 3.关闭资源 erpDataSource.close(); return flag; } /** * 流程初始化Proj_condition_temp表数据 * * @param proj_id * @param doc_id * @throws SQLException */ public void copyData2Temp(String proj_id, String doc_id) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = ""; StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder .append("update proj_condition_temp set tax_type=proj_condition.tax_type,tax_type_invoice=proj_condition.tax_type_invoice from proj_condition_temp left join proj_condition on proj_condition_temp.proj_id=proj_condition.proj_id" + " where proj_condition_temp.proj_id='" + proj_id + "' and proj_condition_temp.doc_id='" + doc_id + "' and isnull(proj_condition_temp.tax_type,'')=''"); sqlStr = sqlBuilder.toString(); System.out.println("sssss" + sqlStr); erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); } /** * 更新tax_type字段 * * @param proj_id * @param doc_id * @throws SQLException */ public int updateTaxType(ConditionBean conditionBean) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = ""; StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("update proj_condition_temp set tax_type='" + conditionBean.getTax_type() + "',tax_type_invoice='"+conditionBean.getTax_type_invoice()+"' where proj_id='" + conditionBean.getProj_id() + "' and doc_id='" + conditionBean.getDoc_id() + "'"); sqlStr = sqlBuilder.toString(); System.out.println("sssss" + sqlStr); int res = erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); return res; } /** * 更新tax_type字段 * * @param proj_id * @param doc_id * @throws SQLException */ public int updateTaxTypeToContractTemp(ConditionBean conditionBean) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = ""; StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("update contract_condition_temp set tax_type='" + conditionBean.getTax_type() + "',tax_type_invoice='"+conditionBean.getTax_type_invoice()+"' where contract_id='" + conditionBean.getContract_id() + "' and doc_id='" + conditionBean.getDoc_id() + "'"); sqlStr = sqlBuilder.toString(); System.out.println("sssss" + sqlStr); int res = erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); return res; } /** * 判断数据是否存在 * * @param contract_id * @param doc_id * @return * @throws SQLException */ public boolean judgeItemContractExist(String contract_id, String doc_id) throws SQLException { boolean flag = false; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "select id from contract_condition_temp where contract_id='" + contract_id + "' and doc_id='" + doc_id + "'"; rs = erpDataSource.executeQuery(sqlStr); flag = rs.next(); // 3.关闭资源 erpDataSource.close(); return flag; } /** * 数据拷贝 * * @param contract_id * @param proj_id * @param doc_id * @throws SQLException */ public void copyData2ContractTemp(String contract_id, String proj_id, String doc_id) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); ResultSet rs = null; // 2.拼接sql,执行插入 String sqlStr = ""; String tax_type = ""; String tax_type_invoice = ""; String sqlstr1 = "select tax_type,tax_type_invoice from proj_condition where proj_id='" + proj_id + "'"; rs = erpDataSource.executeQuery(sqlstr1); if (rs.next()) { tax_type = rs.getString("tax_type"); tax_type_invoice=rs.getString("tax_type_invoice"); } StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("update contract_condition_temp set tax_type='" + tax_type + "',tax_type_invoice='"+tax_type_invoice+"' where contract_id='" + contract_id + "' and doc_id='" + doc_id + "' and isnull(tax_type,'')=''"); sqlStr = sqlBuilder.toString(); System.out.println("测试输出" + sqlStr); erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); } /** * 加载合同交易结构 * * @param contract_id * @param doc_id * @return * @throws SQLException */ public ConditionBean loadConditionContractBeanByKey( ConditionBean conditionBean) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = SqlGenerateUtil1.generateSelectCondContractTemp( conditionBean.getContract_id(), conditionBean.getDoc_id()); rs = erpDataSource.executeQuery(sqlStr); if (rs.next()) { conditionBean.setTax_type(rs.getString("tax_type")); conditionBean.setTax_type_invoice(rs.getString("tax_type_invoice")); } // 3.关闭资源 erpDataSource.close(); return conditionBean; } /** * 加载合同交易结构 - 正式 * * @param contract_id * @return * @throws SQLException */ public ConditionBean loadFactConditionContractBeanByKey(String contract_id) throws SQLException { ConditionBean conditionBean = new ConditionBean(); conditionBean.setContract_id(contract_id); // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = SqlGenerateUtil.generateSelectCondContract(contract_id); rs = erpDataSource.executeQuery(sqlStr); if (rs.next()) { conditionBean.setEquip_amt(rs.getString("equip_amt")); conditionBean.setCurrency(rs.getString("currency")); conditionBean.setLease_money(rs.getString("lease_money")); conditionBean.setFirst_payment_ratio(rs .getString("first_payment_ratio")); conditionBean.setFirst_payment(rs.getString("first_payment")); conditionBean.setCaution_money_ratio(rs .getString("caution_money_ratio")); conditionBean.setCaution_money(rs.getString("caution_money")); conditionBean.setActual_fund(rs.getString("actual_fund")); conditionBean.setActual_fund_ratio(rs .getString("actual_fund_ratio")); conditionBean.setHandling_charge_ratio(rs .getString("handling_charge_ratio")); conditionBean.setHandling_charge(rs.getString("handling_charge")); // ===22== conditionBean.setManagement_fee(rs.getString("management_fee")); conditionBean.setNominalprice(rs.getString("nominalprice")); conditionBean.setReturn_ratio(rs.getString("return_ratio")); conditionBean.setReturn_amt(rs.getString("return_amt")); conditionBean.setRate_subsidy(rs.getString("rate_subsidy")); conditionBean.setBefore_interest(rs.getString("before_interest")); conditionBean.setBefore_interest_type(rs .getString("before_interest_type")); conditionBean.setDiscount_rate(rs.getString("discount_rate")); conditionBean.setConsulting_fee_out(rs .getString("consulting_fee_out")); // ==33== conditionBean.setConsulting_fee_in(rs .getString("consulting_fee_in")); conditionBean.setOther_income(rs.getString("other_income")); conditionBean.setOther_expenditure(rs .getString("other_expenditure")); conditionBean.setIncome_number(rs.getString("income_number")); conditionBean.setIncome_number_year(rs .getString("income_number_year")); conditionBean.setLease_term(rs.getString("lease_term")); conditionBean.setSettle_method(rs.getString("settle_method")); conditionBean.setPeriod_type(rs.getString("period_type")); // ==44== conditionBean.setRate_float_type(rs.getString("rate_float_type")); conditionBean.setRate_float_amt(rs.getString("rate_float_amt")); conditionBean.setAdjust_style(rs.getString("adjust_style")); conditionBean.setYear_rate(rs.getString("year_rate")); conditionBean.setPena_rate(rs.getString("pena_rate")); conditionBean.setStart_date(rs.getString("start_date")); conditionBean.setIncome_day(rs.getString("income_day")); // ==55== conditionBean.setEnd_date(rs.getString("end_date")); conditionBean.setRent_start_date(rs.getString("rent_start_date")); conditionBean.setIrr(rs.getString("irr")); conditionBean.setPlan_irr(rs.getString("plan_irr")); conditionBean.setInsure_type(rs.getString("insure_type")); conditionBean.setInto_batch(rs.getString("into_batch")); conditionBean.setInsure_money(rs.getString("insure_money")); conditionBean.setFree_defa_inter_day(rs .getString("free_defa_inter_day")); // ==66== conditionBean.setAssets_value(rs.getString("assets_value")); conditionBean.setAssess_adjust(rs.getString("assess_adjust")); conditionBean.setRatio_param(rs.getString("ratio_param")); // ==77== conditionBean.setInvoice_type(rs.getString("invoice_type")); conditionBean.setStandardF(rs.getString("StandardF")); conditionBean.setStandardIrr(rs.getString("StandardIrr")); } // 3.关闭资源 erpDataSource.close(); return conditionBean; } /** * 修改合同交易结构临时表 * * @param conditionBean * @return * @throws SQLException */ public int updateConditionContractBeanInTempTable( ConditionBean conditionBean) throws SQLException { int flag = 0; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = SqlGenerateUtil .generateUpdateProjConditionContractTempSql(conditionBean); flag = erpDataSource.executeUpdate(sqlStr); if (log.isDebugEnabled()) { log.debug("ConditionDao执行Update操作,影响结果:" + flag + "___Sql:" + sqlStr); } // 3.关闭资源 erpDataSource.close(); // 5.返回 return flag; } /** * * @param contract_id * @param doc_id * @param markirr * @return * @throws SQLException */ public int updateConditionContractTempPlanIrrOper(String contract_id, String doc_id, String markirr) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "update contract_condition_temp set plan_irr=" + markirr + " where contract_id='" + contract_id + "' and doc_id = '" + doc_id + "' "; int res = erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); return res; } /** * 删除合同交易结构临时表 * * @param contract_id * @param doc_id * @throws SQLException */ public void delProjConditionContractTempData(String contract_id, String doc_id) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "delete from contract_condition_temp where contract_id='" + contract_id + "' and doc_id='" + doc_id + "'"; erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); } /** * 保存合同交易结构临时表 * * @param conditionBean * @return * @throws SQLException */ public int insertConditionContractBeanIntoTempTable( ConditionBean conditionBean) throws SQLException { int flag = 0; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = SqlGenerateUtil .generateInsertProjConditionContractTempSql(conditionBean); LogWriter .logDebug("ConditionDao执行操作,影响结果:" + flag + "___Sql:" + sqlStr); flag = erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); // 5.返回 return flag; } /** * 判断合同系列表中数据是否存在 * * @param contract_id * @param doc_id * @return * @throws SQLException */ public boolean judgeContractDataExist(String contract_id, String doc_id) throws SQLException { boolean flag = false; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "select id from contract_condition_temp where contract_id='" + contract_id + "' and doc_id='" + doc_id + "'"; rs = erpDataSource.executeQuery(sqlStr); flag = rs.next(); // 3.关闭资源 erpDataSource.close(); return flag; } /** * 合同交易结构数据拷贝 * * @param contract_id * @param doc_id * @throws SQLException */ public void copyData2ContractTemp(String contract_id, String doc_id) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = ""; StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder .append("update contract_condition_temp set tax_type=cc.tax_type from contract_condition_temp temp " + "left join contract_condition cc on cc.contract_id=temp.contract_id"); sqlBuilder.append(" where temp.contract_id='" + contract_id + "' and temp.doc_id='" + doc_id + "' and isnull(temp.tax_type,'')=''"); sqlStr = sqlBuilder.toString(); System.out.println("测试:" + sqlStr); erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); } /** * 删除项目交易结构临时表 * * @param proj_id * @param doc_id * @throws SQLException */ public void deleteProjConditionTempData(String proj_id, String doc_id) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "Delete from proj_condition_temp where proj_id='" + proj_id + "' and doc_id='" + doc_id + "'"; erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); } /** * 通过ContractId加载到Bean * * @param contract_id * @return * @throws SQLException */ public ConditionBean loadConditionContractBeanByContractId( String contract_id) throws SQLException { ConditionBean conditionBean = new ConditionBean(); conditionBean.setContract_id(contract_id); // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = SqlGenerateUtil.generateSelectCondContract(contract_id); rs = erpDataSource.executeQuery(sqlStr); if (rs.next()) { conditionBean.setEquip_amt(rs.getString("equip_amt")); conditionBean.setCurrency(rs.getString("currency")); conditionBean.setLease_money(rs.getString("lease_money")); conditionBean.setFirst_payment_ratio(rs .getString("first_payment_ratio")); conditionBean.setFirst_payment(rs.getString("first_payment")); conditionBean.setCaution_money_ratio(rs .getString("caution_money_ratio")); conditionBean.setCaution_money(rs.getString("caution_money")); conditionBean.setActual_fund(rs.getString("actual_fund")); conditionBean.setActual_fund_ratio(rs .getString("actual_fund_ratio")); conditionBean.setHandling_charge_ratio(rs .getString("handling_charge_ratio")); conditionBean.setHandling_charge(rs.getString("handling_charge")); // ===22== conditionBean.setManagement_fee(rs.getString("management_fee")); conditionBean.setNominalprice(rs.getString("nominalprice")); conditionBean.setReturn_ratio(rs.getString("return_ratio")); conditionBean.setReturn_amt(rs.getString("return_amt")); conditionBean.setRate_subsidy(rs.getString("rate_subsidy")); conditionBean.setBefore_interest(rs.getString("before_interest")); conditionBean.setBefore_interest_type(rs .getString("before_interest_type")); conditionBean.setDiscount_rate(rs.getString("discount_rate")); conditionBean.setConsulting_fee_out(rs .getString("consulting_fee_out")); // ==33== conditionBean.setConsulting_fee_in(rs .getString("consulting_fee_in")); conditionBean.setOther_income(rs.getString("other_income")); conditionBean.setOther_expenditure(rs .getString("other_expenditure")); conditionBean.setIncome_number(rs.getString("income_number")); conditionBean.setIncome_number_year(rs .getString("income_number_year")); conditionBean.setLease_term(rs.getString("lease_term")); conditionBean.setSettle_method(rs.getString("settle_method")); conditionBean.setPeriod_type(rs.getString("period_type")); // ==44== conditionBean.setRate_float_type(rs.getString("rate_float_type")); conditionBean.setRate_float_amt(rs.getString("rate_float_amt")); conditionBean.setAdjust_style(rs.getString("adjust_style")); conditionBean.setYear_rate(rs.getString("year_rate")); conditionBean.setPena_rate(rs.getString("pena_rate")); conditionBean.setStart_date(rs.getString("start_date")); conditionBean.setIncome_day(rs.getString("income_day")); // ==55== conditionBean.setEnd_date(rs.getString("end_date")); conditionBean.setRent_start_date(rs.getString("rent_start_date")); conditionBean.setPlan_irr(rs.getString("plan_irr")); conditionBean.setInsure_type(rs.getString("insure_type")); conditionBean.setInto_batch(rs.getString("into_batch")); conditionBean.setInsure_money(rs.getString("insure_money")); conditionBean.setFree_defa_inter_day(rs .getString("free_defa_inter_day")); // ==66== conditionBean.setAssets_value(rs.getString("assets_value")); conditionBean.setAssess_adjust(rs.getString("assess_adjust")); conditionBean.setRatio_param(rs.getString("ratio_param")); // ==77== conditionBean.setInvoice_type(rs.getString("invoice_type")); // conditionBean.setStandardF(rs.getString("StandardF")); // conditionBean.setStandardIrr(rs.getString("StandardIrr")); conditionBean.setInsure_pay_type(rs.getString("insure_pay_type")); } // 3.关闭资源 erpDataSource.close(); return conditionBean; } /** * 判断[Begin_info_temp是否存在数据] * * @param contract_id * @param begin_id * @param doc_id * @return * @throws SQLException */ public boolean judgeBeginDataExist(String contract_id, String begin_id, String doc_id) throws SQLException { boolean flag = false; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "select id from begin_info_temp where contract_id='" + contract_id + "' and begin_id='" + begin_id + "' and doc_id='" + doc_id + "'"; rs = erpDataSource.executeQuery(sqlStr); flag = rs.next(); // 3.关闭资源 erpDataSource.close(); return flag; } /** * 拷贝[begin_info]拷贝到[begin_info_temp] * * @param contract_id * @param begin_id * @param doc_id * @throws SQLException */ public void copyBeginData2Temp(String contract_id, String begin_id, String doc_id) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = ""; StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder .append("update begin_info_temp set tax_type=bi.tax_type,tax_type_invoice=bi.tax_type_invoice from begin_info_temp temp left join begin_info bi on bi.begin_id=temp.begin_id where temp.begin_id='" + begin_id + "' and temp.doc_id='" + doc_id + "'"); sqlStr = sqlBuilder.toString(); LogWriter.logSqlStr("租金变更 -> 更新tax_type", sqlStr); //erpDataSource.executeUpdate(sqlStr); //此语句无需执行 // 3.关闭资源 erpDataSource.close(); } /** * 判断当前合同是否多次起租 * * @param contractId * @return * @throws SQLException */ public boolean judgeBeginType(String contractId) throws SQLException { boolean resultVal = false; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "Select id from contract_begin_info where contract_id='" + contractId + "' and is_more='是'"; rs = erpDataSource.executeQuery(sqlStr); resultVal = rs.next(); // 3.关闭资源 erpDataSource.close(); return resultVal; } /** * 起租流程初始化签约审批数据到起租[begin_info_temp]信息 * * @param contract_id * @param begin_id * @param doc_id * @throws SQLException */ public void copyContract2BeginData2Temp(String contract_id, String begin_id, String doc_id) throws SQLException { // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = ""; StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder .append("update begin_info_temp set tax_type =cc.tax_type,tax_type_invoice=cc.tax_type_invoice from begin_info_temp bi left join contract_condition cc on cc.contract_id=bi.contract_id where bi.contract_id='" + contract_id + "' and bi.begin_id='" + begin_id + "' and bi.doc_id='" + doc_id + "' and isnull(bi.tax_type,'')=''"); sqlStr = sqlBuilder.toString(); System.out.println("啊啊啊啊啊啊啊" + sqlStr); erpDataSource.executeUpdate(sqlStr); // 3.关闭资源 erpDataSource.close(); } /** * 查询项目已使用项目金额 * * @param contractId * @return * @throws SQLException */ public String getUsedMoney(String contractId) throws SQLException { String usedMoney = ""; // 1.获取连接、会话 ERPDataSource erpDataSource = new ERPDataSource(); // 2.拼接sql,执行插入 String sqlStr = "Select [dbo].[T_getSumEquipAmt]('" + contractId + "') as used_money"; rs = erpDataSource.executeQuery(sqlStr); if (rs.next()) { usedMoney = rs.getString("used_money"); } // 3.关闭资源 erpDataSource.close(); return usedMoney; } public static void main(String[] args) { System.out.println(String.valueOf(Double.parseDouble("10.1234567898"))); } }
b51977029c51562401a78a2ca4b36fa2615389c2
2cec4416d8cdbe9f2703a15062907f456290625d
/jtrace-api/src/main/java/com/github/wei/jtrace/api/exception/TransformException.java
c8a59f6f87f732977e48cf57f140e3d1867ff4e2
[]
no_license
kingking888/jtrace-1
23b9bbe331ad6e1711c5210efe28e364c1ec6117
57689f91617587f93f87d0a70a74febbc83ed988
refs/heads/master
2023-05-14T18:38:40.249782
2020-03-24T05:57:35
2020-03-24T05:57:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
616
java
package com.github.wei.jtrace.api.exception; public class TransformException extends Exception { /** * Create a new BeanInstantiationException. * @param msg the offending bean class * @param msg the detail message */ public TransformException(String msg) { super(msg); } public TransformException(Throwable t) { super(t); } /** * Create a new BeanInstantiationException. * @param msg the detail message * @param cause the root cause */ public TransformException(String msg, Throwable cause) { super( msg, cause); } }
c40ea79feb3ee58870bde55e46e7402a557a61dd
c67895f096d928c23748dbef8a540954335a62e1
/wx-util/src/main/java/org/gy/framework/weixin/config/WeiXinConfig.java
2e22e4b6b95e9f85896956cf1e31f5497988ea69
[]
no_license
zhyisme/gy-wx
10c069120e62c9c766081b09a2162bea6f4c2007
cad4844f6b0b0ff675e4732cbd36159f33ce5097
refs/heads/master
2021-01-18T19:09:25.092875
2017-01-23T06:17:15
2017-01-23T06:17:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,167
java
package org.gy.framework.weixin.config; import java.io.Serializable; import java.util.Properties; /** * 微信配置 */ public class WeiXinConfig implements Serializable { private static final long serialVersionUID = 7524964169167796587L; /** * 微信appID配置标识 */ public static final String CONFIG_APPID_KEY = WeiXinConfig.class.getName() + ".appId"; /** * 微信appsecret配置标识 */ public static final String CONFIG_SECRET_KEY = WeiXinConfig.class.getName() + ".secret"; /** * 有效时间配置标识 */ public static final String CONFIG_EXPIRE_TIME_KEY = WeiXinConfig.class.getName() + ".expireTime"; /** * 授权类型配置标识 */ public static final String CONFIG_GRANT_TYPE_KEY = WeiXinConfig.class.getName() + ".grantType"; /** * 授权类型默认值,获取access_token填写client_credential */ public static final String DEFAULT_GRANT_TYPE = "client_credential"; /** * 默认超时时间 */ public static final int DEFAULT_EXPIRE_TIME = 7200; /** * 全量配置 */ private Properties properties; /** * 微信appId */ private String appId; /** * 微信appSecret */ private String secret; /** * 有效时间 */ private Integer expireTime; /** * 授权类型 */ private String grantType; /** * 获取微信appId * * @return appId 微信appId */ public String getAppId() { return appId; } /** * 设置微信appId * * @param appId 微信appId */ public void setAppId(String appId) { this.appId = appId; } /** * 获取微信appSecret * * @return secret 微信appSecret */ public String getSecret() { return secret; } /** * 设置微信appSecret * * @param secret 微信appSecret */ public void setSecret(String secret) { this.secret = secret; } /** * 获取有效时间 * * @return expireTime 有效时间 */ public Integer getExpireTime() { return expireTime; } /** * 设置有效时间 * * @param expireTime 有效时间 */ public void setExpireTime(Integer expireTime) { this.expireTime = expireTime; } /** * 获取授权类型 * * @return grantType 授权类型 */ public String getGrantType() { return grantType; } /** * 设置授权类型 * * @param grantType 授权类型 */ public void setGrantType(String grantType) { this.grantType = grantType; } /** * 获取全量配置 * * @return properties 全量配置 */ public Properties getProperties() { return properties; } /** * 设置全量配置 * * @param properties 全量配置 */ public void setProperties(Properties properties) { this.properties = properties; } }
945a5ab9354a51d1d3ea98aa838da410d940e7ed
40d5b69e825c4606093dcba3630cfa2abbe6d79e
/src/com/sleepycat/je/log/FileManager.java
c61c9cb83c16a4c559bb1df5cca3b7a71d064705
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
bantudb/je
75776f51ee8642f5deea510b1028e0918038186d
bf2710344e74f07a54e7b5fa05531c031b0ddaed
refs/heads/master
2021-01-19T23:49:29.480509
2017-04-22T01:14:01
2017-04-22T01:14:01
89,035,623
1
0
null
null
null
null
UTF-8
Java
false
false
120,931
java
/*- * Copyright (C) 2002, 2017, Oracle and/or its affiliates. All rights reserved. * * This file was distributed by Oracle as part of a version of Oracle Berkeley * DB Java Edition made available at: * * http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html * * Please see the LICENSE file included in the top-level directory of the * appropriate version of Oracle Berkeley DB Java Edition for a copy of the * license and additional information. */ package com.sleepycat.je.log; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_BYTES_READ_FROM_WRITEQUEUE; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_BYTES_WRITTEN_FROM_WRITEQUEUE; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_FILE_OPENS; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_LOG_FSYNCS; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_OPEN_FILES; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_RANDOM_READS; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_RANDOM_READ_BYTES; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_RANDOM_WRITES; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_RANDOM_WRITE_BYTES; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_READS_FROM_WRITEQUEUE; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_SEQUENTIAL_READS; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_SEQUENTIAL_READ_BYTES; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_SEQUENTIAL_WRITES; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_SEQUENTIAL_WRITE_BYTES; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_WRITEQUEUE_OVERFLOW; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_WRITEQUEUE_OVERFLOW_FAILURES; import static com.sleepycat.je.log.LogStatDefinition.FILEMGR_WRITES_FROM_WRITEQUEUE; import static com.sleepycat.je.log.LogStatDefinition.GRPCMGR_FSYNC_MAX_TIME; import static com.sleepycat.je.log.LogStatDefinition.GRPCMGR_FSYNC_TIME; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.EnvironmentFailureException; import com.sleepycat.je.EnvironmentLockedException; import com.sleepycat.je.LogWriteException; import com.sleepycat.je.StatsConfig; import com.sleepycat.je.ThreadInterruptedException; import com.sleepycat.je.config.EnvironmentParams; import com.sleepycat.je.dbi.DbConfigManager; import com.sleepycat.je.dbi.EnvironmentFailureReason; import com.sleepycat.je.dbi.EnvironmentImpl; import com.sleepycat.je.log.entry.FileHeaderEntry; import com.sleepycat.je.log.entry.LogEntry; import com.sleepycat.je.utilint.DbLsn; import com.sleepycat.je.utilint.HexFormatter; import com.sleepycat.je.utilint.IntStat; import com.sleepycat.je.utilint.LoggerUtils; import com.sleepycat.je.utilint.LongMaxZeroStat; import com.sleepycat.je.utilint.LongStat; import com.sleepycat.je.utilint.RelatchRequiredException; import com.sleepycat.je.utilint.StatGroup; /** * The FileManager presents the abstraction of one contiguous file. It doles * out LSNs. */ public class FileManager { public enum FileMode { READ_MODE("r", false), READWRITE_MODE("rw", true), READWRITE_ODSYNC_MODE("rwd", true), READWRITE_OSYNC_MODE("rws", true); private String fileModeValue; private boolean isWritable; private FileMode(String fileModeValue, boolean isWritable) { this.fileModeValue = fileModeValue; this.isWritable = isWritable; } public String getModeValue() { return fileModeValue; } public boolean isWritable() { return isWritable; } } private static final boolean DEBUG = false; /* * The number of writes that have been performed. * * public so that unit tests can diddle them. */ public static long WRITE_COUNT = 0; /* * The write count value where we should stop or throw. */ public static long STOP_ON_WRITE_COUNT = Long.MAX_VALUE; /* * If we're throwing, then throw on write #'s WRITE_COUNT through * WRITE_COUNT + N_BAD_WRITES - 1 (inclusive). */ public static long N_BAD_WRITES = Long.MAX_VALUE; /* * If true, then throw an IOException on write #'s WRITE_COUNT through * WRITE_COUNT + N_BAD_WRITES - 1 (inclusive). */ public static boolean THROW_ON_WRITE = false; public static final String JE_SUFFIX = ".jdb"; // regular log files public static final String DEL_SUFFIX = ".del"; // cleaned files public static final String BAD_SUFFIX = ".bad"; // corrupt files private static final String LOCK_FILE = "je.lck";// lock file static final String[] DEL_SUFFIXES = { DEL_SUFFIX }; static final String[] JE_SUFFIXES = { JE_SUFFIX }; private static final String[] JE_AND_DEL_SUFFIXES = { JE_SUFFIX, DEL_SUFFIX }; /* * The suffix used to denote a file that is in the process of being * transferred during a network backup. The file may not have been * completely transferred, or its digest verified. */ public static final String TMP_SUFFIX = ".tmp"; /* * The suffix used to rename files out of the way, if they are being * retained during a backup. Note that the suffix is used in conjunction * with a backup number as described in <code>NetworkBackup</code> */ public static final String BUP_SUFFIX = ".bup"; /* May be set to false to speed unit tests. */ private boolean syncAtFileEnd = true; private final EnvironmentImpl envImpl; private final long maxFileSize; private final File dbEnvHome; private final File[] dbEnvDataDirs; /* True if .del files should be included in the list of log files. */ private boolean includeDeletedFiles = false; /* File cache */ private final FileCache fileCache; private FileCacheWarmer fileCacheWarmer; /* The channel and lock for the je.lck file. */ private RandomAccessFile lockFile; private FileChannel channel; private FileLock envLock; private FileLock exclLock; /* True if all files should be opened readonly. */ private final boolean readOnly; /* Handles onto log position */ private volatile long currentFileNum; // number of the current file private volatile long nextAvailableLsn; // the next LSN available private volatile long lastUsedLsn; // last LSN used in the current file private long prevOffset; // Offset to use for the previous pointer private boolean forceNewFile; // Force new file on next write /* endOfLog is used for writes and fsyncs to the end of the log. */ private final LogEndFileDescriptor endOfLog; /* * When we bump the LSNs over to a new file, we must remember the last LSN * of the previous file so we can set the prevOffset field of the file * header appropriately. We have to save it in a map because there's a time * lag between when we know what the last LSN is and when we actually do * the file write, because LSN bumping is done before we get a write * buffer. This map is keyed by file num->last LSN. */ private final Map<Long, Long> perFileLastUsedLsn; /* * True if we should use the Write Queue. This queue is enabled by default * and contains any write() operations which were attempted but would have * blocked because an fsync() or another write() was in progress at the * time. The operations on the Write Queue are later executed by the next * operation that is able to grab the fsync latch. File systems like ext3 * need this queue in order to achieve reasonable throughput since it * acquires an exclusive mutex on the inode during any IO operation * (seek/read/write/fsync). OS's like Windows and Solaris do not since * they are able to handle concurrent IO operations on a single file. */ private final boolean useWriteQueue; /* The starting size of the Write Queue. */ private final int writeQueueSize; /* * Use O_DSYNC to open JE log files. */ private final boolean useODSYNC; /* public for unit tests. */ public boolean VERIFY_CHECKSUMS = false; /** {@link EnvironmentParams#LOG_FSYNC_TIME_LIMIT}. */ private final int fSyncTimeLimit; /* * Non-0 means to use envHome/data001 through envHome/data00N for the * environment directories, where N is nDataDirs. Distribute *.jdb files * through dataNNN directories round-robin. */ private final int nDataDirs; /* * Last file to which any IO was done. */ long lastFileNumberTouched = -1; /* * Current file offset of lastFile. */ long lastFileTouchedOffset = 0; /* * For IO stats, this is a measure of what is "close enough" to constitute * a sequential IO vs a random IO. 1MB for now. Generally a seek within a * few tracks of the current disk track is "fast" and only requires a * single rotational latency. */ private static final long ADJACENT_TRACK_SEEK_DELTA = 1 << 20; /* * Used to detect unexpected file deletion. */ private final FileDeletionDetector fdd; /* * Stats */ final StatGroup stats; final LongStat nRandomReads; final LongStat nRandomWrites; final LongStat nSequentialReads; final LongStat nSequentialWrites; final LongStat nRandomReadBytes; final LongStat nRandomWriteBytes; final LongStat nSequentialReadBytes; final LongStat nSequentialWriteBytes; final IntStat nFileOpens; final IntStat nOpenFiles; final LongStat nBytesReadFromWriteQueue; final LongStat nBytesWrittenFromWriteQueue; final LongStat nReadsFromWriteQueue; final LongStat nWritesFromWriteQueue; final LongStat nWriteQueueOverflow; final LongStat nWriteQueueOverflowFailures; /* all fsyncs, includes those issued for group commit */ final LongStat nLogFSyncs; final LongStat nFSyncTime; final LongMaxZeroStat nFSyncMaxTime; /** * Set up the file cache and initialize the file manager to point to the * beginning of the log. * * @param dbEnvHome environment home directory * * @throws IllegalArgumentException via Environment ctor * * @throws EnvironmentLockedException via Environment ctor */ public FileManager(EnvironmentImpl envImpl, File dbEnvHome, boolean readOnly) throws EnvironmentLockedException { this.envImpl = envImpl; this.dbEnvHome = dbEnvHome; this.readOnly = readOnly; boolean success = false; stats = new StatGroup(LogStatDefinition.FILEMGR_GROUP_NAME, LogStatDefinition.FILEMGR_GROUP_DESC); nRandomReads = new LongStat(stats, FILEMGR_RANDOM_READS); nRandomWrites = new LongStat(stats, FILEMGR_RANDOM_WRITES); nSequentialReads = new LongStat(stats, FILEMGR_SEQUENTIAL_READS); nSequentialWrites = new LongStat(stats, FILEMGR_SEQUENTIAL_WRITES); nRandomReadBytes = new LongStat(stats, FILEMGR_RANDOM_READ_BYTES); nRandomWriteBytes = new LongStat(stats, FILEMGR_RANDOM_WRITE_BYTES); nSequentialReadBytes = new LongStat(stats, FILEMGR_SEQUENTIAL_READ_BYTES); nSequentialWriteBytes = new LongStat(stats, FILEMGR_SEQUENTIAL_WRITE_BYTES); nFileOpens = new IntStat(stats, FILEMGR_FILE_OPENS); nOpenFiles = new IntStat(stats, FILEMGR_OPEN_FILES); nBytesReadFromWriteQueue = new LongStat(stats, FILEMGR_BYTES_READ_FROM_WRITEQUEUE); nBytesWrittenFromWriteQueue = new LongStat(stats, FILEMGR_BYTES_WRITTEN_FROM_WRITEQUEUE); nReadsFromWriteQueue = new LongStat(stats, FILEMGR_READS_FROM_WRITEQUEUE); nWritesFromWriteQueue = new LongStat(stats, FILEMGR_WRITES_FROM_WRITEQUEUE); nWriteQueueOverflow = new LongStat(stats, FILEMGR_WRITEQUEUE_OVERFLOW); nWriteQueueOverflowFailures = new LongStat(stats, FILEMGR_WRITEQUEUE_OVERFLOW_FAILURES); nLogFSyncs = new LongStat(stats, FILEMGR_LOG_FSYNCS); nFSyncTime = new LongStat(stats, GRPCMGR_FSYNC_TIME); nFSyncMaxTime = new LongMaxZeroStat(stats, GRPCMGR_FSYNC_MAX_TIME); try { /* Read configurations. */ DbConfigManager configManager = envImpl.getConfigManager(); maxFileSize = configManager.getLong(EnvironmentParams.LOG_FILE_MAX); useWriteQueue = configManager.getBoolean( EnvironmentParams.LOG_USE_WRITE_QUEUE); writeQueueSize = configManager.getInt( EnvironmentParams.LOG_WRITE_QUEUE_SIZE); useODSYNC = configManager.getBoolean( EnvironmentParams.LOG_USE_ODSYNC); VERIFY_CHECKSUMS = configManager.getBoolean( EnvironmentParams.LOG_VERIFY_CHECKSUMS); fSyncTimeLimit = configManager.getDuration( EnvironmentParams.LOG_FSYNC_TIME_LIMIT); nDataDirs = configManager.getInt( EnvironmentParams.LOG_N_DATA_DIRECTORIES); if (nDataDirs != 0) { dbEnvDataDirs = gatherDataDirs(); } else { checkNoDataDirs(); dbEnvDataDirs = null; } if (!envImpl.isMemOnly()) { if (!dbEnvHome.exists()) { throw new IllegalArgumentException ("Environment home " + dbEnvHome + " doesn't exist"); } /* * If this is an arbiter take an exclusive lock. */ boolean isReadOnly = envImpl.isArbiter() ? false : readOnly; if (!lockEnvironment(isReadOnly, false)) { throw new EnvironmentLockedException (envImpl, "The environment cannot be locked for " + (isReadOnly ? "shared" : "single writer") + " access."); } } /* Cache of files. */ fileCache = new FileCache(configManager); /* Start out as if no log existed. */ currentFileNum = 0L; nextAvailableLsn = DbLsn.makeLsn(currentFileNum, firstLogEntryOffset()); lastUsedLsn = DbLsn.NULL_LSN; perFileLastUsedLsn = Collections.synchronizedMap(new HashMap<Long, Long>()); prevOffset = 0L; endOfLog = new LogEndFileDescriptor(); forceNewFile = false; final String stopOnWriteCountName = "je.debug.stopOnWriteCount"; final String stopOnWriteCountProp = System.getProperty(stopOnWriteCountName); if (stopOnWriteCountProp != null) { try { STOP_ON_WRITE_COUNT = Long.parseLong(stopOnWriteCountProp); } catch (NumberFormatException e) { throw new IllegalArgumentException ("Could not parse: " + stopOnWriteCountName, e); } } final String stopOnWriteActionName = "je.debug.stopOnWriteAction"; final String stopOnWriteActionProp = System.getProperty(stopOnWriteActionName); if (stopOnWriteActionProp != null) { if (stopOnWriteActionProp.compareToIgnoreCase("throw") == 0) { THROW_ON_WRITE = true; } else if (stopOnWriteActionProp. compareToIgnoreCase("stop") == 0) { THROW_ON_WRITE = false; } else { throw new IllegalArgumentException ("Unknown value for: " + stopOnWriteActionName + stopOnWriteActionProp); } } final Boolean logFileDeleteDetect = configManager.getBoolean( EnvironmentParams.LOG_DETECT_FILE_DELETE); if (!envImpl.isMemOnly() && logFileDeleteDetect) { fdd = new FileDeletionDetector( dbEnvHome, dbEnvDataDirs, envImpl); } else { fdd = null; } success = true; } finally { if (!success) { try { close(); } catch (IOException e) { /* * Klockwork - ok * Eat it, we want to throw the original exception. */ } } } } /** * Set the file manager's "end of log". * * @param nextAvailableLsn LSN to be used for the next log entry * @param lastUsedLsn last LSN to have a valid entry, may be null * @param prevOffset value to use for the prevOffset of the next entry. * If the beginning of the file, this is 0. */ public void setLastPosition(long nextAvailableLsn, long lastUsedLsn, long prevOffset) { this.lastUsedLsn = lastUsedLsn; perFileLastUsedLsn.put(Long.valueOf(DbLsn.getFileNumber(lastUsedLsn)), Long.valueOf(lastUsedLsn)); this.nextAvailableLsn = nextAvailableLsn; currentFileNum = DbLsn.getFileNumber(this.nextAvailableLsn); this.prevOffset = prevOffset; } /** * May be used to disable sync at file end to speed unit tests. * Must only be used for unit testing, since log corruption may result. */ public void setSyncAtFileEnd(boolean sync) { syncAtFileEnd = sync; } /* * File management */ /** * public for cleaner. * * @return the number of the first file in this environment. */ public Long getFirstFileNum() { return getFileNum(true); } public boolean getReadOnly() { return readOnly; } /** * @return the number of the last file in this environment. */ public Long getLastFileNum() { return getFileNum(false); } /** * Returns the highest (current) file number. Note that this is * unsynchronized, so if it is called outside the log write latch it is * only valid as an approximation. */ public long getCurrentFileNum() { return currentFileNum; } /** * For unit tests. */ boolean getUseWriteQueue() { return useWriteQueue; } /** * For assertions that check whether a file is valid or has been deleted * via log cleaning. */ public boolean isFileValid(long fileNum) { /* * If the file is the current file, it may be buffered and not yet * created. If the env is memory-only, we will never create or delete * log files. */ if (fileNum == currentFileNum || envImpl.isMemOnly()) { return true; } /* Check for file existence. */ String fileName = getFullFileName(fileNum, FileManager.JE_SUFFIX); File file = new File(fileName); return file.exists(); } public void setIncludeDeletedFiles(boolean includeDeletedFiles) { this.includeDeletedFiles = includeDeletedFiles; } /** * Get all JE file numbers. * @return an array of all JE file numbers. */ public Long[] getAllFileNumbers() { /* Get all the names in sorted order. */ String[] names = listFileNames(JE_SUFFIXES); Long[] nums = new Long[names.length]; for (int i = 0; i < nums.length; i += 1) { String name = names[i]; long num = nums[i] = getNumFromName(name); if (nDataDirs != 0) { int dbEnvDataDirsIdx = getDataDirIndexFromName(name) - 1; if (dbEnvDataDirsIdx != (num % nDataDirs)) { throw EnvironmentFailureException.unexpectedState ("Found file " + name + " but it should have been in " + "data directory " + (dbEnvDataDirsIdx + 1) + ". Perhaps it was moved or restored incorrectly?"); } } } return nums; } /** * Get the next file number before/after currentFileNum. * @param curFile the file we're at right now. Note that * it may not exist, if it's been cleaned and renamed. * @param forward if true, we want the next larger file, if false * we want the previous file * @return null if there is no following file, or if filenum doesn't exist */ public Long getFollowingFileNum(long curFile, boolean forward) { /* * First try the next/prev file number without listing all files. This * efficiently supports an important use case: reading files during * recovery, where there are no gaps due to log cleaning. If there is a * gap due to log cleaning, fall through and get a list of all files. */ final long tryFile; if (forward) { if (curFile == Long.MAX_VALUE) { return null; } tryFile = curFile + 1; } else { if (curFile <= 0) { return null; } tryFile = curFile - 1; } String tryName = getFullFileName(tryFile, JE_SUFFIX); if ((new File(tryName)).isFile()) { return tryFile; } /* Get all the names in sorted order. */ String[] names = listFileNames(JE_SUFFIXES); /* Search for the current file. */ String searchName = getFileName(curFile, JE_SUFFIX); int foundIdx = Arrays.binarySearch(names, searchName, stringComparator); boolean foundTarget = false; if (foundIdx >= 0) { if (forward) { foundIdx++; } else { foundIdx--; } } else { /* * currentFileNum not found (might have been cleaned). FoundIdx * will be (-insertionPoint - 1). */ foundIdx = Math.abs(foundIdx + 1); if (!forward) { foundIdx--; } } /* The current fileNum is found, return the next or prev file. */ if (forward && (foundIdx < names.length)) { foundTarget = true; } else if (!forward && (foundIdx > -1)) { foundTarget = true; } if (foundTarget) { return getNumFromName(names[foundIdx]); } return null; } /** * @return true if there are any files at all. */ public boolean filesExist() { String[] names = listFileNames(JE_SUFFIXES); return (names.length != 0); } /** * Get the first or last file number in the set of JE files. * * @param first if true, get the first file, else get the last file * @return the file number or null if no files exist */ private Long getFileNum(boolean first) { String[] names = listFileNames(JE_SUFFIXES); if (names.length == 0) { return null; } int index = 0; if (!first) { index = names.length - 1; } return getNumFromName(names[index]); } /** * Get the data dir index from a file name. * * @return index into dbEnvDataDirs of this fileName's data directory. * -1 if multiple data directories are not being used. */ private int getDataDirIndexFromName(String fileName) { if (nDataDirs == 0) { return -1; } int dataDirEnd = fileName.lastIndexOf(File.separator); String dataDir = fileName.substring(0, dataDirEnd); return Integer.valueOf (Integer.parseInt(dataDir.substring("data".length()))); } /** * Get the file number from a file name. * * @param fileName the file name * @return the file number */ public Long getNumFromName(String fileName) { String name = fileName; if (nDataDirs != 0) { name = name.substring(name.lastIndexOf(File.separator) + 1); } String fileNumber = name.substring(0, name.indexOf(".")); return Long.valueOf(Long.parseLong(fileNumber, 16)); } /** * Find JE files. Return names sorted in ascending fashion. * @param suffixes which type of file we're looking for * @return array of file names * * Used by unit tests so package protection. */ String[] listFileNames(String[] suffixes) { JEFileFilter fileFilter = new JEFileFilter(suffixes); return listFileNamesInternal(fileFilter); } /** * Find .jdb files which are >= the minimimum file number and * <= the maximum file number. * Return names sorted in ascending fashion. * * @return array of file names */ public String[] listFileNames(long minFileNumber, long maxFileNumber) { JEFileFilter fileFilter = new JEFileFilter(JE_SUFFIXES, minFileNumber, maxFileNumber); return listFileNamesInternal(fileFilter); } private static Comparator<File> fileComparator = new Comparator<File>() { private String getFileNum(File file) { String fname = file.toString(); return fname.substring(fname.indexOf(File.separator) + 1); } public int compare(File o1, File o2) { String fnum1 = getFileNum(o1); String fnum2 = getFileNum(o2); return o1.compareTo(o2); } }; private static Comparator<String> stringComparator = new Comparator<String>() { private String getFileNum(String fname) { return fname.substring(fname.indexOf(File.separator) + 1); } public int compare(String o1, String o2) { String fnum1 = getFileNum(o1); String fnum2 = getFileNum(o2); return fnum1.compareTo(fnum2); } }; /** * Find JE files, flavor for unit test support. * * @param suffixes which type of file we're looking for * @return array of file names */ public static String[] listFiles(File envDirFile, String[] suffixes, boolean envMultiSubDir) { String[] names = envDirFile.list(new JEFileFilter(suffixes)); ArrayList<String> subFileNames = new ArrayList<String>(); if (envMultiSubDir) { for (File file : envDirFile.listFiles()) { if (file.isDirectory() && file.getName().startsWith("data")) { File[] subFiles = file.listFiles(new JEFileFilter(suffixes)); for (File subFile : subFiles) { subFileNames.add(file.getName() + File.separator + subFile.getName()); } } } String[] totalFileNames = new String[names.length + subFileNames.size()]; for (int i = 0; i < totalFileNames.length; i++) { if (i < names.length) { totalFileNames[i] = names[i]; } else { totalFileNames[i] = subFileNames.get(i - names.length); } } names = totalFileNames; } if (names != null) { Arrays.sort(names, stringComparator); } else { names = new String[0]; } return names; } public File[] listJDBFiles() { if (nDataDirs == 0) { return listJDBFilesInternalSingleDir(new JEFileFilter(JE_SUFFIXES)); } else { return listJDBFilesInternalMultiDir(new JEFileFilter(JE_SUFFIXES)); } } public File[] listJDBFilesInternalSingleDir(JEFileFilter fileFilter) { File[] files = dbEnvHome.listFiles(fileFilter); if (files != null) { Arrays.sort(files); } else { files = new File[0]; } return files; } public File[] listJDBFilesInternalMultiDir(JEFileFilter fileFilter) { File[][] files = new File[nDataDirs][]; int nTotalFiles = 0; int i = 0; for (File envDir : dbEnvDataDirs) { files[i] = envDir.listFiles(fileFilter); nTotalFiles += files[i].length; i++; } if (nTotalFiles == 0) { return new File[0]; } File[] ret = new File[nTotalFiles]; i = 0; for (File[] envFiles : files) { for (File envFile : envFiles) { ret[i++] = envFile; } } Arrays.sort(ret, fileComparator); return ret; } private String[] listFileNamesInternal(JEFileFilter fileFilter) { if (nDataDirs == 0) { return listFileNamesInternalSingleDir(fileFilter); } else { return listFileNamesInternalMultiDirs(fileFilter); } } private String[] listFileNamesInternalSingleDir(JEFileFilter fileFilter) { String[] fileNames = dbEnvHome.list(fileFilter); if (fileNames != null) { Arrays.sort(fileNames); } else { fileNames = new String[0]; } return fileNames; } private String[] listFileNamesInternalMultiDirs(JEFileFilter filter) { String[][] files = new String[nDataDirs][]; int nTotalFiles = 0; int i = 0; for (File envDir : dbEnvDataDirs) { files[i] = envDir.list(filter); String envDirName = envDir.toString(); String dataDirName = envDirName. substring(envDirName.lastIndexOf(File.separator) + 1); for (int j = 0; j < files[i].length; j += 1) { files[i][j] = dataDirName + File.separator + files[i][j]; } nTotalFiles += files[i].length; i++; } if (nTotalFiles == 0) { return new String[0]; } String[] ret = new String[nTotalFiles]; i = 0; for (String[] envFiles : files) { for (String envFile : envFiles) { ret[i++] = envFile; } } Arrays.sort(ret, stringComparator); return ret; } private void checkNoDataDirs() { String[] dataDirNames = dbEnvHome.list(new FilenameFilter() { public boolean accept(File dir, String name) { /* We'll validate the subdirNum later. */ return name != null && name.length() == "dataNNN".length() && name.startsWith("data"); } } ); if (dataDirNames != null && dataDirNames.length != 0) { throw EnvironmentFailureException.unexpectedState (EnvironmentParams.LOG_N_DATA_DIRECTORIES.getName() + " was not set and expected to find no" + " data directories, but found " + dataDirNames.length + " data directories instead."); } } public File[] gatherDataDirs() { String[] dataDirNames = dbEnvHome.list(new FilenameFilter() { public boolean accept(File dir, String name) { /* We'll validate the subdirNum later. */ return name != null && name.length() == "dataNNN".length() && name.startsWith("data"); } } ); if (dataDirNames != null) { Arrays.sort(dataDirNames); } else { dataDirNames = new String[0]; } if (dataDirNames.length != nDataDirs) { throw EnvironmentFailureException.unexpectedState (EnvironmentParams.LOG_N_DATA_DIRECTORIES.getName() + " was set and expected to find " + nDataDirs + " data directories, but found " + dataDirNames.length + " instead."); } int ddNum = 1; File[] dataDirs = new File[nDataDirs]; for (String fn : dataDirNames) { String subdirNumStr = fn.substring(4); try { int subdirNum = Integer.parseInt(subdirNumStr); if (subdirNum != ddNum) { throw EnvironmentFailureException.unexpectedState ("Expected to find data subdir: data" + paddedDirNum(ddNum) + " but found data" + subdirNumStr + " instead."); } File dataDir = new File(dbEnvHome, fn); if (!dataDir.exists()) { throw EnvironmentFailureException.unexpectedState ("Data dir: " + dataDir + " doesn't exist."); } if (!dataDir.isDirectory()) { throw EnvironmentFailureException.unexpectedState ("Data dir: " + dataDir + " is not a directory."); } dataDirs[ddNum - 1] = dataDir; } catch (NumberFormatException E) { throw EnvironmentFailureException.unexpectedState ("Illegal data subdir: data" + subdirNumStr); } ddNum++; } return dataDirs; } private String paddedDirNum(int dirNum) { String paddedStr = "000" + dirNum; int len = paddedStr.length(); return paddedStr.substring(len - 3); } /** * @return the full file name and path for the nth JE file. */ String[] getFullFileNames(long fileNum) { if (includeDeletedFiles) { int nSuffixes = JE_AND_DEL_SUFFIXES.length; String[] ret = new String[nSuffixes]; for (int i = 0; i < nSuffixes; i++) { ret[i] = getFullFileName(fileNum, JE_AND_DEL_SUFFIXES[i]); } return ret; } return new String[] { getFullFileName(fileNum, JE_SUFFIX) }; } private File getDataDir(long fileNum) { return (nDataDirs == 0) ? dbEnvHome : dbEnvDataDirs[((int) (fileNum % nDataDirs))]; } public String getFullFileName(long fileNum) { return getFullFileName(fileNum, JE_SUFFIX); } /** * @return the full file name and path for this file name. */ public String getFullFileName(long fileNum, String suffix) { File dbEnvDataDir = getDataDir(fileNum); return dbEnvDataDir + File.separator + getFileName(fileNum, suffix); } /* * Return the full file name of a specified log file name, including the * sub directories names if needed. */ public String getFullFileName(String fileName) { final int suffixStartPos = fileName.indexOf("."); String suffix = fileName.substring(suffixStartPos, fileName.length()); assert suffix != null; String fileNum = fileName.substring(0, suffixStartPos); return getFullFileName (Long.valueOf(Long.parseLong(fileNum, 16)), suffix); } /** * @return the file name for the nth file. */ public static String getFileName(long fileNum, String suffix) { return (getFileNumberString(fileNum) + suffix); } /** @return the file name for the nth log (*.jdb) file. */ public static String getFileName(long fileNum) { return getFileName(fileNum, JE_SUFFIX); } /** * HexFormatter generates a 0 padded string starting with 0x. We want * the right most 8 digits, so start at 10. */ private static String getFileNumberString(long fileNum) { return HexFormatter.formatLong(fileNum).substring(10); } /** * @return true if successful, false if File.renameTo returns false, which * can occur on Windows if the file was recently closed. */ public boolean renameFile(final long fileNum, final String newSuffix) throws IOException, DatabaseException { return renameFile(fileNum, newSuffix, null) != null; } /** * Rename this file to NNNNNNNN.suffix. If that file already exists, try * NNNNNNNN.suffix.1, etc. Used for deleting files or moving corrupt files * aside. * * @param fileNum the file we want to move * * @param newSuffix the new file suffix * * @param subDir the data directory sub-directory to rename the file into. * The subDir must already exist. May be null to leave the file in its * current data directory. * * @return renamed File if successful, or null if File.renameTo returns * false, which can occur on Windows if the file was recently closed. */ public File renameFile(final long fileNum, final String newSuffix, final String subDir) throws IOException { final File oldDir = getDataDir(fileNum); final String oldName = getFileName(fileNum); final File oldFile = new File(oldDir, oldName); final File newDir = (subDir != null) ? (new File(oldDir, subDir)) : oldDir; final String newName = getFileName(fileNum, newSuffix); String generation = ""; int repeatNum = 0; while (true) { final File newFile = new File(newDir, newName + generation); if (newFile.exists()) { repeatNum++; generation = "." + repeatNum; continue; } /* * If CLEANER_EXPUNGE is false, then the cleaner will rename * the .jdb file. The rename action will first delete the * old file and then create the new file. So we should also * record the file rename action here. */ if (fdd != null) { if (oldName.endsWith(FileManager.JE_SUFFIX)) { fdd.addDeletedFile(oldName); } } clearFileCache(fileNum); final boolean success = oldFile.renameTo(newFile); return success ? newFile : null; } } /** * Delete log file NNNNNNNN. * * @param fileNum the file we want to move * * @return true if successful, false if File.delete returns false, which * can occur on Windows if the file was recently closed. */ public boolean deleteFile(final long fileNum) throws IOException, DatabaseException { final String fileName = getFullFileNames(fileNum)[0]; /* * Add files deleted by JE to filesDeletedByJE in fdd, which aims to * check whether a deleted file is deleted by JE or by users wrongly. * * The file name gotten from WatchKey is the relative file name, * so we should also get the relative file name here. */ if (fdd != null) { if (fileName.endsWith(FileManager.JE_SUFFIX)) { final int index = fileName.lastIndexOf(File.separator) + 1; final String relativeFileName = fileName.substring(index); fdd.addDeletedFile(relativeFileName); } } clearFileCache(fileNum); final File file = new File(fileName); return file.delete(); } /** * Returns the log version for the given file. */ public int getFileLogVersion(long fileNum) throws DatabaseException { try { FileHandle handle = getFileHandle(fileNum); int logVersion = handle.getLogVersion(); handle.release(); return logVersion; } catch (FileNotFoundException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_FILE_NOT_FOUND, e); } catch (ChecksumException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_CHECKSUM, e); } } /** * Return a read only file handle that corresponds to this file number. * Retrieve it from the cache or open it anew and validate the file header. * This method takes a latch on this file, so that the file descriptor will * be held in the cache as long as it's in use. When the user is done with * the file, the latch must be released. * * @param fileNum which file * @return the file handle for the existing or newly created file */ public FileHandle getFileHandle(long fileNum) throws FileNotFoundException, ChecksumException, DatabaseException { /* Check the file cache for this file. */ Long fileId = Long.valueOf(fileNum); FileHandle fileHandle = null; /** * Loop until we get an open FileHandle. */ try { while (true) { /* * The file cache is intentionally not latched here so that * it's not a bottleneck in the fast path. We check that the * file handle that we get back is really still open after we * latch it down below. */ fileHandle = fileCache.get(fileId); /* * If the file isn't in the cache, latch the cache and check * again. Under the latch, if the file is not in the cache we * add it to the cache but do not open the file yet. We latch * the handle here, and open the file further below after * releasing the cache latch. This prevents blocking other * threads that are opening other files while we open this * file. The latch on the handle blocks other threads waiting * to open the same file, which is necessary. */ boolean newHandle = false; if (fileHandle == null) { synchronized (fileCache) { fileHandle = fileCache.get(fileId); if (fileHandle == null) { newHandle = true; fileHandle = addFileHandle(fileId); } } } if (newHandle) { /* * Open the file with the fileHandle latched. It was * latched by addFileHandle above. */ boolean success = false; try { openFileHandle(fileHandle, FileMode.READ_MODE, null /*existingHandle*/); success = true; } finally { if (!success) { /* An exception is in flight -- clean up. */ fileHandle.release(); clearFileCache(fileNum); } } } else { /* * The handle was found in the cache. Latch the fileHandle * before checking getFile below and returning. */ if (!fileHandle.latchNoWait()) { /* * But the handle was latched. Rather than wait, let's * just make a new transient handle. It doesn't need * to be latched, but it does need to be closed. */ final FileHandle existingHandle = fileHandle; fileHandle = new FileHandle( envImpl, fileId, getFileNumberString(fileId)) { @Override public void release() throws DatabaseException { try { close(); } catch (IOException E) { // Ignore } } }; openFileHandle(fileHandle, FileMode.READ_MODE, existingHandle); } } /* * We may have obtained this file handle outside the file cache * latch, so we have to test that the handle is still valid. * If it's not, then loop back and try again. */ if (fileHandle.getFile() == null) { fileHandle.release(); } else { break; } } } catch (FileNotFoundException e) { /* Handle at higher levels. */ throw e; } catch (IOException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_READ, e); } return fileHandle; } /** * Creates a new FileHandle and adds it to the cache, but does not open * the file. * @return the latched FileHandle. */ private FileHandle addFileHandle(Long fileNum) throws IOException, DatabaseException { FileHandle fileHandle = new FileHandle(envImpl, fileNum, getFileNumberString(fileNum)); fileCache.add(fileNum, fileHandle); fileHandle.latch(); return fileHandle; } private FileMode getAppropriateReadWriteMode() { if (useODSYNC) { return FileMode.READWRITE_ODSYNC_MODE; } return FileMode.READWRITE_MODE; } /** * Creates a new handle and opens it. Does not add the handle to the * cache. */ private FileHandle makeFileHandle(long fileNum, FileMode mode) throws FileNotFoundException, ChecksumException { FileHandle fileHandle = new FileHandle(envImpl, fileNum, getFileNumberString(fileNum)); openFileHandle(fileHandle, mode, null /*existingHandle*/); return fileHandle; } /** * Opens the file for the given handle and initializes it. * * @param existingHandle is an already open handle for the same file or * null. If non-null it is used to avoid the cost of reading the file * header. */ private void openFileHandle(FileHandle fileHandle, FileMode mode, FileHandle existingHandle) throws FileNotFoundException, ChecksumException { nFileOpens.increment(); long fileNum = fileHandle.getFileNum(); String[] fileNames = getFullFileNames(fileNum); RandomAccessFile newFile = null; String fileName = null; boolean success = false; try { /* * Open the file. Note that we are going to try a few names to open * this file -- we'll try for N.jdb, and if that doesn't exist and * we're configured to look for all types, we'll look for N.del. */ FileNotFoundException FNFE = null; for (String fileName2 : fileNames) { fileName = fileName2; try { newFile = fileFactory.createFile(dbEnvHome, fileName, mode.getModeValue()); break; } catch (FileNotFoundException e) { /* Save the first exception thrown. */ if (FNFE == null) { FNFE = e; } } } /* * If we didn't find the file or couldn't create it, rethrow the * exception. */ if (newFile == null) { assert FNFE != null; throw FNFE; } /* * If there is an existing open handle, there is no need to read or * validate the header. Note that the log version is zero if the * existing handle is not fully initialized. */ if (existingHandle != null) { final int logVersion = existingHandle.getLogVersion(); if (logVersion > 0) { fileHandle.init(newFile, logVersion); success = true; return; } } int logVersion = LogEntryType.LOG_VERSION; if (newFile.length() == 0) { /* * If the file is empty, reinitialize it if we can. If not, * send the file handle back up; the calling code will deal * with the fact that there's nothing there. */ if (mode.isWritable()) { /* An empty file, write a header. */ long lastLsn = DbLsn.longToLsn(perFileLastUsedLsn.remove (Long.valueOf(fileNum - 1))); long headerPrevOffset = 0; if (lastLsn != DbLsn.NULL_LSN) { headerPrevOffset = DbLsn.getFileOffset(lastLsn); } if ((headerPrevOffset == 0) && (fileNum > 1) && syncAtFileEnd) { /* Get more info if this happens again. [#20732] */ throw EnvironmentFailureException.unexpectedState (envImpl, "Zero prevOffset fileNum=0x" + Long.toHexString(fileNum) + " lastLsn=" + DbLsn.getNoFormatString(lastLsn) + " perFileLastUsedLsn=" + perFileLastUsedLsn + " fileLen=" + newFile.length()); } FileHeader fileHeader = new FileHeader(fileNum, headerPrevOffset); writeFileHeader(newFile, fileName, fileHeader, fileNum); } } else { /* A non-empty file, check the header */ logVersion = readAndValidateFileHeader(newFile, fileName, fileNum); } fileHandle.init(newFile, logVersion); success = true; } catch (FileNotFoundException e) { /* Handle at higher levels. */ throw e; } catch (IOException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_READ, "Couldn't open file " + fileName, e); } catch (DatabaseException e) { /* * Let this exception go as a checksum exception, so it sets the * run recovery state correctly. */ closeFileInErrorCase(newFile); e.addErrorMessage("Couldn't open file " + fileName); throw e; } finally { if (!success) { closeFileInErrorCase(newFile); } } } /** * Close this file and eat any exceptions. Used in catch clauses. */ private void closeFileInErrorCase(RandomAccessFile file) { try { if (file != null) { file.close(); } } catch (Exception e) { } } /** * Read the given JE log file and validate the header. * * @throws DatabaseException if the file header isn't valid * * @return file header log version. */ private int readAndValidateFileHeader(RandomAccessFile file, String fileName, long fileNum) throws ChecksumException, DatabaseException { /* * Read the file header from this file. It's always the first log * entry. * * The special UNKNOWN_FILE_HEADER_VERSION value is passed for reading * the entry header. The actual log version is read as part of the * FileHeader entry. [#16939] */ LogManager logManager = envImpl.getLogManager(); LogEntry headerEntry = logManager.getLogEntryAllowChecksumException (DbLsn.makeLsn(fileNum, 0), file, LogEntryType.UNKNOWN_FILE_HEADER_VERSION); FileHeader header = (FileHeader) headerEntry.getMainItem(); return header.validate(envImpl, fileName, fileNum); } /** * Write a proper file header to the given file. */ private void writeFileHeader(RandomAccessFile file, String fileName, FileHeader header, long fileNum) throws DatabaseException { /* Fail loudly if the environment is invalid. */ envImpl.checkIfInvalid(); /* * Fail silent if the environment is not open. */ if (envImpl.mayNotWrite()) { return; } /* Write file header into this buffer in the usual log entry format. */ LogEntry headerLogEntry = new FileHeaderEntry(LogEntryType.LOG_FILE_HEADER, header); ByteBuffer headerBuf = envImpl.getLogManager(). putIntoBuffer(headerLogEntry, 0); // prevLogEntryOffset /* Write the buffer into the channel. */ int bytesWritten; try { if (LOGWRITE_EXCEPTION_TESTING) { generateLogWriteException(file, headerBuf, 0, fileNum); } /* * Always flush header so that file.length() will be non-zero when * this method returns and two threads won't attempt to create the * header. [#20732] */ bytesWritten = writeToFile(file, headerBuf, 0, fileNum, true /*flushRequired*/); } catch (ClosedChannelException e) { /* * The channel should never be closed. It may be closed because * of an interrupt received by another thread. See SR [#10463] */ throw new ThreadInterruptedException (envImpl, "Channel closed, may be due to thread interrupt", e); } catch (IOException e) { /* Possibly an out of disk exception. */ throw new LogWriteException(envImpl, e); } if (bytesWritten != headerLogEntry.getSize() + LogEntryHeader.MIN_HEADER_SIZE) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_INTEGRITY, "File " + fileName + " was created with an incomplete header. Only " + bytesWritten + " bytes were written."); } } /** * @return the prevOffset field stored in the file header. */ long getFileHeaderPrevOffset(long fileNum) throws ChecksumException, DatabaseException { try { LogEntry headerEntry = envImpl.getLogManager().getLogEntryAllowChecksumException (DbLsn.makeLsn(fileNum, 0)); FileHeader header = (FileHeader) headerEntry.getMainItem(); return header.getLastEntryInPrevFileOffset(); } catch (FileNotFoundException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_FILE_NOT_FOUND, e); } } /* * Support for writing new log entries */ /** * @return the file offset of the last LSN that was used. For constructing * the headers of log entries. If the last LSN that was used was in a * previous file, or this is the very first LSN of the whole system, return * 0. */ long getPrevEntryOffset() { return prevOffset; } /** * Increase the current log position by "size" bytes. Move the prevOffset * pointer along. * * @param size is an unsigned int * @return true if we flipped to the next log file. */ boolean bumpLsn(long size) { boolean flippedFiles = false; if (forceNewFile || (DbLsn.getFileOffset(nextAvailableLsn) + size) > maxFileSize) { forceNewFile = false; /* Move to another file. */ currentFileNum++; /* Remember the last used LSN of the previous file. */ if (lastUsedLsn != DbLsn.NULL_LSN) { perFileLastUsedLsn.put (Long.valueOf(DbLsn.getFileNumber(lastUsedLsn)), Long.valueOf(lastUsedLsn)); } prevOffset = 0; lastUsedLsn = DbLsn.makeLsn(currentFileNum, firstLogEntryOffset()); flippedFiles = true; } else { if (lastUsedLsn == DbLsn.NULL_LSN) { prevOffset = 0; } else { prevOffset = DbLsn.getFileOffset(lastUsedLsn); } lastUsedLsn = nextAvailableLsn; } nextAvailableLsn = DbLsn.makeLsn(DbLsn.getFileNumber(lastUsedLsn), (DbLsn.getFileOffset(lastUsedLsn) + size)); return flippedFiles; } /** * Write out a log buffer to the file. * @param fullBuffer buffer to write * @param flushWriteQueue true if this write can not be queued on the * Write Queue. */ void writeLogBuffer(LogBuffer fullBuffer, boolean flushWriteQueue) throws DatabaseException { /* Fail loudly if the environment is invalid. */ envImpl.checkIfInvalid(); /* * Fail silent if the environment is not open. */ if (envImpl.mayNotWrite()) { return; } /* Use the LSN to figure out what file to write this buffer to. */ long firstLsn = fullBuffer.getFirstLsn(); /* * Is there anything in this write buffer? We could have been called by * the environment shutdown, and nothing is actually in the buffer. */ if (firstLsn != DbLsn.NULL_LSN) { RandomAccessFile file = endOfLog.getWritableFile(DbLsn.getFileNumber(firstLsn), true); ByteBuffer data = fullBuffer.getDataBuffer(); try { /* * Check that we do not overwrite unless the file only contains * a header [#11915] [#12616]. */ assert fullBuffer.getRewriteAllowed() || (DbLsn.getFileOffset(firstLsn) >= file.length() || file.length() == firstLogEntryOffset()) : "FileManager would overwrite non-empty file 0x" + Long.toHexString(DbLsn.getFileNumber(firstLsn)) + " lsnOffset=0x" + Long.toHexString(DbLsn.getFileOffset(firstLsn)) + " fileLength=0x" + Long.toHexString(file.length()); if (LOGWRITE_EXCEPTION_TESTING) { generateLogWriteException (file, data, DbLsn.getFileOffset(firstLsn), DbLsn.getFileNumber(firstLsn)); } writeToFile(file, data, DbLsn.getFileOffset(firstLsn), DbLsn.getFileNumber(firstLsn), flushWriteQueue); } catch (ClosedChannelException e) { /* * The file should never be closed. It may be closed because * of an interrupt received by another thread. See SR [#10463]. */ throw new ThreadInterruptedException (envImpl, "File closed, may be due to thread interrupt", e); } catch (IOException e) { throw new LogWriteException(envImpl, e); } assert EnvironmentImpl.maybeForceYield(); } } /** * Write a buffer to a file at a given offset. */ private int writeToFile(RandomAccessFile file, ByteBuffer data, long destOffset, long fileNum, boolean flushWriteQueue) throws IOException, DatabaseException { int totalBytesWritten = 0; bumpWriteCount("write"); int pos = data.position(); int size = data.limit() - pos; if (lastFileNumberTouched == fileNum && (Math.abs(destOffset - lastFileTouchedOffset) < ADJACENT_TRACK_SEEK_DELTA)) { nSequentialWrites.increment(); nSequentialWriteBytes.add(size); } else { nRandomWrites.increment(); nRandomWriteBytes.add(size); } if (VERIFY_CHECKSUMS) { verifyChecksums(data, destOffset, "pre-write"); } /* * Perform a RandomAccessFile write and update the buffer position. * ByteBuffer.array() is safe to use since all non-direct ByteBuffers * have a backing array. * * Synchronization on the file object is needed because two threads may * call seek() on the same file object. * * If the Write Queue is enabled, attempt to get the fsync latch. If * we can't get it, then an fsync or write is in progress and we'd * block anyway. In that case, queue the write operation. */ boolean fsyncLatchAcquired = endOfLog.fsyncFileSynchronizer.tryLock(); boolean enqueueSuccess = false; if (!fsyncLatchAcquired && useWriteQueue && !flushWriteQueue) { enqueueSuccess = endOfLog.enqueueWrite(fileNum, data.array(), destOffset, pos + data.arrayOffset(), size); } if (!enqueueSuccess) { if (!fsyncLatchAcquired) { endOfLog.fsyncFileSynchronizer.lock(); } try { if (useWriteQueue) { endOfLog.dequeuePendingWrites1(); } synchronized (file) { file.seek(destOffset); file.write(data.array(), pos + data.arrayOffset(), size); if (VERIFY_CHECKSUMS) { file.seek(destOffset); file.read( data.array(), pos + data.arrayOffset(), size); verifyChecksums(data, destOffset, "post-write"); } } } finally { endOfLog.fsyncFileSynchronizer.unlock(); } } data.position(pos + size); totalBytesWritten = size; lastFileNumberTouched = fileNum; lastFileTouchedOffset = destOffset + size; return totalBytesWritten; } private void bumpWriteCount(final String debugMsg) throws IOException { if (DEBUG) { System.out.println("Write: " + WRITE_COUNT + " " + debugMsg); } if (++WRITE_COUNT >= STOP_ON_WRITE_COUNT && WRITE_COUNT < (STOP_ON_WRITE_COUNT + N_BAD_WRITES)) { if (THROW_ON_WRITE) { throw new IOException ("IOException generated for testing: " + WRITE_COUNT + " " + debugMsg); } Runtime.getRuntime().halt(0xff); } } /** * Read a buffer from a file at a given offset. We know that the desired * data exists in this file. There's no need to incur extra costs * such as checks of the file length, nor to return status as to whether * this file contains the data. */ void readFromFile(RandomAccessFile file, ByteBuffer readBuffer, long offset, long fileNo) throws DatabaseException { readFromFile(file, readBuffer, offset, fileNo, true /* dataKnownToBeInFile */); } /** * Read a buffer from a file at a given offset. * * @return true if the read buffer is filled, false, if there is nothing * left in the file to read */ boolean readFromFile(RandomAccessFile file, ByteBuffer readBuffer, long offset, long fileNo, boolean dataKnownToBeInFile) throws DatabaseException { /* * All IOExceptions on read turn into EnvironmentFailureExceptions * [#15768]. */ try { /* * Check if there's a pending write(s) in the write queue for this * fileNo/offset and if so, use it to fulfill this read request. */ if (useWriteQueue && endOfLog.checkWriteCache(readBuffer, offset, fileNo)) { return true; } /* * Nothing queued, all data for this file must be in the file. * Note that there's no synchronization between the check of the * write queue above, and this check of file length. It's possible * that a newly written log entry could show up between the * statements, and enter the write queue just after we finish the * check. * * Because of this, callers of this method must abide by one of * three conditions: * 1. They guarantee that the attempt to read a chunk of new data * comes after the new data has been logged by the LogManager. * 2. The files are quiescent when the read is going on. * 3. The caller is sure the data is in this file. * * The replication feeder reader abides by (1) while all other file * readers abide by (2). Callers which are fetching specific log * entries fall under (3). */ boolean readThisFile = true; if (!dataKnownToBeInFile) { /* * Callers who are not sure whether the desired data is in this * file or the next incur the cost of a check of file.length(), * which is a system call. */ readThisFile = (offset < file.length()); } if (readThisFile) { readFromFileInternal(file, readBuffer, offset, fileNo); return true; } return false; } catch (ClosedChannelException e) { /* * The channel should never be closed. It may be closed because * of an interrupt received by another thread. See SR [#10463] */ throw new ThreadInterruptedException (envImpl, "Channel closed, may be due to thread interrupt", e); } catch (IOException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_READ, e); } } private void readFromFileInternal(RandomAccessFile file, ByteBuffer readBuffer, long offset, long fileNum) throws IOException { /* * Perform a RandomAccessFile read and update the buffer position. * ByteBuffer.array() is safe to use since all non-direct ByteBuffers * have a backing array. Synchronization on the file object is needed * because two threads may call seek() on the same file object. */ synchronized (file) { int pos = readBuffer.position(); int size = readBuffer.limit() - pos; if (lastFileNumberTouched == fileNum && (Math.abs(offset - lastFileTouchedOffset) < ADJACENT_TRACK_SEEK_DELTA)) { nSequentialReads.increment(); nSequentialReadBytes.add(size); } else { nRandomReads.increment(); nRandomReadBytes.add(size); } file.seek(offset); int bytesRead = file.read(readBuffer.array(), pos + readBuffer.arrayOffset(), size); if (bytesRead > 0) { readBuffer.position(pos + bytesRead); } lastFileNumberTouched = fileNum; lastFileTouchedOffset = offset + bytesRead; } } private void printLogBuffer(ByteBuffer entryBuffer, long lsn) { int curPos = entryBuffer.position(); while (entryBuffer.remaining() > 0) { int recStartPos = entryBuffer.position(); LogEntryHeader header = null; try { header = new LogEntryHeader( entryBuffer, LogEntryType.LOG_VERSION, lsn); } catch (ChecksumException e) { System.err.println("ChecksumException in printLogBuffer " + e); break; } LogEntryType recType = LogEntryType.findType(header.getType()); int recSize = header.getSize() + header.getItemSize(); System.out.println( "LOGREC " + recType.toStringNoVersion() + " at LSN " + DbLsn.toString(lsn) + " , log buffer offset " + recStartPos); lsn += recSize; entryBuffer.position(recStartPos + recSize); } entryBuffer.position(curPos); } private void verifyChecksums(ByteBuffer entryBuffer, long lsn, String comment) { int curPos = entryBuffer.position(); try { while (entryBuffer.remaining() > 0) { int recStartPos = entryBuffer.position(); /* Write buffer contains current log version entries. */ LogEntryHeader header = new LogEntryHeader( entryBuffer, LogEntryType.LOG_VERSION, lsn); verifyChecksum(entryBuffer, header, lsn, comment); entryBuffer.position(recStartPos + header.getSize() + header.getItemSize()); } } catch (ChecksumException e) { System.err.println("ChecksumException: (" + comment + ") " + e); System.err.println("start stack trace"); e.printStackTrace(System.err); System.err.println("end stack trace"); } entryBuffer.position(curPos); } private void verifyChecksum(ByteBuffer entryBuffer, LogEntryHeader header, long lsn, String comment) throws ChecksumException { ChecksumValidator validator = null; /* Add header to checksum bytes */ validator = new ChecksumValidator(); int headerSizeMinusChecksum = header.getSizeMinusChecksum(); int itemStart = entryBuffer.position(); entryBuffer.position(itemStart - headerSizeMinusChecksum); validator.update(entryBuffer, headerSizeMinusChecksum); entryBuffer.position(itemStart); /* * Now that we know the size, read the rest of the entry if the first * read didn't get enough. */ int itemSize = header.getItemSize(); if (entryBuffer.remaining() < itemSize) { System.err.println("Couldn't verify checksum (" + comment + ")"); return; } /* * Do entry validation. Run checksum before checking the entry * type, it will be the more encompassing error. */ validator.update(entryBuffer, itemSize); validator.validate(header.getChecksum(), lsn); } /** * FSync the end of the log. */ void syncLogEnd() throws DatabaseException { try { endOfLog.force(); } catch (IOException e) { throw new LogWriteException (envImpl, "IOException during fsync", e); } } /** * Sync the end of the log, close off this log file. Should only be called * under the log write latch. */ void syncLogEndAndFinishFile() throws DatabaseException, IOException { if (syncAtFileEnd) { syncLogEnd(); } endOfLog.close(); } /** * Returns whether anything is in the write queue. */ public boolean hasQueuedWrites() { return endOfLog.hasQueuedWrites(); } /** * For unit testing only. */ public void testWriteQueueLock() { endOfLog.fsyncFileSynchronizer.lock(); } /** * For unit testing only. */ public void testWriteQueueUnlock() { endOfLog.fsyncFileSynchronizer.unlock(); } public void startFileCacheWarmer(final long recoveryStartLsn){ assert fileCacheWarmer == null; final DbConfigManager cm = envImpl.getConfigManager(); final int warmUpSize = cm.getInt( EnvironmentParams.LOG_FILE_WARM_UP_SIZE); if (warmUpSize == 0) { return; } final int bufSize = cm.getInt( EnvironmentParams.LOG_FILE_WARM_UP_BUF_SIZE); fileCacheWarmer = new FileCacheWarmer( envImpl, recoveryStartLsn, lastUsedLsn, warmUpSize, bufSize); fileCacheWarmer.start(); } private void stopFileCacheWarmer(){ /* * Use fcw local var because fileCacheWarmer can be set to null by * other threads calling clearFileCacheWarmer, namely the cache warmer * thread. */ final FileCacheWarmer fcw = fileCacheWarmer; if (fcw == null) { return; } fcw.shutdown(); clearFileCacheWarmer(); } /* Allow cache warmer thread to be GC'd. */ void clearFileCacheWarmer() { fileCacheWarmer = null; } /** * Close all file handles and empty the cache. */ public void clear() throws IOException, DatabaseException { synchronized (fileCache) { fileCache.clear(); } endOfLog.close(); } /** * Clear the file lock. */ public void close() throws IOException { stopFileCacheWarmer(); if (envLock != null) { envLock.release(); envLock = null; } if (exclLock != null) { exclLock.release(); exclLock = null; } if (channel != null) { channel.close(); channel = null; } if (lockFile != null) { lockFile.close(); lockFile = null; } if (fdd != null) { fdd.close(); } } /** * Lock the environment. Return true if the lock was acquired. If * exclusive is false, then this implements a single writer, multiple * reader lock. If exclusive is true, then implement an exclusive lock. * * There is a lock file and there are two regions of the lock file: byte 0, * and byte 1. Byte 0 is the exclusive writer process area of the lock * file. If an environment is opened for write, then it attempts to take * an exclusive write lock on byte 0. Byte 1 is the shared reader process * area of the lock file. If an environment is opened for read-only, then * it attempts to take a shared lock on byte 1. This is how we implement * single writer, multi reader semantics. * * The cleaner, each time it is invoked, attempts to take an exclusive lock * on byte 1. The owning process already either has an exclusive lock on * byte 0, or a shared lock on byte 1. This will necessarily conflict with * any shared locks on byte 1, even if it's in the same process and there * are no other holders of that shared lock. So if there is only one * read-only process, it will have byte 1 for shared access, and the * cleaner can not run in it because it will attempt to get an exclusive * lock on byte 1 (which is already locked for shared access by itself). * If a write process comes along and tries to run the cleaner, it will * attempt to get an exclusive lock on byte 1. If there are no other * reader processes (with shared locks on byte 1), and no other writers * (which are running cleaners on with exclusive locks on byte 1), then the * cleaner will run. */ public boolean lockEnvironment(boolean rdOnly, boolean exclusive) { try { if (checkEnvHomePermissions(rdOnly)) { return true; } if (lockFile == null) { lockFile = new RandomAccessFile (new File(dbEnvHome, LOCK_FILE), FileMode.READWRITE_MODE.getModeValue()); } channel = lockFile.getChannel(); try { if (exclusive) { /* * To lock exclusive, must have exclusive on * shared reader area (byte 1). */ exclLock = channel.tryLock(1, 1, false); if (exclLock == null) { return false; } return true; } if (rdOnly) { envLock = channel.tryLock(1, 1, true); } else { envLock = channel.tryLock(0, 1, false); } if (envLock == null) { return false; } return true; } catch (OverlappingFileLockException e) { return false; } } catch (IOException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_INTEGRITY, e); } } public void releaseExclusiveLock() throws DatabaseException { try { if (exclLock != null) { exclLock.release(); } } catch (IOException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_INTEGRITY, e); } } /** * Ensure that if the environment home dir is on readonly media or in a * readonly directory that the environment has been opened for readonly * access. * * @return true if the environment home dir is readonly. * * @throws IllegalArgumentException via Environment ctor */ public boolean checkEnvHomePermissions(boolean rdOnly) throws DatabaseException { if (nDataDirs == 0) { return checkEnvHomePermissionsSingleEnvDir(dbEnvHome, rdOnly); } else { return checkEnvHomePermissionsMultiEnvDir(rdOnly); } } private boolean checkEnvHomePermissionsSingleEnvDir(File dbEnvHome, boolean rdOnly) throws DatabaseException { boolean envDirIsReadOnly = !dbEnvHome.canWrite(); if (envDirIsReadOnly && !rdOnly) { /* * Use the absolute path in the exception message, to * make a mis-specified relative path problem more obvious. */ throw new IllegalArgumentException ("The Environment directory " + dbEnvHome.getAbsolutePath() + " is not writable, but the " + "Environment was opened for read-write access."); } return envDirIsReadOnly; } private boolean checkEnvHomePermissionsMultiEnvDir(boolean rdOnly) throws DatabaseException { for (File dbEnvDir : dbEnvDataDirs) { if (!checkEnvHomePermissionsSingleEnvDir(dbEnvDir, rdOnly)) { return false; } } return true; } /** * Truncate a log at this position. Used by recovery to a timestamp * utilities and by recovery to set the end-of-log position, see * LastFileReader.setEndOfFile(). * * <p>This method forces a new log file to be written next, if the last * file (the file truncated to) has an old version in its header. This * ensures that when the log is opened by an old version of JE, a version * incompatibility will be detected. [#11243]</p> */ public void truncateSingleFile(long fileNum, long offset) throws IOException, DatabaseException { try { FileHandle handle = makeFileHandle(fileNum, getAppropriateReadWriteMode()); RandomAccessFile file = handle.getFile(); try { file.getChannel().truncate(offset); } finally { file.close(); } if (handle.isOldHeaderVersion()) { forceNewFile = true; } } catch (ChecksumException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_CHECKSUM, e); } } /* * Truncate all log entries after a specified log entry, the position of * that entry is specified by the fileNum and offset, we do this to avoid * the log file gap. Used by replication hard recovery and the * DbTruncateLog utility, see SR [#19463]. */ public void truncateLog(long fileNum, long offset) throws IOException, DatabaseException { /* * Truncate the log files following by this log file in descending * order to avoid the log entry gap, see SR [#19463]. */ for (long i = getLastFileNum(); i >= fileNum; i--) { /* Do nothing if this file doesn't exist. */ if (!isFileValid(i)) { continue; } /* * If this is the file that truncation starts, invoke * truncateSingleFile. If the offset is 0, which means the * FileHeader is also deleted, delete the whole file to avoid a log * file gap. */ if (i == fileNum) { truncateSingleFile(fileNum, offset); if (offset != 0) { continue; } } boolean deleted = deleteFile(i); assert deleted : "File " + getFullFileName(i, JE_SUFFIX) + " not deleted during truncateLog"; } } /** * Mark the specified log entries as invisible and obsolete. The entries * are written here, but are fsync'ed later. If there is any problem or * exception during the setting, the method will throw an * EnvironmentFailureException. * * These changes are made directly to the file, but recently logged log * entries may also be resident in the log buffers. The caller must take * care to call LogManager.flush() before this method, to ensure that all * entries are on disk. * * In addition, we must ensure that after this step, the affected log * entries will only be read via a FileReader, and will not be faulted in * by the LogManager. Entries may be present in the log and in the log * buffers, but only the on disk version is modified by this method. The * LogManager can read directly from the log buffers and may read the * incorrect, non-invisible version of the log entry, rather than the * invisible version from the file. This should not be an issue, because * invisible log entries should be detached from the in-memory tree before * they are made invisible. * * @param fileNum target file. * @param lsns The list of LSNs to make invisible, must be sorted in * ascending order. */ public void makeInvisible(long fileNum, List<Long> lsns) { if (lsns.size() == 0) { return; } /* Open this file. */ FileHandle handle = null; try { /* * Note that we are getting a new, non-cached file handle for * specific use by this method. */ handle = makeFileHandle(fileNum, getAppropriateReadWriteMode()); } catch (ChecksumException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_CHECKSUM, "Opening file " + fileNum + " for invisible marking ", e); } catch (FileNotFoundException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_FILE_NOT_FOUND, "Opening file " + fileNum + " for invisible marking ", e); } RandomAccessFile file = handle.getFile(); /* Set the invisible bit for each entry. */ try { for (Long lsn : lsns) { if (DbLsn.getFileNumber(lsn) != fileNum) { /* * This failure will not invalidate the environment right * away. But since it causes replication syncup to fail, * the environment will shutdown, which is the effect we * want. */ throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.UNEXPECTED_STATE, "LSN of " + DbLsn.getNoFormatString(lsn) + " did not match file number" + fileNum); } int entryFlagsOffset = (int) (DbLsn.getFileOffset(lsn) + LogEntryHeader.FLAGS_OFFSET); file.seek(entryFlagsOffset); byte flags = file.readByte(); byte newFlags = LogEntryHeader.makeInvisible(flags); file.seek(entryFlagsOffset); file.writeByte(newFlags); } } catch (IOException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_WRITE, "Flipping invisibility in file " + fileNum, e); } finally { /* * Just close the file. Fsyncs will be done later on, in the hope * that the OS has already synced asynchronously. */ try { file.close(); } catch (IOException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_WRITE, "Closing after invisibility cloaking: file " + fileNum, e); } } } /** * Fsync this set of log files. Used for replication syncup rollback. */ public void force(Set<Long> fileNums) { for (long fileNum : fileNums) { RandomAccessFile file = null; try { FileHandle handle = makeFileHandle(fileNum, getAppropriateReadWriteMode()); file = handle.getFile(); file.getChannel().force(false); nLogFSyncs.increment(); } catch (FileNotFoundException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_FILE_NOT_FOUND, "Invisible fsyncing file " + fileNum, e); } catch (ChecksumException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_CHECKSUM, "Invisible fsyncing file " + fileNum, e); } catch (IOException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_WRITE, "Invisible fsyncing file " + fileNum, e); } finally { if (file != null) { try { file.close(); } catch (IOException e) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_WRITE, "Invisible fsyncing file " + fileNum, e); } } } } } /** * Set the flag that causes a new file to be written before the next write. */ public void forceNewLogFile() { forceNewFile = true; } /** * Return the offset of the first log entry after the file header. */ /** * @return the size in bytes of the file header log entry. */ public static int firstLogEntryOffset() { return FileHeader.entrySize() + LogEntryHeader.MIN_HEADER_SIZE; } /** * Return the next available LSN in the log. Note that this is * unsynchronized, so if it is called outside the log write latch it is * only valid as an approximation. */ public long getNextLsn() { return nextAvailableLsn; } /** * Return the last allocated LSN in the log. Note that this is * unsynchronized, so if it is called outside the log write latch it is * only valid as an approximation. */ public long getLastUsedLsn() { return lastUsedLsn; } StatGroup loadStats(StatsConfig config) { nOpenFiles.set(fileCache.size()); StatGroup copyStats = stats.cloneGroup(config.getClear()); return copyStats; } /* * Unit test support */ /* * @return ids of files in cache */ Set<Long> getCacheKeys() { return fileCache.getCacheKeys(); } /** * Clear a file out of the file cache regardless of mode type. */ private void clearFileCache(long fileNum) throws IOException, DatabaseException { synchronized (fileCache) { fileCache.remove(fileNum); } } /* * The file cache keeps N RandomAccessFile objects cached for file * access. The cache consists of two parts: a Hashtable that doesn't * require extra synchronization, for the most common access, and a linked * list of files to support cache administration. Looking up a file from * the hash table doesn't require extra latching, but adding or deleting a * file does. */ private static class FileCache { private final Map<Long, FileHandle> fileMap; // Long->file private final List<Long> fileList; // list of file numbers private final int fileCacheSize; FileCache(DbConfigManager configManager) { /* * A fileMap maps the file number to FileHandles (RandomAccessFile, * latch). The fileList is a list of Longs to determine which files * to eject out of the file cache if it's too small. */ fileMap = new Hashtable<Long, FileHandle>(); fileList = new LinkedList<Long>(); fileCacheSize = configManager.getInt(EnvironmentParams.LOG_FILE_CACHE_SIZE); } private FileHandle get(Long fileId) { return fileMap.get(fileId); } private void add(Long fileId, FileHandle fileHandle) throws IOException, DatabaseException { /* * Does the cache have any room or do we have to evict? Hunt down * the file list for an unused file. Note that the file cache might * actually grow past the prescribed size if there is nothing * evictable. Should we try to shrink the file cache? Presently if * it grows, it doesn't shrink. */ if (fileList.size() >= fileCacheSize) { Iterator<Long> iter = fileList.iterator(); while (iter.hasNext()) { Long evictId = iter.next(); FileHandle evictTarget = fileMap.get(evictId); /* * Try to latch. If latchNoWait returns false, then another * thread owns this latch. Note that a thread that's trying * to get a new file handle should never already own the * latch on another file handle, because these latches are * meant to be short lived and only held over the i/o out * of the file. */ if (evictTarget.latchNoWait()) { try { fileMap.remove(evictId); iter.remove(); evictTarget.close(); } finally { evictTarget.release(); } break; } } } /* * We've done our best to evict. Add the file the the cache now * whether or not we did evict. */ fileList.add(fileId); fileMap.put(fileId, fileHandle); } /** * Take any file handles corresponding to this file name out of the * cache. A file handle could be there twice, in rd only and in r/w * mode. */ private void remove(long fileNum) throws IOException, DatabaseException { Iterator<Long> iter = fileList.iterator(); while (iter.hasNext()) { Long evictId = iter.next(); if (evictId.longValue() == fileNum) { FileHandle evictTarget = fileMap.get(evictId); try { evictTarget.latch(); fileMap.remove(evictId); iter.remove(); evictTarget.close(); } finally { evictTarget.release(); } } } } private void clear() throws IOException, DatabaseException { Iterator<FileHandle> iter = fileMap.values().iterator(); while (iter.hasNext()) { FileHandle fileHandle = iter.next(); try { fileHandle.latch(); fileHandle.close(); iter.remove(); } finally { fileHandle.release(); } } fileMap.clear(); fileList.clear(); } private Set<Long> getCacheKeys() { return fileMap.keySet(); } private int size() { return fileMap.size(); } } /** * The LogEndFileDescriptor is used to write and fsync the end of the log. * Because the JE log is append only, there is only one logical R/W file * descriptor for the whole environment. This class actually implements two * RandomAccessFile instances, one for writing and one for fsyncing, so the * two types of operations don't block each other. * * The write file descriptor is considered the master. Manipulation of * this class is done under the log write latch. Here's an explanation of * why the log write latch is sufficient to safeguard all operations. * * There are two types of callers who may use this file descriptor: the * thread that is currently writing to the end of the log and any threads * that are fsyncing on behalf of the FSyncManager. * * The writing thread appends data to the file and fsyncs the file when we * flip over to a new log file. The file is only instantiated at the point * that it must do so -- which is either when the first fsync is required * by JE or when the log file is full and we flip files. Therefore, the * writing thread has two actions that change this descriptor -- we * initialize the file descriptor for the given log file at the first write * to the file, and we close the file descriptor when the log file is full. * Therefore is a period when there is no log descriptor -- when we have * not yet written a log buffer into a given log file. * * The fsyncing threads ask for the log end file descriptor asynchronously, * but will never modify it. These threads may arrive at the point when * the file descriptor is null, and therefore skip their fysnc, but that is * fine because it means a writing thread already flipped that target file * and has moved on to the next file. * * Time Activity * 10 thread 1 writes log entry A into file 0x0, issues fsync * outside of log write latch, yields the processor * 20 thread 2 writes log entry B, piggybacks off thread 1 * 30 thread 3 writes log entry C, but no room left in that file, * so it flips the log, and fsyncs file 0x0, all under the log * write latch. It nulls out endOfLogRWFile, moves onto file * 0x1, but doesn't create the file yet. * 40 thread 1 finally comes along, but endOfLogRWFile is null-- * no need to fsync in that case, 0x0 got fsynced. * * If a write is attempted and an fsync is already in progress, then the * information pertaining to the data to be written (data, offset, length) * is saved away in the "queuedWrites" array. When the fsync completes, * the queuedWrites buffer is emptied. This ensures that writes continue * to execute on file systems which block all IO calls during an fsync() * call (e.g. ext3). */ class LogEndFileDescriptor { private RandomAccessFile endOfLogRWFile = null; private RandomAccessFile endOfLogSyncFile = null; private final ReentrantLock fsyncFileSynchronizer = new ReentrantLock(); /* * Holds all data for writes which have been queued due to their * being blocked by an fsync when the original write was attempted. * The next thread to execute an fsync or write will execute any * queued writes in this buffer. * Latch order is fsyncFileSynchronizer, followed by the queuedWrites * mutex [ synchronized (queuedWrites) {} ]. * * Default protection for unit tests. */ private final byte[] queuedWrites = useWriteQueue ? new byte[writeQueueSize] : null; /* Current position in the queuedWrites array. */ private int queuedWritesPosition = 0; /* The starting offset on disk of the first byte in queuedWrites. */ private long qwStartingOffset; /* The file number that the queuedWrites are destined for. */ private long qwFileNum = -1; /* For unit tests. */ void setQueueFileNum(final long qwFileNum) { this.qwFileNum = qwFileNum; } /* * Check if fileNo/offset is present in queuedWrites, and if so, fill * readBuffer with those bytes. We theorize that this is needed * because HA will be reading at the very end of the log and those * writes, if enqueued, may no longer be in LogBuffers in the * LogBufferPool. This might happen in the case of lots of concurrent * non-synchronous writes (with synchronous commits) which become * enqueued in the queuedWrites cache, but cycle out of the LBP. In * general, using synchronous commits with HA is a bad idea. * * Default protection for unit tests. * @return true if more data was available. If so, the read buffer * will be filled up. */ /* private */ boolean checkWriteCache(final ByteBuffer readBuffer, final long requestedOffset, final long fileNum) { int pos = readBuffer.position(); int targetBufSize = readBuffer.limit() - pos; synchronized (queuedWrites) { if (qwFileNum != fileNum) { return false; } if (queuedWritesPosition == 0) { return false; } if (requestedOffset < qwStartingOffset || (qwStartingOffset + queuedWritesPosition) <= requestedOffset) { return false; } /* We have the bytes available. */ int nBytesToCopy = (int) (queuedWritesPosition - (requestedOffset - qwStartingOffset)); nBytesToCopy = Math.min(nBytesToCopy, targetBufSize); readBuffer.put(queuedWrites, (int) (requestedOffset - qwStartingOffset), nBytesToCopy); nBytesReadFromWriteQueue.add(nBytesToCopy); nReadsFromWriteQueue.increment(); return true; } } /* * Enqueue a blocked write call for later execution by the next thread * to do either an fsync or write call. fsyncFileSynchronizer is not * held when this is called. * * Default protection for unit tests. */ /* private */ boolean enqueueWrite(final long fileNum, final byte[] data, final long destOffset, final int arrayOffset, final int size) throws DatabaseException { assert !fsyncFileSynchronizer.isHeldByCurrentThread(); for (int i = 0; i < 2; i++) { try { enqueueWrite1(fileNum, data, destOffset, arrayOffset, size); return true; } catch (RelatchRequiredException RE) { dequeuePendingWrites(); } } /* Give up after two tries. */ nWriteQueueOverflowFailures.increment(); return false; } private void enqueueWrite1(final long fileNum, final byte[] data, final long destOffset, final int arrayOffset, final int size) throws RelatchRequiredException, DatabaseException { /* * The queuedWrites queue only ever holds writes for a single file. * * This check is safe because qwFileNum can only ever change inside * enqueueWrite which can only ever be called while the Log Write * Latch is held. * * NOTE: We believe the commented out second condition is safe * to add to the code if we ever see contention with this call to * dequeuePendingWrites against an fsync. Here is the reasoning: * * queuedWritesPosition is changed in two places: (1) enqueueWrite1 * where it is incremented, and (2) dequeuePendingWrites1 where it * is zeroed. Both of these places are proected by the queuedWrites * mutex. The zero'ing (2) will only make the dequeue unnecessary * so the extra commented out check below is safe since it will * only result in eliminating an unnecessary dequeuePendingWrites * call. */ if (qwFileNum < fileNum /* && queuedWritesPosition > 0 */) { dequeuePendingWrites(); qwFileNum = fileNum; } synchronized (queuedWrites) { boolean overflow = (writeQueueSize - queuedWritesPosition) < size; if (overflow) { nWriteQueueOverflow.increment(); /* * Since we can't write this "write call" into the * ByteBuffer without overflowing, we will try to dequeue * all current writes in the buffer. But that requires * holding the fsyncFileSynchronizer latch first which * would be latching out of order relative to the * queuedWrites mutex. */ throw RelatchRequiredException.relatchRequiredException; } assert qwFileNum == fileNum; int curPos = queuedWritesPosition; if (curPos == 0) { /* * This is the first entry in queue. Set qwStartingOffset. */ qwStartingOffset = destOffset; } if (curPos + qwStartingOffset != destOffset) { throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_INTEGRITY, "non-consecutive writes queued. " + "qwPos=" + queuedWritesPosition + " write destOffset=" + destOffset); } System.arraycopy(data, arrayOffset, queuedWrites, queuedWritesPosition, size); queuedWritesPosition += size; } } /** * Returns whether anything is in the write queue. */ boolean hasQueuedWrites() { return queuedWritesPosition > 0; } /* * Execute pending writes. Assumes fsyncFileSynchronizer is not held. */ private void dequeuePendingWrites() throws DatabaseException { assert !fsyncFileSynchronizer.isHeldByCurrentThread(); fsyncFileSynchronizer.lock(); try { dequeuePendingWrites1(); } finally { fsyncFileSynchronizer.unlock(); } } /* * Execute pending writes. Assumes fsyncFileSynchronizer is held. */ private void dequeuePendingWrites1() throws DatabaseException { assert fsyncFileSynchronizer.isHeldByCurrentThread(); try { synchronized (queuedWrites) { /* Nothing to see here. Move along. */ if (queuedWritesPosition == 0) { return; } RandomAccessFile file = getWritableFile(qwFileNum, false); synchronized (file) { file.seek(qwStartingOffset); file.write(queuedWrites, 0, queuedWritesPosition); nBytesWrittenFromWriteQueue.add(queuedWritesPosition); nWritesFromWriteQueue.increment(); if (VERIFY_CHECKSUMS) { file.seek(qwStartingOffset); file.read(queuedWrites, 0, queuedWritesPosition); ByteBuffer bb = ByteBuffer.allocate(queuedWritesPosition); bb.put(queuedWrites, 0, queuedWritesPosition); bb.position(0); verifyChecksums (bb, qwStartingOffset, "post-write"); } } /* We flushed the queue. Reset the buffer. */ queuedWritesPosition = 0; } } catch (IOException e) { throw new LogWriteException (envImpl, "IOException during fsync", e); } } /** * getWritableFile must be called under the log write latch. * * Typically, endOfLogRWFile is not null. Hence the * fsyncFileSynchronizer does not need to be locked (which would * block the write queue from operating. */ private RandomAccessFile getWritableFile(final long fileNumber, final boolean doLock) { try { if (endOfLogRWFile == null) { /* * We need to make a file descriptor for the end of the * log. This is guaranteed to be called under the log * write latch. * * Protect both the RWFile and SyncFile under this lock, * to avoid a race for creating the file and writing the * header. [#20732] */ if (doLock) { fsyncFileSynchronizer.lock(); } try { endOfLogRWFile = makeFileHandle(fileNumber, getAppropriateReadWriteMode()). getFile(); endOfLogSyncFile = makeFileHandle(fileNumber, getAppropriateReadWriteMode()). getFile(); } finally { if (doLock) { fsyncFileSynchronizer.unlock(); } } } return endOfLogRWFile; } catch (Exception e) { /* * If we can't get a write channel, we need to invalidate the * environment. */ throw new EnvironmentFailureException (envImpl, EnvironmentFailureReason.LOG_INTEGRITY, e); } } /** * FSync the log file that makes up the end of the log. */ private void force() throws DatabaseException, IOException { /* * Get a local copy of the end of the log file descriptor, it could * change. No need to latch, no harm done if we get an old file * descriptor, because we forcibly fsync under the log write latch * when we switch files. * * If there is no current end file descriptor, we know that the log * file has flipped to a new file since the fsync was issued. */ fsyncFileSynchronizer.lock(); try { /* Flush any queued writes. */ if (useWriteQueue) { dequeuePendingWrites1(); } RandomAccessFile file = endOfLogSyncFile; if (file != null) { bumpWriteCount("fsync"); FileChannel ch = file.getChannel(); long start = System.currentTimeMillis(); try { ch.force(false); } catch (ClosedChannelException e) { /* * The channel should never be closed. It may be closed * because of an interrupt received by another thread. * See SR [#10463]. */ throw new ThreadInterruptedException (envImpl, "Channel closed, may be due to thread interrupt", e); } final long fSyncMs = System.currentTimeMillis() - start; nLogFSyncs.increment(); nFSyncTime.add(fSyncMs); if (nFSyncMaxTime.setMax(fSyncMs) && fSyncTimeLimit != 0 && fSyncMs > fSyncTimeLimit) { LoggerUtils.warning( envImpl.getLogger(), envImpl, String.format( "FSync time of %d ms exceeds limit (%d ms)", fSyncMs, fSyncTimeLimit)); } assert EnvironmentImpl.maybeForceYield(); } /* Flush any writes which were queued while fsync'ing. */ if (useWriteQueue) { dequeuePendingWrites1(); } } finally { fsyncFileSynchronizer.unlock(); } } /** * Close the end of the log file descriptor. Use atomic assignment to * ensure that we won't force and close on the same descriptor. */ void close() throws IOException { /* * Protect both the RWFile and SyncFile under this lock out of * paranoia, although we don't expect two threads to call close * concurrently. [#20732] */ fsyncFileSynchronizer.lock(); try { IOException firstException = null; if (endOfLogRWFile != null) { RandomAccessFile file = endOfLogRWFile; /* * Null out so that other threads know endOfLogRWFile is no * longer available. */ endOfLogRWFile = null; try { file.close(); } catch (IOException e) { /* Save this exception, so we can try second close. */ firstException = e; } } if (endOfLogSyncFile != null) { RandomAccessFile file = endOfLogSyncFile; /* * Null out so that other threads know endOfLogSyncFile is * no longer available. */ endOfLogSyncFile = null; file.close(); } if (firstException != null) { throw firstException; } } finally { fsyncFileSynchronizer.unlock(); } } } /* * Generate IOExceptions for testing. */ /* Testing switch. public so others can read the value. */ public static final boolean LOGWRITE_EXCEPTION_TESTING; private static String RRET_PROPERTY_NAME = "je.logwrite.exception.testing"; static { LOGWRITE_EXCEPTION_TESTING = (System.getProperty(RRET_PROPERTY_NAME) != null); } /* Max write counter value. */ private static final int LOGWRITE_EXCEPTION_MAX = 100; /* Current write counter value. */ private int logWriteExceptionCounter = 0; /* Whether an exception has been thrown. */ private boolean logWriteExceptionThrown = false; /* Random number generator. */ private Random logWriteExceptionRandom = null; private void generateLogWriteException(RandomAccessFile file, ByteBuffer data, long destOffset, long fileNum) throws DatabaseException, IOException { if (logWriteExceptionThrown) { (new Exception("Write after LogWriteException")). printStackTrace(); } logWriteExceptionCounter += 1; if (logWriteExceptionCounter >= LOGWRITE_EXCEPTION_MAX) { logWriteExceptionCounter = 0; } if (logWriteExceptionRandom == null) { logWriteExceptionRandom = new Random(System.currentTimeMillis()); } if (logWriteExceptionCounter == logWriteExceptionRandom.nextInt(LOGWRITE_EXCEPTION_MAX)) { int len = logWriteExceptionRandom.nextInt(data.remaining()); if (len > 0) { byte[] a = new byte[len]; data.get(a, 0, len); ByteBuffer buf = ByteBuffer.wrap(a); writeToFile(file, buf, destOffset, fileNum, false /*flushRequired*/); } logWriteExceptionThrown = true; throw new IOException("Randomly generated for testing"); } } /** * The factory interface for creating RandomAccessFiles. For production * use, the default factory is always used and a DefaultRandomAccessFile is * always created. For testing, the factory can be overridden to return a * subclass of DefaultRandomAccessFile that overrides methods and injects * faults, for example. */ public interface FileFactory { /** * @param envHome can be used to distinguish environments in a test * program that opens multiple environments. Not for production use. * * @param fullName the full file name to be passed to the * RandomAccessFile constructor. * * @param mode the file mode to be passed to the RandomAccessFile * constructor. */ RandomAccessFile createFile(File envHome, String fullName, String mode) throws FileNotFoundException; } /** * The RandomAccessFile for production use. Tests that override the * default FileFactory should return a RandomAccessFile that subclasses * this class to inherit workarounds such as the overridden length method. */ public static class DefaultRandomAccessFile extends RandomAccessFile { public DefaultRandomAccessFile(String fullName, String mode) throws FileNotFoundException { super(fullName, mode); } /** * RandomAccessFile.length() is not thread safe and side-effects the * file pointer if interrupted in the middle. It is synchronized here * to work around that problem. */ @Override public synchronized long length() throws IOException { return super.length(); } } /** * The factory instance used to create RandomAccessFiles. This field is * intentionally public and non-static so it may be set by tests. See * FileFactory. */ public static FileFactory fileFactory = new FileFactory() { public RandomAccessFile createFile(File envHome, String fullName, String mode) throws FileNotFoundException { return new DefaultRandomAccessFile(fullName, mode); } }; }
8639d24d88a06d230a4a9875480f669af7188690
b3f9f7bfbf69c52eb07daf3a6d041ad56fe95254
/src/main/java/com/lypgod/test/ThinkingInJava/Ch21_Concurrency/Practice6/Practice6.java
79dc68846cf9ca1e55d973de91f7a44bfd1d847c
[]
no_license
lypgod/ThinkingInJavaPractice
33c13a8ad07648560d24060206db537e6d95aa76
b3ced3631e751c09914af6d47fe0e3c17846801a
refs/heads/master
2021-01-12T13:57:43.799008
2016-11-04T19:48:10
2016-11-04T19:48:10
69,253,448
0
0
null
null
null
null
UTF-8
Java
false
false
667
java
package com.lypgod.test.ThinkingInJava.Ch21_Concurrency.Practice6; import java.util.Random; public class Practice6 implements Runnable { private static int idIndex = 0; private final int id = idIndex++; private int sleepTime = (new Random().nextInt(10)) * 1000; @Override public void run() { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("#" + id + ": " + sleepTime); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(new Practice6()).start(); } } }
722a0d50819aa4a01ee9cddb3a8f6b7a28460923
8e97963e8b35f6ebc49eebd833ea95d7a4e9ae34
/java-tags-angular-master/src/main/java/com/emergya/java/tags/angular/EntityFormTagHandler.java
aab7b5b0fb47a82b841b85147fffa6ee7a9dadaf
[]
no_license
himabindu68/ETLPROJECT
1371f898300be301fae932e4329151fccbfea3d0
75da52a12225b136f59132ea7bdb14898537e6d3
refs/heads/master
2022-10-14T06:56:43.294444
2019-07-16T18:07:05
2019-07-16T18:07:05
197,084,398
0
0
null
2022-10-05T19:54:39
2019-07-15T23:12:59
Java
UTF-8
Java
false
false
8,333
java
package com.emergya.java.tags.angular; import com.emergya.java.Utils; import com.emergya.java.tags.angular.annotations.DetailsField; import com.emergya.java.tags.angular.annotations.FormField; import com.emergya.java.tags.angular.annotations.FormWidgetType; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.SimpleTagSupport; import org.springframework.util.StringUtils; /** * * @author lroman */ public class EntityFormTagHandler extends SimpleTagSupport { private String className; private String formModel = "form"; /** * Called by the container to invoke this tag. The implementation of this method is provided by the tag library developer, and * handles all tag processing, body iteration, etc. * * @throws javax.servlet.jsp.JspException */ @Override public final void doTag() throws JspException { JspWriter out = getJspContext().getOut(); Class<?> filterClass; try { filterClass = Class.forName(className); } catch (ClassNotFoundException ex) { throw new JspException("Error in FormFilterTag tag", ex); } Method[] methods = filterClass.getDeclaredMethods(); List<FormField> sortedAnnotations = new ArrayList<>(); for (Method method : methods) { FormField formFieldAnnotation = method.getAnnotation(FormField.class); if (formFieldAnnotation != null) { if (StringUtils.isEmpty(formFieldAnnotation.scopeName())) { String scopeName = Utils.getFieldName(method); formFieldAnnotation = new FormFieldDTO( formFieldAnnotation.order(), scopeName, formFieldAnnotation.label(), formFieldAnnotation.type(), formFieldAnnotation.cssClasses(), formFieldAnnotation.attributes(), formFieldAnnotation.optionsExpression()); } sortedAnnotations.add(formFieldAnnotation); } } Collections.sort(sortedAnnotations, new Comparator<FormField>() { @Override public int compare(FormField o1, FormField o2) { return o1.order() - o2.order(); } }); StringBuilder builder = new StringBuilder(); builder.append("<div class=\"form-horizontal\">"); for (FormField fieldViewAnnotation : sortedAnnotations) { builder.append(createFormField(formModel, fieldViewAnnotation)); } builder.append("</div>"); try { out.write(builder.toString()); } catch (IOException ex) { throw new RuntimeException(ex); } } /** * Sets the class name used to generate the form. * * @param className The class name including its full class path. */ public final void setClassName(final String className) { this.className = className; } /** * Sets the form's model variable. * * @param model The model variable. */ public final void setModel(final String model) { this.formModel = model; } private Object createFormField(String baseModel, FormField formFieldAnnotation) { List<String> attributes = createAttributes(baseModel, formFieldAnnotation); String elementHTML = String.format("<%s %s></%s>", formFieldAnnotation.type().getDomElement(), StringUtils.collectionToDelimitedString(attributes, " "), // If we are using a directive with a custom template we cannot add data-validate to the element, as it won't work. formFieldAnnotation.type().getDomElement()); if (!StringUtils.isEmpty(formFieldAnnotation.type().getWrapper())) { elementHTML = String.format(formFieldAnnotation.type().getWrapper(), elementHTML); } String rowHTML = String.format( "<div class=\"form-group\" data-ng-class=\"{'has-error':errors.%s.length}\" >" + "<label class=\"col-md-3 control-label\">{{'%s'|translate}}</label>" + "<div class=\"col-md-9\">%s %s</div></div>", formFieldAnnotation.scopeName(), formFieldAnnotation.label(), elementHTML, createErrorsRepeater(formFieldAnnotation.scopeName())); return rowHTML; } private List<String> createAttributes(String baseModel, FormField formFieldAnnotation) { ArrayList<String> attributes = new ArrayList<>(); if (!StringUtils.isEmpty(formFieldAnnotation.type().getAttributes())) { attributes.add(formFieldAnnotation.type().getAttributes()); } String[] customAttributes = formFieldAnnotation.attributes(); if (customAttributes != null) { attributes.addAll(Arrays.asList(customAttributes)); } if (formFieldAnnotation.type().isUsingOptionsModel()) { String optionsModelAttribute = "options"; if (!StringUtils.isEmpty(formFieldAnnotation.optionsExpression())) { optionsModelAttribute = formFieldAnnotation.optionsExpression(); } attributes.add(String.format("data-ng-options=\"%s\"", optionsModelAttribute)); } attributes.add(String.format( "data-ng-model=\"%s.%s\"", baseModel, formFieldAnnotation.scopeName())); attributes.add(String.format( "class=\"%s %s\"", formFieldAnnotation.type().getCssClasses(), formFieldAnnotation.cssClasses())); return attributes; } private String createErrorsRepeater(String scopeName) { return String.format( "<ul class=\"help-block\"data-ng-show=\"errors.%s.length\">" + "<li data-ng-repeat=\"error in errors.%s\">{{error}}</li>" + "</ul>", scopeName, scopeName); } /** * Auxiliary class to hold data from the FormField annotation and be able to handle it normally so we can sort fields etc. */ private static class FormFieldDTO implements FormField { private final String label; private final String scopeName; private final int order; private final FormWidgetType type; private final String cssClasses; private final String[] attributes; private final String optionsExpression; FormFieldDTO( int order, String scopeName, String label, FormWidgetType type, String cssClasses, String[] attributes, String optionsScopeName) { this.order = order; this.scopeName = scopeName; this.label = label; this.type = type; this.cssClasses = cssClasses; this.attributes = attributes; this.optionsExpression = optionsScopeName; } /** * @return the label */ @Override public String label() { return label; } /** * @return the scopeName */ @Override public String scopeName() { return scopeName; } /** * @return the order */ @Override public int order() { return order; } @Override public Class<? extends Annotation> annotationType() { return DetailsField.class; } @Override public FormWidgetType type() { return type; } @Override public String cssClasses() { return cssClasses; } @Override public String[] attributes() { return attributes; } /** * @return the optionsExpression */ @Override public String optionsExpression() { return optionsExpression; } } }
55f901a23689a3eb28e5004ad20d9f56c6e4a675
f40747ed1b112514f5c7a9190708cb384dbf5f7a
/ext/infinispan/src/main/java/io/machinecode/chainlink/transport/infinispan/configuration/ChainlinkModuleCommandExtensions.java
8610125ed25e34b470344e78d4b48295812329e1
[ "Apache-2.0" ]
permissive
machinecode-io/chainlink
aa755924d587377a8dcca8178e3359f9f417023e
31d5c367bd94ce83f3d0fa7a22b38c680651eb5a
refs/heads/master
2020-12-30T18:16:06.669427
2015-03-09T23:30:27
2015-03-09T23:30:27
21,302,325
0
0
null
null
null
null
UTF-8
Java
false
false
739
java
package io.machinecode.chainlink.transport.infinispan.configuration; import org.infinispan.commands.module.ExtendedModuleCommandFactory; import org.infinispan.commands.module.ModuleCommandExtensions; import org.infinispan.commands.module.ModuleCommandInitializer; /** * From ServiceLoader * @author <a href="mailto:[email protected]">Brent Douglas</a> */ public class ChainlinkModuleCommandExtensions implements ModuleCommandExtensions { @Override public ExtendedModuleCommandFactory getModuleCommandFactory() { return new ChainlinkModuleCommandFactory(); } @Override public ModuleCommandInitializer getModuleCommandInitializer() { return new ChainlinkModuleCommandInitializer(); } }
8d75c51fd82c9790fb1cb7d48f4a3f73959e7be7
77eddd3ae4d72d915189498015abab01f7eaa5c0
/Lab Spring2017/src/Lab16_4.java
8ca1993f38ffb2c6351d28cf54b2d0fadd29cc2e
[]
no_license
fannydai/CSE114
bcec66efce0a1da4dea57aff7be43753e7668481
8c1b6b1fde41cc24d62baa14fe4d3070fd66aa4e
refs/heads/master
2023-04-29T21:57:10.289980
2019-04-30T19:22:53
2019-04-30T19:22:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
838
java
import java.util.ArrayList; import java.util.Scanner; /* * Lab 16 part 4 */ public class Lab16_4 { public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer> list2){ ArrayList list3 = new ArrayList(); list3 = list1; while(!list2.isEmpty()){ list3.add(list2.get(0)); list2.remove(0); } return list3; } public static void main(String[] args){ Scanner stdin = new Scanner(System.in); ArrayList<Integer> list1 = new ArrayList<Integer>(); ArrayList<Integer> list2 = new ArrayList<Integer>(); System.out.print("Enter five integers for list1: "); for(int i=0; i<5; i++) list1.add(stdin.nextInt()); System.out.print("Enter five integers for list2: "); for(int i=0; i<5; i++) list2.add(stdin.nextInt()); System.out.print("The combined list is " + union(list1, list2)); } }
e663b7c753d2b0483693b1ff7c8136e2d6755eb3
9cb6f5eb2caffc4be040693a54a005484fbad97a
/src/main/java/com/mahesh/model/Solution.java
0d66139d96d72cec506f64e268c8424aa94f91d1
[]
no_license
Maheshmahi7/TicketAssessment
ad407ba9cf5f7b51904b72848239bcf2882a8c0e
ffc8fcb8034d99e8a9160ba5ef794fbd7a627b0e
refs/heads/master
2021-01-09T05:32:14.795340
2017-02-06T11:41:49
2017-02-06T11:41:49
80,718,616
0
0
null
null
null
null
UTF-8
Java
false
false
161
java
package com.mahesh.model; import lombok.Data; @Data public class Solution { private int id; private Ticket ticketId; private String solution; }
1f99b5d748627f9583c59da8e1868bf6c4f119aa
48249985a8ba53cecb2fcc2f51ce2ee90c802a3d
/VIT/CSE1007 - Java Programming/DA/package1/NationalTravel_17BCI0113.java
c36844426ecac0bc13da4a95b39a981b241c8e16
[]
no_license
namsnath/MiscellaneousCode
7e373d681f47bba90525a86d36e68319e1cadf10
5791ada575052e4d21c7f692ad5696ae9e755c64
refs/heads/master
2021-06-25T00:02:37.020949
2020-10-28T09:03:05
2020-10-28T09:03:05
134,683,286
0
2
null
2019-10-02T06:29:27
2018-05-24T08:12:19
Java
UTF-8
Java
false
false
658
java
package package1; import package1.Travel_17BCI0113; public class NationalTravel_17BCI0113 extends Travel_17BCI0113 { String fromState; String toState; public NationalTravel_17BCI0113(String fromPlace, String fromState, String toPlace, String toState, int cost, int year) { super.fromPlace = fromPlace; this.fromState = fromState; super.toPlace = toPlace; this.toState = toState; super.cost = cost; super.yearOfTravel = year; } public String getDetails() { return String.format("%s(%s)-%s(%s) (%d) => Rs %d", fromPlace, fromState, toPlace, toState, yearOfTravel, cost); } }
999e0a9c71307f8b8daeedd51d140cc819e6f8a2
aa478ce54868ccf79bb3e0de990e9a6192ac9a03
/src/main/java/com/jfinal/json/JFinalJsonKit.java
2cee6c6d77be8982b5bd2009692ac6136277b59a
[ "Apache-2.0" ]
permissive
zhuzhuxiaSoft/jfinal
d53241970d47fdb68d215cdb31eb5fa1ef6a897b
f9f41ecb68a4505ea27a88fb9013b7db1b91ea94
refs/heads/master
2021-06-19T21:34:00.231330
2021-02-04T07:32:32
2021-02-04T07:32:32
171,877,554
0
0
Apache-2.0
2021-02-04T07:32:33
2019-02-21T13:33:00
Java
UTF-8
Java
false
false
21,933
java
/** * Copyright (c) 2011-2021, James Zhan 詹波 ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jfinal.json; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.sql.Time; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import com.jfinal.kit.StrKit; import com.jfinal.kit.SyncWriteMap; import com.jfinal.plugin.activerecord.CPI; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.Record; /** * JFinalJsonKit */ @SuppressWarnings({"rawtypes", "unchecked"}) public class JFinalJsonKit { public static final JFinalJsonKit me = new JFinalJsonKit(); // 缓存 ToJson 对象 protected static SyncWriteMap<Class<?>, ToJson<?>> cache = new SyncWriteMap<>(512, 0.25F); // StringBuilder 最大缓冲区大小 protected static int maxBufferSize = 1024 * 512; // 将 Model 当成 Bean 只对 getter 方法进行转换 protected static boolean treatModelAsBean = false; // 是否跳过 null 值的字段,不对其进行转换 protected static boolean skipNullValueField = false; // 对 Model 和 Record 的字段名进行转换的函数。例如转成驼峰形式对 oracle 支持更友好 protected static Function<String, String> modelAndRecordFieldNameConverter = null; protected static Function<Object, ToJson<?>> toJsonFactory = null; public interface ToJson<T> { void toJson(T value, int depth, JsonResult ret); } public ToJson<?> getToJson(Object object) { ToJson<?> ret = cache.get(object.getClass()); if (ret == null) { ret = createToJson(object); cache.putIfAbsent(object.getClass(), ret); } return ret; } /** * 添加 ToJson 转换接口实现类,自由定制任意类型数据的转换规则 * <pre> * 例子: * ToJson<Timestamp> toJson = (value, depth, ret) -> { * ret.addLong(value.getTime()); * }; * * JFinalJson.addToJson(Timestamp.class, toJson); * * 以上代码为 Timestamp 类型的 json 转换定制了转换规则 * 将其转换成了 long 型数据 * </pre> */ public static void addToJson(Class<?> type, ToJson<?> toJson) { Objects.requireNonNull(type, "type can not be null"); Objects.requireNonNull(toJson, "toJson can not be null"); cache.put(type, toJson); } protected ToJson<?> createToJson(Object value) { // 优先使用 toJsonFactory 创建 ToJson 实例,方便用户优先接管 ToJson 转换器的创建 if (toJsonFactory != null) { ToJson<?> tj = toJsonFactory.apply(value); if (tj != null) { return tj; } } // 基础类型 ----------------------------------------- if (value instanceof String) { return new StrToJson(); } if (value instanceof Number) { if (value instanceof Integer) { return new IntToJson(); } if (value instanceof Long) { return new LongToJson(); } if (value instanceof Double) { return new DoubleToJson(); } if (value instanceof Float) { return new FloatToJson(); } return new NumberToJson(); } if (value instanceof Boolean) { return new BooleanToJson(); } if (value instanceof Character) { return new CharacterToJson(); } if (value instanceof Enum) { return new EnumToJson(); } if (value instanceof java.util.Date) { if (value instanceof Timestamp) { return new TimestampToJson(); } if (value instanceof Time) { return new TimeToJson(); } return new DateToJson(); } // 集合、Bean 类型,需要检测 depth --------------------------------- if (! treatModelAsBean) { if (value instanceof Model) { return new ModelToJson(); } } if (value instanceof Record) { return new RecordToJson(); } if (value instanceof Map) { return new MapToJson(); } if (value instanceof Collection) { return new CollectionToJson(); } if (value.getClass().isArray()) { return new ArrayToJson(); } if (value instanceof Enumeration) { return new EnumerationToJson(); } if (value instanceof Iterator) { return new IteratorToJson(); } if (value instanceof Iterable) { return new IterableToJson(); } BeanToJson beanToJson = buildBeanToJson(value); if (beanToJson != null) { return beanToJson; } return new UnknownToJson(); } public static boolean checkDepth(int depth, JsonResult ret) { if (depth < 0) { ret.addNull(); return true; } else { return false; } } static class StrToJson implements ToJson<String> { public void toJson(String str, int depth, JsonResult ret) { escape(str, ret.sb); } } static class CharacterToJson implements ToJson<Character> { public void toJson(Character ch, int depth, JsonResult ret) { escape(ch.toString(), ret.sb); } } static class IntToJson implements ToJson<Integer> { public void toJson(Integer value, int depth, JsonResult ret) { ret.addInt(value); } } static class LongToJson implements ToJson<Long> { public void toJson(Long value, int depth, JsonResult ret) { ret.addLong(value); } } static class DoubleToJson implements ToJson<Double> { public void toJson(Double value, int depth, JsonResult ret) { if (value.isInfinite() || value.isNaN()) { ret.addNull(); } else { ret.addDouble(value); } } } static class FloatToJson implements ToJson<Float> { public void toJson(Float value, int depth, JsonResult ret) { if (value.isInfinite() || value.isNaN()) { ret.addNull(); } else { ret.addFloat(value); } } } // 接管 int、long、double、float 之外的 Number 类型 static class NumberToJson implements ToJson<Number> { public void toJson(Number value, int depth, JsonResult ret) { ret.addNumber(value); } } static class BooleanToJson implements ToJson<Boolean> { public void toJson(Boolean value, int depth, JsonResult ret) { ret.addBoolean(value); } } static class EnumToJson implements ToJson<Enum> { public void toJson(Enum en, int depth, JsonResult ret) { ret.addEnum(en); } } static class TimestampToJson implements ToJson<Timestamp> { public void toJson(Timestamp ts, int depth, JsonResult ret) { ret.addTimestamp(ts); } } static class TimeToJson implements ToJson<Time> { public void toJson(Time t, int depth, JsonResult ret) { ret.addTime(t); } } static class DateToJson implements ToJson<Date> { public void toJson(Date value, int depth, JsonResult ret) { ret.addDate(value); } } static class ModelToJson implements ToJson<Model> { public void toJson(Model model, int depth, JsonResult ret) { if (checkDepth(depth--, ret)) { return ; } Map<String, Object> attrs = CPI.getAttrs(model); modelAndRecordToJson(attrs, depth, ret); } } static class RecordToJson implements ToJson<Record> { public void toJson(Record record, int depth, JsonResult ret) { if (checkDepth(depth--, ret)) { return ; } Map<String, Object> columns = record.getColumns(); modelAndRecordToJson(columns, depth, ret); } } public static void modelAndRecordToJson(Map<String, Object> map, int depth, JsonResult ret) { Iterator iter = map.entrySet().iterator(); boolean first = true; ret.addChar('{'); while (iter.hasNext()) { Map.Entry<String, Object> entry = (Map.Entry)iter.next(); Object value = entry.getValue(); if (value == null && skipNullValueField) { continue ; } if (first) { first = false; } else { ret.addChar(','); } String fieldName = entry.getKey(); if (modelAndRecordFieldNameConverter != null) { fieldName = modelAndRecordFieldNameConverter.apply(fieldName); } ret.addStrNoEscape(fieldName); ret.addChar(':'); if (value != null) { ToJson tj = me.getToJson(value); tj.toJson(value, depth, ret); } else { ret.addNull(); } } ret.addChar('}'); } static class MapToJson implements ToJson<Map<?, ?>> { public void toJson(Map<?, ?> map, int depth, JsonResult ret) { if (checkDepth(depth--, ret)) { return ; } mapToJson(map, depth, ret); } } public static void mapToJson(Map<?, ?> map, int depth, JsonResult ret) { Iterator iter = map.entrySet().iterator(); boolean first = true; ret.addChar('{'); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); Object value = entry.getValue(); if (value == null && skipNullValueField) { continue ; } if (first) { first = false; } else { ret.addChar(','); } ret.addMapKey(entry.getKey()); ret.addChar(':'); if (value != null) { ToJson tj = me.getToJson(value); tj.toJson(value, depth, ret); } else { ret.addNull(); } } ret.addChar('}'); } static class CollectionToJson implements ToJson<Collection> { public void toJson(Collection c, int depth, JsonResult ret) { if (checkDepth(depth--, ret)) { return ; } iteratorToJson(c.iterator(), depth, ret); } } static class ArrayToJson implements ToJson<Object> { public void toJson(Object object, int depth, JsonResult ret) { if (checkDepth(depth--, ret)) { return ; } iteratorToJson(new ArrayIterator(object), depth, ret); } } static class ArrayIterator implements Iterator<Object> { private Object array; private int size; private int index; public ArrayIterator(Object array) { this.array = array; this.size = Array.getLength(array); this.index = 0; } public boolean hasNext() { return index < size; } public Object next() { return Array.get(array, index++); } } static class EnumerationToJson implements ToJson<Enumeration> { public void toJson(Enumeration en, int depth, JsonResult ret) { if (checkDepth(depth--, ret)) { return ; } ArrayList list = Collections.list(en); iteratorToJson(list.iterator(), depth, ret); } } static class IteratorToJson implements ToJson<Iterator> { public void toJson(Iterator it, int depth, JsonResult ret) { if (checkDepth(depth--, ret)) { return ; } iteratorToJson(it, depth, ret); } } public static void iteratorToJson(Iterator it, int depth, JsonResult ret) { boolean first = true; ret.addChar('['); while (it.hasNext()) { if (first) { first = false; } else { ret.addChar(','); } Object value = it.next(); if (value != null) { ToJson tj = me.getToJson(value); tj.toJson(value, depth, ret); } else { ret.addNull(); } } ret.addChar(']'); } static class IterableToJson implements ToJson<Iterable> { public void toJson(Iterable iterable, int depth, JsonResult ret) { if (checkDepth(depth--, ret)) { return ; } iteratorToJson(iterable.iterator(), depth, ret); } } static class BeanToJson implements ToJson<Object> { private static final Object[] NULL_ARGS = new Object[0]; private String[] fields; private Method[] methods; public BeanToJson(String[] fields, Method[] methods) { if (fields.length != methods.length) { throw new IllegalArgumentException("fields 与 methods 长度必须相同"); } this.fields = fields; this.methods = methods; } public void toJson(Object bean, int depth, JsonResult ret) { if (checkDepth(depth--, ret)) { return ; } try { ret.addChar('{'); boolean first = true; for (int i = 0; i < fields.length; i++) { Object value = methods[i].invoke(bean, NULL_ARGS); if (value == null && skipNullValueField) { continue ; } if (first) { first = false; } else { ret.addChar(','); } ret.addStrNoEscape(fields[i]); ret.addChar(':'); if (value != null) { ToJson tj = me.getToJson(value); tj.toJson(value, depth, ret); } else { ret.addNull(); } } ret.addChar('}'); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } } /** * 存在 getter/is 方法返回 BeanToJson,否则返回 null */ public static BeanToJson buildBeanToJson(Object bean) { List<String> fields = new ArrayList<>(); List<Method> methods = new ArrayList<>(); Method[] methodArray = bean.getClass().getMethods(); for (Method m : methodArray) { if (m.getParameterCount() != 0 || m.getReturnType() == void.class) { continue ; } String methodName = m.getName(); int indexOfGet = methodName.indexOf("get"); if (indexOfGet == 0 && methodName.length() > 3) { // Only getter String attrName = methodName.substring(3); if (!attrName.equals("Class")) { // Ignore Object.getClass() fields.add(StrKit.firstCharToLowerCase(attrName)); methods.add(m); } } else { int indexOfIs = methodName.indexOf("is"); if (indexOfIs == 0 && methodName.length() > 2) { String attrName = methodName.substring(2); fields.add(StrKit.firstCharToLowerCase(attrName)); methods.add(m); } } } int size = fields.size(); if (size > 0) { return new BeanToJson(fields.toArray(new String[size]), methods.toArray(new Method[size])); } else { return null; } } static class UnknownToJson implements ToJson<Object> { public void toJson(Object object, int depth, JsonResult ret) { // 未知类型无法处理时当作字符串处理,否则 ajax 调用返回时 js 无法解析 ret.addUnknown(object); } } /** * JsonResult 用于存放 json 生成结果,结合 ThreadLocal 进行资源重用 */ public static class JsonResult { /** * 缓存 SimpleDateFormat * * 备忘:请勿使用 TimeKit.getSimpleDateFormat(String) 优化这里,可减少一次 * ThreadLocal.get() 调用 */ Map<String, SimpleDateFormat> formats = new HashMap<>(); // StringBuilder 内部对 int、long、double、float 数据写入有优化 StringBuilder sb = new StringBuilder(); String datePattern; String timestampPattern; boolean inUse = false; public void init(String datePattern, String timestampPattern) { this.datePattern = datePattern; this.timestampPattern = timestampPattern; inUse = true; } // 用来判断当前是否处于重入型转换状态,如果为 true,则要使用 new JsonResult() public boolean isInUse() { return inUse; } public void clear() { inUse = false; // 释放空间占用过大的缓存 if (sb.length() > maxBufferSize) { sb = new StringBuilder(Math.max(1024, maxBufferSize / 2)); } else { sb.setLength(0); } } public String toString() { return sb.toString(); } public int length() { return sb.length(); } public void addChar(char ch) { sb.append(ch); } public void addNull() { // sb.append((String)null); sb.append("null"); } public void addStr(String str) { escape(str, sb); } public void addStrNoEscape(String str) { sb.append('\"').append(str).append('\"'); } public void addInt(int i) { sb.append(i); } public void addLong(long l) { sb.append(l); } public void addDouble(double d) { sb.append(d); } public void addFloat(float f) { sb.append(f); } public void addNumber(Number n) { sb.append(n.toString()); } public void addBoolean(boolean b) { sb.append(b); } public void addEnum(Enum en) { sb.append('\"').append(en.toString()).append('\"'); } public String getDatePattern() { return datePattern; } public String getTimestampPattern() { return timestampPattern; } public SimpleDateFormat getFormat(String pattern) { SimpleDateFormat ret = formats.get(pattern); if (ret == null) { ret = new SimpleDateFormat(pattern); formats.put(pattern, ret); } return ret; } public void addTime(Time t) { sb.append('\"').append(t.toString()).append('\"'); } public void addTimestamp(Timestamp ts) { if (timestampPattern != null) { sb.append('\"').append(getFormat(timestampPattern).format(ts)).append('\"'); } else { sb.append(ts.getTime()); } } public void addDate(Date d) { if (datePattern != null) { sb.append('\"').append(getFormat(datePattern).format(d)).append('\"'); } else { sb.append(d.getTime()); } } public void addMapKey(Object value) { escape(String.valueOf(value), sb); } public void addUnknown(Object obj) { escape(obj.toString(), sb); } } /** * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). */ public static void escape(String s, StringBuilder sb) { sb.append('\"'); for (int i = 0, len = s.length(); i < len; i++) { char ch = s.charAt(i); switch (ch) { case '"': sb.append("\\\""); break; case '\\': sb.append("\\\\"); break; case '\b': sb.append("\\b"); break; case '\f': sb.append("\\f"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; //case '/': // sb.append("\\/"); // break; default: if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) { String str = Integer.toHexString(ch); sb.append("\\u"); for (int k = 0; k < 4 - str.length(); k++) { sb.append('0'); } sb.append(str.toUpperCase()); } else { sb.append(ch); } } } sb.append('\"'); } public static void setMaxBufferSize(int maxBufferSize) { int size = 1024 * 1; if (maxBufferSize < size) { throw new IllegalArgumentException("maxBufferSize can not less than " + size); } JFinalJsonKit.maxBufferSize = maxBufferSize; } /** * 将 Model 当成 Bean 只对 getter 方法进行转换 * * 默认值为 false,将使用 Model 内的 Map attrs 属性进行转换,不对 getter 方法进行转换 * 优点是可以转换 sql 关联查询产生的动态字段,还可以转换 Model.put(...) 进来的数据 * * 配置为 true 时,将 Model 当成是传统的 java bean 对其 getter 方法进行转换, * 使用生成器生成过 base model 的情况下才可以使用此配置 */ public static void setTreatModelAsBean(boolean treatModelAsBean) { JFinalJsonKit.treatModelAsBean = treatModelAsBean; } /** * 配置 Model、Record 字段名的转换函数 * * <pre> * 例子: * JFinalJson.setModelAndRecordFieldNameConverter(fieldName -> { * return StrKit.toCamelCase(fieldName, true); * }); * * 以上例子中的方法 StrKit.toCamelCase(...) 的第二个参数可以控制大小写转化的细节 * 可以查看其方法上方注释中的说明了解详情 * </pre> */ public static void setModelAndRecordFieldNameConverter(Function<String, String>converter) { JFinalJsonKit.modelAndRecordFieldNameConverter = converter; } /** * 配置将 Model、Record 字段名转换为驼峰格式 * * <pre> * toLowerCaseAnyway 参数的含义: * 1:true 值无条件将字段先转换成小写字母。适用于 oracle 这类字段名是大写字母的数据库 * 2:false 值只在出现下划线时将字段转换成小写字母。适用于 mysql 这类字段名是小写字母的数据库 * </pre> */ public static void setModelAndRecordFieldNameToCamelCase(boolean toLowerCaseAnyway) { modelAndRecordFieldNameConverter = (fieldName) -> { return StrKit.toCamelCase(fieldName, toLowerCaseAnyway); }; } /** * 配置将 Model、Record 字段名转换为驼峰格式 * * 先将字段名无条件转换成小写字母,然后再转成驼峰格式,适用于 oracle 这类字段名是大写字母的数据库 * * 如果是 mysql 数据库,建议使用: setModelAndRecordFieldNameToCamelCase(false); */ public static void setModelAndRecordFieldNameToCamelCase() { setModelAndRecordFieldNameToCamelCase(true); } public static void setToJsonFactory(Function<Object, ToJson<?>> toJsonFactory) { JFinalJsonKit.toJsonFactory = toJsonFactory; } public static void setSkipNullValueField(boolean skipNullValueField) { JFinalJsonKit.skipNullValueField = skipNullValueField; } }
32f846e4b588514b20ce927e3a47f3f8f8fd4dd9
4c71910a700026d9bdec41c135299aa7004bdb20
/liyun-cms-iface/src/main/java/com/liyun/car/materiel/entity/CmsDealerMateriel.java
555f4a43d20dd49a6d7533b7a9bf37cf382c9901
[]
no_license
zhoujinhua/lyqc-cms
3a350a5375d0870e284666d07d9fcf4a6b3cae36
bacae83f5de77e0c7cb43fedb3a60d655a3a2f90
refs/heads/master
2021-01-13T03:45:53.920248
2017-02-09T02:33:17
2017-02-09T02:33:17
77,212,808
0
1
null
null
null
null
UTF-8
Java
false
false
3,461
java
package com.liyun.car.materiel.entity; import java.util.Date; import org.activiti.engine.task.Task; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.liyun.car.common.serializer.EnumSerializer; import com.liyun.car.materiel.enums.DealerMaterielStatusEnum; public class CmsDealerMateriel implements java.io.Serializable { // Fields public static String FLOW_NAME = "materiel"; private Integer mtrlAppCode; private Integer dealerCode; private String dealerName; private Integer companyCode; private String companyName; private CmsMaterielInfo info; private String mtrlCode; private String mtrlNm; private Integer aMtrlCnt; private Integer rMtrlCnt; private Double rMtrlAmt; private String trackNum; private DealerMaterielStatusEnum status; private Date appDt; private Date grantDt; private Date cofimDt; private String remarks; private Task task; // Constructors /** default constructor */ public CmsDealerMateriel() { } // Property accessors public Integer getMtrlAppCode() { return this.mtrlAppCode; } public void setMtrlAppCode(Integer mtrlAppCode) { this.mtrlAppCode = mtrlAppCode; } public Integer getDealerCode() { return this.dealerCode; } public void setDealerCode(Integer dealerCode) { this.dealerCode = dealerCode; } public Integer getCompanyCode() { return this.companyCode; } public void setCompanyCode(Integer companyCode) { this.companyCode = companyCode; } public String getMtrlCode() { return this.mtrlCode; } public void setMtrlCode(String mtrlCode) { this.mtrlCode = mtrlCode; } public String getMtrlNm() { return this.mtrlNm; } public void setMtrlNm(String mtrlNm) { this.mtrlNm = mtrlNm; } public Integer getaMtrlCnt() { return aMtrlCnt; } public void setaMtrlCnt(Integer aMtrlCnt) { this.aMtrlCnt = aMtrlCnt; } public Integer getrMtrlCnt() { return rMtrlCnt; } public void setrMtrlCnt(Integer rMtrlCnt) { this.rMtrlCnt = rMtrlCnt; } public Double getrMtrlAmt() { return rMtrlAmt; } public void setrMtrlAmt(Double rMtrlAmt) { this.rMtrlAmt = rMtrlAmt; } public String getTrackNum() { return this.trackNum; } public void setTrackNum(String trackNum) { this.trackNum = trackNum; } @JsonSerialize(using = EnumSerializer.class) public DealerMaterielStatusEnum getStatus() { return this.status; } public void setStatus(DealerMaterielStatusEnum status) { this.status = status; } public Date getAppDt() { return this.appDt; } public void setAppDt(Date appDt) { this.appDt = appDt; } public Date getGrantDt() { return this.grantDt; } public void setGrantDt(Date grantDt) { this.grantDt = grantDt; } public Date getCofimDt() { return cofimDt; } public void setCofimDt(Date cofimDt) { this.cofimDt = cofimDt; } public String getRemarks() { return this.remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getDealerName() { return dealerName; } public void setDealerName(String dealerName) { this.dealerName = dealerName; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public CmsMaterielInfo getInfo() { return info; } public void setInfo(CmsMaterielInfo info) { this.info = info; } public Task getTask() { return task; } public void setTask(Task task) { this.task = task; } }
e4005cd02cf451610a26ca764a7c8d437948f06d
bec686b9c0c0d95c99095097a5e604c5ef01828b
/jdo/rdbms/src/java/org/datanucleus/samples/rdbms/views/MinMaxWidgetValues.java
671e762f9e15d84ab6bdeaa835f14b683530d5d9
[ "Apache-2.0" ]
permissive
datanucleus/tests
d6bcbcf2df68841c1a27625a5509b87fa9ccfc9e
b47ac565c5988aba5c16389fb2870aafe9142522
refs/heads/master
2023-09-02T11:24:56.386187
2023-08-16T12:30:38
2023-08-16T12:30:38
14,927,016
10
18
Apache-2.0
2023-09-13T14:01:00
2013-12-04T15:10:03
Java
UTF-8
Java
false
false
3,746
java
/********************************************************************** Copyright (c) 2005 Andy Jefferson and others. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: ... **********************************************************************/ package org.datanucleus.samples.rdbms.views; import org.datanucleus.samples.rdbms.views.MinMaxWidgetValues; import org.datanucleus.tests.TestObject; public class MinMaxWidgetValues extends TestObject { private boolean booleanValue; private byte minByteValue; private short minShortValue; private int maxIntValue; private long maxLongValue; protected MinMaxWidgetValues() {} public MinMaxWidgetValues(boolean booleanValue) { this.booleanValue = booleanValue; this.minByteValue = Byte.MAX_VALUE; this.minShortValue = Short.MAX_VALUE; this.maxIntValue = Integer.MIN_VALUE; this.maxLongValue = Long.MIN_VALUE; } public boolean getBooleanValue() { return booleanValue; } public byte getMinByteValue() { return minByteValue; } public short getMinShortValue() { return minShortValue; } public int getMaxIntValue() { return maxIntValue; } public long getMaxLongValue() { return maxLongValue; } public void setMinByteValue(byte minByteValue) { this.minByteValue = minByteValue; } public void setMinShortValue(short minShortValue) { this.minShortValue = minShortValue; } public void setMaxIntValue(int maxIntValue) { this.maxIntValue = maxIntValue; } public void setMaxLongValue(long maxLongValue) { this.maxLongValue = maxLongValue; } public void fillRandom() { booleanValue = r.nextBoolean(); minByteValue = (byte)(r.nextInt(Byte.MAX_VALUE * 2) - Byte.MAX_VALUE); minShortValue = (short)(r.nextInt(Short.MAX_VALUE * 2) - Short.MAX_VALUE); maxIntValue = r.nextInt(); maxLongValue = r.nextLong(); } public boolean compareTo(Object obj) { if (obj == this) return true; if (!(obj instanceof MinMaxWidgetValues)) return false; MinMaxWidgetValues wv = (MinMaxWidgetValues)obj; return booleanValue == wv.booleanValue && minByteValue == wv.minByteValue && minShortValue == wv.minShortValue && maxIntValue == wv.maxIntValue && maxLongValue == wv.maxLongValue; } public String toString() { StringBuffer s = new StringBuffer(super.toString()); s.append(" booleanValue = ").append(booleanValue); s.append('\n'); s.append(" minByteValue = ").append(minByteValue); s.append('\n'); s.append(" minShortValue = ").append(minShortValue); s.append('\n'); s.append(" maxIntValue = ").append(maxIntValue); s.append('\n'); s.append(" maxLongValue = ").append(maxLongValue); s.append('\n'); return s.toString(); } }
9d978c17c9074f9121ba9f9c9db31985898815ee
d97bac5f40e7dcd592ad6139b715f02dbc17badf
/src/chandwani804/Browser.java
6465585a9936114a6765b29959b47b889da2a1e6
[]
no_license
ashishsc/TWIT
77052e6d271218610822f44f1987a325f3f6f923
78448ba8b98f5709cd505a76ff11e36b51de00c7
refs/heads/master
2016-09-05T11:06:12.726869
2013-10-24T05:54:12
2013-10-24T05:54:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,898
java
package chandwani804; import com.apple.dnssd.*; public class Browser implements BrowseListener, ResolveListener { // service should probably be something like "http" private DNSSDService browser; private DNSSDService resolver; private OnlineList onlineList; private String myID; /** * @param service * @param onlineList */ public Browser(String service, OnlineList onlineList, String myID) { String sdService = "_" + service + "._tcp"; browser = null; browse(sdService); this.onlineList = onlineList; this.myID = myID; } public void browse(String sdService) { if (browser == null) { try { browser = DNSSD.browse(sdService, this); Console.message("Browser", "browse(): looking for " + sdService); } catch (DNSSDException e) { Console.message("Browser", "Exception on browse: " + e.toString()); } } } // Part of BrowseListener interface public void serviceFound(DNSSDService br, int flags, int ifIndex, String serviceName, String regType, String domain) { // Console.message("Browser", instanceName); try { DNSSD.resolve(0, DNSSD.ALL_INTERFACES, serviceName, regType, domain, this); } catch (DNSSDException e) { Console.message("Browser", "Exception on resolve: " + e.toString()); } } // Part of BrowseListener interface // Remove the lost person from the online list public void serviceLost(DNSSDService br, int flags, int ifIndex, String serviceName, String regType, String domain) { synchronized (onlineList) { if (onlineList.containsName(serviceName)) { TwitPeer peer = onlineList.remove(serviceName); Console.message("Browser", peer.getName() + " went offline"); } else { Console.message("Browser", serviceName + " went offline (couldn't remove)"); } } } // Once the service is resolved, add someone to online list public void serviceResolved(DNSSDService resolver, int flags, int ifIndex, String fullName, String hostName, int port, TXTRecord record) { resolver.stop(); resolver = null; // Add to online list synchronized (onlineList) { // Verify that the ID of the registered user is not my own. if (!(record.getValueAsString(3)).equalsIgnoreCase(myID)) { // BAD: Assumes serviceName == DisplayName from the txtrec String name = record.getValueAsString("DisplayName"); onlineList.add(hostName, port, record); Console.message("Browser", name + " is online."); } else { Console.message("Browser", "You are now online"); } } } // Part of BrowseListener interface public void operationFailed(DNSSDService service, int errorCode) { Console.message("Browser", "Operation Failure, errorCode: " + errorCode); } // Close browser and any open resolver public void close() { if (browser != null) { browser.stop(); browser = null; } if (resolver != null) { resolver.stop(); resolver = null; } } }
e2708b2148a50bdf1dfd81e9140f4e4be57bcdd2
63b01ff5eb91dc134a5ae5812c59ee66b7107b5e
/src/main/java/co/axelrod/ibm/mq/client/mq/MQUtil.java
8191d49a15eb2818847896ec481709b85c2cbac6
[]
no_license
axelrodvl/ibm-mq-client
85cf98579b2f5951dbaa50f11913b88139206065
3923ad1e4bc95fb3a18ae52867d13f6af0244fee
refs/heads/main
2023-01-01T00:22:49.397063
2020-10-16T15:54:16
2020-10-16T15:54:16
304,337,057
0
0
null
null
null
null
UTF-8
Java
false
false
752
java
package co.axelrod.ibm.mq.client.mq; import co.axelrod.ibm.mq.client.configuration.MQConfiguration; import com.ibm.mq.MQEnvironment; public class MQUtil { private MQUtil() { // Utility class } public static void initializeMQEnvironment(MQConfiguration mqConfiguration) { MQEnvironment.hostname = mqConfiguration.getHost(); MQEnvironment.port = mqConfiguration.getPort(); MQEnvironment.channel = mqConfiguration.getChannel(); MQEnvironment.userID = mqConfiguration.getUser(); MQEnvironment.password = mqConfiguration.getPassword(); if (mqConfiguration.getSslCipherSuite() != null) { MQEnvironment.sslCipherSuite = mqConfiguration.getSslCipherSuite(); } } }
2c9f259e8f96675adaf5592744447ecf966a9594
73e61e3970027974d519c13cc1f3e3d19c06653d
/app/src/main/java/com/benjaminfinlay/activitytracker/TrackedListFragment.java
6837c85548424c94c026d12945ec2586d9a33cf2
[]
no_license
usc-bjf017/ActivityTracker_BJF017
8e769d3c624e3e48fb0508ae2de65627b5a473f9
d45673168d75561566f3d4ea1ca758f614cf27d5
refs/heads/master
2020-08-23T02:13:46.927568
2019-10-31T14:41:49
2019-10-31T14:41:49
216,521,687
0
0
null
null
null
null
UTF-8
Java
false
false
5,715
java
package com.benjaminfinlay.activitytracker; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Stack; /** * Controls a list of Tracked Activity's to be viewed and clicked on. * Controls menu bar on the list page. */ public class TrackedListFragment extends ListFragment { /** * Triggered when the Fragment is created * @param savedInstanceState App's compiled code and resources. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); getActivity().setTitle(R.string.tracked_title); Stack<Tracked> mTracked = TrackedManager.get(getActivity()).getAllTracked(); TrackedAdapter adapter = new TrackedAdapter(mTracked); setListAdapter(adapter); } /** * Triggers when a Tracked Activity is clicked on the list. Opening the Tracked Activity in * a larger view with the remaining information. * @param l List that the list item is in. * @param v Current view the list is in. * @param position Position of list item in list. To be used to get the Tracked Activity at position in data base. * @param id Id of list item. */ @Override public void onListItemClick(ListView l, View v, int position, long id) { Tracked a = ((TrackedAdapter)getListAdapter()).getItem(position); // Start CrimePagerActivity with this crime Intent i = new Intent(getActivity(), TrackedPagerActivity.class); if (a != null) { i.putExtra(TrackedFragment.EXTRA_TRACKED_ID, a.getUUID()); } startActivity(i); } /** * Custom adapter to list custom list items. * Card view displaying: * - Title * - Place * - Date */ private class TrackedAdapter extends ArrayAdapter<Tracked> { /** * Constructor for custom adapter * @param tracked Stack of tracked activity's to be added to the list. */ TrackedAdapter(Stack<Tracked> tracked) { super(getActivity(), 0, tracked); } /** * Creates or gets an old view for each of the list items. * @param position Position of new item in list in Stack/List. * @param convertView Converts an old view to be used on the list again. * @param parent The view that the list is a child of. * @return Returns the new list items view. */ @Override public View getView(int position, View convertView, ViewGroup parent) { // If we weren't given a view, inflate one if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_tracked, null); } // Configure the view for this tracked activity Tracked a = getItem(position); // Title Input TextView titleTextView = (TextView)convertView.findViewById(R.id.tracked_list_item_titleTextView); titleTextView.setText(a.getTitle()); // Place Input TextView placeTextView = (TextView)convertView.findViewById(R.id.tracked_list_item_placeTextView); placeTextView.setText(a.getPlace()); // Date Input TextView dateTextView = (TextView)convertView.findViewById(R.id.tracked_list_item_dateTextView); SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); dateTextView.setText(formatter.format(a.getDate())); return convertView; } } /** * Runs every time the List Fragment is opened or resumed. E.g. if the screen is locked then reopened. */ @Override public void onResume() { super.onResume(); ((TrackedAdapter)getListAdapter()).notifyDataSetChanged(); } /** * Triggered to create the menu bar at the top of the page * @param menu Menu * @param inflater Used to inflate the menu XML. */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.fragment_tracked_list, menu); } /** * Triggered when an item on the menu bar is clicked. * @param item Menu item that was clicked * @return Returns true or false if the click was handled. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Button used to create a new activity and open Tracked Pager view with new activity case R.id.menu_activity: Tracked tracked = new Tracked(); TrackedManager.get(getActivity()).addTracked(tracked); Intent i = new Intent(getActivity(), TrackedPagerActivity.class); i.putExtra(TrackedFragment.EXTRA_TRACKED_ID, tracked.getUUID()); startActivityForResult(i, 0); return true; // Sends the user to the help page, launching the TrackedWebActivity and Fragment. case R.id.menu_help: Intent a = new Intent(getActivity(), TrackedWebActivity.class); startActivityForResult(a, 0); return true; default: return super.onOptionsItemSelected(item); } } }
6145ceba1c37c223f343417e12aef7982d7cd446
f6e4c5e955bef4d7e3f098fb70845a8dee8ecf56
/src/com/company/Commercial.java
c66f8cdfc1bb96a960d6515ff5601712a4b9d0f4
[]
no_license
TheLostKing/MAD105Inheritance
ce9be0d8d64b772e80c7db75e56bbeac1968e44e
2b6307caf48bd4b5796c13a9a311da021e554ee3
refs/heads/master
2021-07-12T17:06:01.103686
2017-10-16T04:56:49
2017-10-16T04:56:49
107,079,837
0
0
null
null
null
null
UTF-8
Java
false
false
1,321
java
package com.company; public class Commercial extends Employee { String propertyName; static double RATE = .0005; boolean multiProperty; public Commercial(String customerName, String customerAddress, String customerPhone, double squareFootage, String propertyName, boolean multiProperty){ super(customerName, customerAddress, customerPhone, squareFootage); setPropertyName(propertyName); setMultiProperty(multiProperty); } public String getPropertyName() { return propertyName; } public boolean getMultiProperty() { return multiProperty; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public void setMultiProperty(boolean multiProperty) { this.multiProperty = multiProperty; } public double weeklyCharge(){ //calculates weekly charge double charge = super.getSquareFootage() * RATE; if(multiProperty){ //checks if there are multiple properties and gives the discount if so charge *= .9; } return charge; } @Override public String toString() { return super.toString() + "\nProperty Name: " + getPropertyName() + "\nMulti-property: " + getMultiProperty() + "\nWeekly Charge: " + weeklyCharge(); } }
fc9a3cb6846f6c6a69749cd4d26dd020f27fc35f
d0cd9f6e13a9f1c51f16fc9e12d3792b738f6b04
/Civ/GUI/gui/elements/GuiElementMultiTable.java
765a62c759dd6abf3079924c7ef2aa2d7a0904d8
[]
no_license
IlyaSamoVal/Civ-b
6206902a648a0f52199a1c1525b3252b1df78014
a7b4ef63db30e4fc312454f60fbff53f1fb49189
refs/heads/master
2020-07-26T22:11:56.676221
2014-11-09T07:32:12
2014-11-09T07:32:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,266
java
package gui.elements; import java.awt.Graphics; import java.awt.Image; import javax.media.opengl.GL3; import recources.Recources; import gui.GuiElement; import gui.misc.MultiTableLine; public class GuiElementMultiTable extends GuiElement { public static final int lineSize = 20; // data protected MultiTableLine list; protected int selected = -1; // slider protected int elementsMax = 0; protected Image textureSlider; protected float scaling = 0; protected int scroll = 0; protected int sliderPos = 0; protected int sliderScale = 0; protected boolean scrolled = true; public GuiElementMultiTable(String title) { super(title); list = new MultiTableLine(""); list.setRoot(); MultiTableLine line = new MultiTableLine(""); list.addLine(line); this.textureSlider = Recources.getImage("slider"); } public void addLine(MultiTableLine line){ list.addLine(line); } public void select(int line) { list.select(selected, false); list.select(line + scroll + 1, true); this.selected = line + scroll + 1; } public int getTableSize(){ return list.getSize() - 2; // -2 because .root() and .first(); } public void scroll(float percent, int mouseY){ this.scroll = (int)((float)getTableSize() * percent); this.scrolled = true; } @Override public void setSize(int sizeX, int sizeY) { this.elementsMax = (sizeY - 10) / GuiElementMultiTable.lineSize; super.setSize(sizeX, sizeY); } @Override public void draw(Graphics g, long tic) { if(visible){ // afterscrolling update slider position if(scrolled){ scrolled = false; scaling = (float)elementsMax / (float)getTableSize(); sliderScale = (int)((sizeY - 10) * scaling); sliderPos = (int)(scroll * scaling * GuiElementMultiTable.lineSize); if(sliderPos + sliderScale >= sizeY){ System.out.println("size " + sizeY + " pos " + (sliderPos + sliderScale)); sliderPos = sizeY - sliderScale - 5; } } // draw Table g.drawImage(textureNormal, drawX, drawY, sizeX, sizeY, null); g.drawImage(textureSlider, drawX + sizeX - 15, drawY + sliderPos + 5, 15, sliderScale, null); list.setDraw(drawX, drawY, scroll, sizeX, drawX); list.draw(g, tic); } } @Override public void draw(GL3 gl) { } }
ff252d09a59a5e453bc7c2c953f504ec8bbe52a2
89c84e2d0d69e36f4643517b93341a7d823caa9d
/app/src/androidTest/java/com/learn/template/ExampleInstrumentedTest.java
fb314af2d38a04fbd54f0c0813464edd42f7f2ee
[]
no_license
bingoloves/Template
c6608428be0a77f6adacee078beee95440b4c93b
29ebeb5bffac54c8ac66b228f1cde0dc8894f369
refs/heads/master
2022-11-15T02:18:45.478113
2020-07-15T09:40:10
2020-07-15T09:40:10
273,198,103
0
0
null
null
null
null
UTF-8
Java
false
false
737
java
package com.learn.template; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.learn.template", appContext.getPackageName()); } }
101ea5061223a26e9eeca2e88181352718a3d0a7
52114455921aa53072c06e4d53afcf7022cdc28f
/src/main/java/com/mmall/dao/SysRoleMapper.java
f11a05fade4963d6ab33b5c8c2a7501e3e028051
[]
no_license
GravesG/permission
701c8b0e7303a16fa3f56992da18f5711ddfdd8e
6471e2288802d5d78b360d25040e2f389f25dbaf
refs/heads/master
2020-04-09T08:42:34.185274
2019-03-02T07:43:23
2019-03-02T07:43:23
160,205,304
1
0
null
null
null
null
UTF-8
Java
false
false
603
java
package com.mmall.dao; import com.mmall.model.SysRole; import org.apache.ibatis.annotations.Param; import java.util.List; public interface SysRoleMapper { int deleteByPrimaryKey(Integer id); int insert(SysRole record); int insertSelective(SysRole record); SysRole selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(SysRole record); int updateByPrimaryKey(SysRole record); List<SysRole> getAll(); int countByName(@Param("name") String name,@Param("id") Integer id); //TODO List<SysRole> getByIdList(@Param("idList") List<Integer> idList); }
0a7774f96337e32f8bd560a3b21b23f7710360ce
82b95bcae448456685d0ec3e38ba4d47d2f5e178
/maven-demo/springboot/server-demo/src/main/java/com/xad/server/service/OrganizationService.java
d11316882745da642d679b7a7fcda40cf0ba86ed
[]
no_license
LeonEDs/MyRepository
13fc4b594958ce0a8dd6df6b0c253758331f05df
031fe5d4f7397ef2a7ffc9963a1482de8196676e
refs/heads/master
2022-10-27T18:27:53.151672
2021-06-04T07:40:55
2021-06-04T07:40:55
152,078,675
0
0
null
2022-10-05T18:22:48
2018-10-08T12:46:37
Java
UTF-8
Java
false
false
782
java
package com.xad.server.service; import com.xad.server.dto.OrganizationDto; import java.util.List; /** * 组织 Service. * @version 1.0 * @author xad * @date 2020/12/24 0024 */ public interface OrganizationService { /** * 查询板块下所有营运组织信息 */ List<OrganizationDto> queryInfoBySector(OrganizationDto vo); /** * 查询营运组织信息 */ List<OrganizationDto> queryInfoFuzzyName(OrganizationDto vo); /** * 查询营运组织信息 */ OrganizationDto queryOneInfoByOrgCode(String orgCode); /** * 查询营运企业名称 */ String queryNameByOrgCode(String orgCode); /** * 查询营运企业所属的板块 */ String querySectorByEnterprise(String orgCode); }
3031195e766f6794998de85a8be7758e644f8d6d
37048b9a888cf825acc6861ed7e1c1ac4522a4aa
/photography-jwtService/src/main/java/com/topnotch/demo/models/Authority.java
5f36bde9c938890979450d5daaa2d56ce04fa83f
[]
no_license
testapp93/microservice-doc-upload-project
78a6a51e89d2a11cd5ae59db69086620a68aa546
69e349d088ad390c876e8d10a848943fcf74f283
refs/heads/main
2023-08-05T11:08:42.614972
2021-09-07T10:34:09
2021-09-07T10:34:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,050
java
package com.topnotch.demo.models; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="user_authorities") @IdClass(AuthorityKey.class) public class Authority implements Serializable { // FOREIGN KEY @Id @ManyToOne @JoinColumn(name = "email", referencedColumnName = "email") private DBUser username; // PRIMARY KEY @Id @Column(name = "authority") private String authority; public Authority() { super(); } public Authority(DBUser username, String authority) { super(); this.username = username; this.authority = authority; } public DBUser getUsername() { return username; } public void setUsername(DBUser username) { this.username = username; } public String getAuthority() { return authority; } public void setAuthority(String authority) { this.authority = authority; } }
1f0fecc3b21b760649074385ebb061f5a3f1a515
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_a9dfac0a1adb069539bc714e4608570c159bea96/HtmlTable/2_a9dfac0a1adb069539bc714e4608570c159bea96_HtmlTable_s.java
13e0fcf012c4f0af853590e2ec0189986b55f762
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
11,979
java
/* * [The "BSD licence"] * Copyright (c) 2012 Dandelion * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Dandelion nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.github.dandelion.datatables.core.html; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.NestedNullException; import org.apache.commons.beanutils.PropertyUtils; import com.github.dandelion.datatables.core.configuration.ConfigurationLoader; import com.github.dandelion.datatables.core.configuration.TableConfiguration; import com.github.dandelion.datatables.core.export.ExportConf; import com.github.dandelion.datatables.core.util.ResourceHelper; import com.github.dandelion.datatables.core.util.StringUtils; /** * Plain old HTML <code>table</code> tag. * * @author Thibault Duchateau * @since 0.1.0 */ public class HtmlTable extends HtmlTag { // Internal attributes private HtmlCaption caption; private List<HtmlRow> head = new LinkedList<HtmlRow>(); private List<HtmlRow> body = new LinkedList<HtmlRow>(); private List<HtmlRow> foot = new LinkedList<HtmlRow>(); private TableConfiguration tableConfiguration; private String randomId; public HtmlTable(String id, HttpServletRequest request) { this.tag = "table"; this.randomId = ResourceHelper.getRamdomNumber(); this.id = id; tableConfiguration = TableConfiguration.getInstance(request); tableConfiguration.setTableId(id); } public HtmlTable(String id, HttpServletRequest request, String groupName) { this.tag = "table"; this.randomId = ResourceHelper.getRamdomNumber(); this.id = id; tableConfiguration = TableConfiguration.getInstance(request, groupName); tableConfiguration.setTableId(id); } public HtmlTable(String id) { this.tag = "table"; this.randomId = ResourceHelper.getRamdomNumber(); this.id = id; } public HtmlTable(String id, HttpServletRequest request, String groupName, Map<String, String> dynamicAttributes) { this.tag = "table"; this.randomId = ResourceHelper.getRamdomNumber(); this.id = id; this.dynamicAttributes = dynamicAttributes; tableConfiguration = TableConfiguration.getInstance(request, groupName); tableConfiguration.setTableId(id); } /** * {@inheritDoc} */ @Override public StringBuilder toHtml() { if(StringUtils.isNotBlank(this.tableConfiguration.getExtraAppear())){ addCssStyle("display:none;"); } StringBuilder html = new StringBuilder(); html.append(getHtmlOpeningTag()); html.append(getHtmlHeader()); html.append(getHtmlBody()); html.append(getHtmlFooter()); html.append(getHtmlClosingTag()); return html; } private StringBuilder getHtmlHeader() { StringBuilder html = new StringBuilder(); if (this.caption != null) { html.append(this.caption.toHtml()); } html.append("<thead>"); for (HtmlRow row : this.head) { html.append(row.toHtml()); } html.append("</thead>"); return html; } private StringBuilder getHtmlBody() { StringBuilder html = new StringBuilder(); html.append("<tbody>"); for (HtmlRow row : this.body) { html.append(row.toHtml()); } html.append("</tbody>"); return html; } private StringBuilder getHtmlFooter() { StringBuilder html = new StringBuilder(); if (!this.foot.isEmpty()) { html.append("<tfoot>"); for (HtmlRow row : this.foot) { html.append(row.toHtml()); } html.append("</tfoot>"); } return html; } protected StringBuilder getHtmlAttributes() { StringBuilder html = new StringBuilder(); html.append(writeAttribute("id", this.id)); html.append(writeAttribute("class", this.tableConfiguration.getCssClass())); html.append(writeAttribute("style", this.tableConfiguration.getCssStyle())); return html; } public HtmlCaption getCaption() { return caption; } public void setCaption(HtmlCaption caption) { this.caption = caption; } public List<HtmlRow> getHeadRows() { return head; } public List<HtmlRow> getBodyRows() { return body; } public HtmlRow addHeaderRow() { HtmlRow row = new HtmlRow(); this.head.add(row); return row; } public HtmlRow addRow() { HtmlRow row = new HtmlRow(); this.body.add(row); return row; } public HtmlRow addFooterRow() { HtmlRow row = new HtmlRow(); this.foot.add(row); return row; } public HtmlRow addRow(String rowId) { HtmlRow row = new HtmlRow(rowId); this.body.add(row); return row; } public HtmlTable addRows(HtmlRow... rows) { for (HtmlRow row : rows) { this.body.add(row); } return this; } public HtmlRow getLastFooterRow() { return ((LinkedList<HtmlRow>) this.foot).getLast(); } public HtmlRow getFirstHeaderRow() { return ((LinkedList<HtmlRow>) this.head).getFirst(); } public HtmlRow getLastHeaderRow() { return ((LinkedList<HtmlRow>) this.head).getLast(); } public HtmlRow getLastBodyRow() { return ((LinkedList<HtmlRow>) this.body).getLast(); } public void addCssStyle(String cssStyle) { if(this.tableConfiguration.getCssStyle() == null) { this.tableConfiguration.setCssStyle(new StringBuilder()); } else { this.tableConfiguration.getCssStyle().append(CSS_SEPARATOR); } this.tableConfiguration.getCssStyle().append(cssStyle); } public void addCssClass(String cssClass) { if(this.tableConfiguration.getCssClass() == null) { this.tableConfiguration.setCssClass(new StringBuilder()); } else { this.tableConfiguration.getCssClass().append(CLASS_SEPARATOR); } this.tableConfiguration.getCssClass().append(cssClass); } public HtmlColumn getColumnHeadByUid(String uid) { for (HtmlRow row : this.head) { for (HtmlColumn column : row.getColumns()) { if (column.isHeaderColumn() != null && column.isHeaderColumn() && column.getColumnConfiguration().getUid() != null && column.getColumnConfiguration().getUid().equals(uid)) { return column; } } } return null; } public String getRandomId() { return randomId; } public void setRandomId(String randomId) { this.randomId = randomId; } public TableConfiguration getTableConfiguration() { return tableConfiguration; } public void setTableConfiguration(TableConfiguration tableConfiguration) { this.tableConfiguration = tableConfiguration; } /** * HtmlTable builder, allowing you to build a table in an export controller * for example. */ public static class Builder<T> { private String id; private List<T> data; private LinkedList<HtmlColumn> headerColumns = new LinkedList<HtmlColumn>(); private HttpServletRequest request; private ExportConf exportConf; public Builder(String id, List<T> data, HttpServletRequest request) { this.id = id; this.data = data; this.request = request; } // Table configuration public Builder<T> column(String property) { HtmlColumn column = new HtmlColumn(true, ""); column.getColumnConfiguration().setProperty(property); column.getColumnConfiguration().setTitle(property); headerColumns.add(column); return this; } public Builder<T> title(String title) { headerColumns.getLast().getColumnConfiguration().setTitle(title); return this; } public Builder<T> format(String pattern) { headerColumns.getLast().getColumnConfiguration().setFormat(pattern); return this; } public Builder<T> defaultContent(String defaultContent) { headerColumns.getLast().getColumnConfiguration().setDefaultValue(defaultContent); return this; } public Builder<T> configureExport(ExportConf exportConf) { this.exportConf = exportConf; return this; } public HtmlTable build() { return new HtmlTable(this); } } /** * Private constructor used by the Builder to build a HtmlTable in a fluent * way. * * @param builder */ private <T> HtmlTable(Builder<T> builder) { this.tag = "table"; this.id = builder.id; this.tableConfiguration = TableConfiguration .getInstance(builder.request, ConfigurationLoader.DEFAULT_GROUP_NAME); this.tableConfiguration.setExportConfs(new HashSet<ExportConf>(Arrays.asList(builder.exportConf))); if(builder.data != null && builder.data.size() > 0){ this.tableConfiguration.setInternalObjectType(builder.data.get(0).getClass().getSimpleName()); } else{ this.tableConfiguration.setInternalObjectType("???"); } addHeaderRow(); for (HtmlColumn column : builder.headerColumns) { column.setContent(new StringBuilder(column.getColumnConfiguration().getTitle())); getLastHeaderRow().addColumn(column); } if (builder.data != null) { for (T o : builder.data) { addRow(); for (HtmlColumn headerColumn : builder.headerColumns) { Object content = null; try { content = PropertyUtils.getNestedProperty(o, headerColumn.getColumnConfiguration().getProperty().toString().trim()); // If a format exists, we format the property if (StringUtils.isNotBlank(headerColumn.getColumnConfiguration().getFormat()) && content != null) { MessageFormat messageFormat = new MessageFormat(headerColumn.getColumnConfiguration().getFormat()); content = messageFormat.format(new Object[] { content }); } else if (StringUtils.isBlank(headerColumn.getColumnConfiguration().getFormat()) && content != null) { content = content.toString(); } else { if (StringUtils.isNotBlank(headerColumn.getColumnConfiguration().getDefaultValue())) { content = headerColumn.getColumnConfiguration().getDefaultValue().trim(); } } } catch (NestedNullException e) { if (StringUtils.isNotBlank(headerColumn.getColumnConfiguration().getDefaultValue())) { content = headerColumn.getColumnConfiguration().getDefaultValue().trim(); } } catch (IllegalAccessException e) { content = ""; } catch (InvocationTargetException e) { content = ""; } catch (NoSuchMethodException e) { content = ""; } catch (IllegalArgumentException e) { content = ""; } getLastBodyRow().addColumn(String.valueOf(content)); } } } } }