text
stringlengths
10
2.72M
package com.project.battle; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import com.project.ActionBox; import com.project.DraggableIcon; import com.project.Handler; import com.project.button.Button; import com.project.slider.VerticalSliderHandle; public class BattleHandler extends Handler { private BattleScreen bs; public BattleHandler(BattleScreen bs) { this.bs=bs; } public BattleHandler() { } public boolean clickShip(int x , int y) { if (bs.checkShipClick(x,y)) { return bs.clickShip(x,y); } return false; } public int getLayerClicked(int x,int y) { return bs.getLayerClicked(x,y); } public boolean checkLeftClick(int x, int y, int button) { if(checkButtons(x, y,button)){ return true;} return clickShip(x,y); } public void updateMouse(int x,int y) { super.updateMouse(x, y); } public void checkDrag(int x, int y, int button) { if(dragging instanceof Button) { ((Button) dragging ).drag(x,y,button); } if(dragging instanceof DraggableIcon) { ((DraggableIcon) dragging ).drag(x,y); } if(dragging instanceof VerticalSliderHandle){ ((VerticalSliderHandle) dragging).drag(x,y); } } public boolean checkPress(int x, int y, int button) { if(dragging == null) { // check all draggable objects for(int i = 0; i<buttons.size();i++) { if(buttons.get(i).isDraggable()&&buttons.get(i)!=null && buttons.get(i).isInside(x, y)) { dragging = buttons.get(i); return true; } } for(int i = 0; i<icons.size();i++) { if(icons.get(i).isInside(x, y)) { dragging = icons.get(i); return true; } } for(int i = 0; i<handles.size();i++) { if(handles.get(i).isInside(x, y)) { dragging = handles.get(i); handles.get(i).grabbed(x, y); return true; } } } return false; } public boolean checkRelease(int x, int y, int button) { if(dragging == null) { return false; } if(dragging instanceof DraggableIcon) { List<ActionBox> boxes = new ArrayList<ActionBox>(); boxes.addAll(BattleUI.actionBoxes); boxes.addAll(BattleUI.manoeuvreActionBoxes); ((DraggableIcon) dragging ).drop(boxes); if(button == MouseEvent.BUTTON3) {((DraggableIcon)dragging).reset();} } if (dragging instanceof VerticalSliderHandle){ ((VerticalSliderHandle) dragging).drop(); } dragging = null; return true; } public void checkRightClick(int x, int y) { checkDraggableIcons(x,y); } private boolean checkDraggableIcons(int x, int y) { for(int i = 0; i<icons.size();i++) { if(icons.get(i).isInside(x, y)) { icons.get(i).reset(); return true; } } return false; } public static void changeMouseIcon(String path){ changeMouseIcon(path); } public BattleScreen getBs() { return bs; } public void setBs(BattleScreen bs) { this.bs = bs; } }
package com.pisen.ott.launcher.service; import com.pisen.ott.launcher.HomeActivity; import android.content.Context; import android.izy.service.WifiService; import android.net.wifi.WifiInfo; /** * 1、定时检查内容是否有更新 * 2、下载图片 * @author Liuhc * @version 1.0 2015年1月9日 下午2:14:15 */ public class UIContentUpdateService extends WifiService { private Context mContext; @Override public void onCreate() { super.onCreate(); this.mContext = getApplication(); } @Override public void onWifiConnected(WifiInfo info) { // 检查是否有等待下载任务 ImageDownLoader.getDownLoader(mContext).checkQueue(); } @Override public void onWifiDisconnected(WifiInfo info) { ImageDownLoader.getDownLoader(mContext).cancelTasks(); } @Override public void onDestroy() { ImageDownLoader.getDownLoader(mContext).cancelTasks(); super.onDestroy(); } }
/* * Copyright © 2020-2022 ForgeRock AS (obst@forgerock.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.org.openbanking.datamodel.service.converter.payment; import uk.org.openbanking.datamodel.payment.*; import static uk.org.openbanking.datamodel.service.converter.payment.OBConsentAuthorisationConverter.*; import static uk.org.openbanking.datamodel.service.converter.payment.OBDomesticScheduledConverter.*; public class OBWriteDomesticScheduledConsentConverter { public static OBWriteDomesticScheduledConsent1 toOBWriteDomesticScheduledConsent1(OBWriteDomesticScheduledConsent2 obWriteDomesticScheduledConsent2) { return (new OBWriteDomesticScheduledConsent1()) .data(toOBWriteDataDomesticScheduledConsent1(obWriteDomesticScheduledConsent2.getData())) .risk(obWriteDomesticScheduledConsent2.getRisk()); } public static OBWriteDomesticScheduledConsent1 toOBWriteDomesticScheduledConsent1(OBWriteDomesticScheduledConsent3 obWriteDomesticScheduledConsent3) { return (new OBWriteDomesticScheduledConsent1()) .data(toOBWriteDataDomesticScheduledConsent1(obWriteDomesticScheduledConsent3.getData())) .risk(obWriteDomesticScheduledConsent3.getRisk()); } public static OBWriteDomesticScheduledConsent1 toOBWriteDomesticScheduledConsent1(OBWriteDomesticScheduledConsent4 domesticScheduledConsent4) { return domesticScheduledConsent4 == null ? null : (new OBWriteDomesticScheduledConsent1()) .data(toOBWriteDataDomesticScheduledConsent1(domesticScheduledConsent4.getData())) .risk(domesticScheduledConsent4.getRisk()); } public static OBWriteDomesticScheduledConsent2 toOBWriteDomesticScheduledConsent2(OBWriteDomesticScheduledConsent1 obWriteDomesticScheduledConsent1) { return (new OBWriteDomesticScheduledConsent2()) .data(toOBWriteDataDomesticScheduledConsent2(obWriteDomesticScheduledConsent1.getData())) .risk(obWriteDomesticScheduledConsent1.getRisk()); } public static OBWriteDomesticScheduledConsent3 toOBWriteDomesticScheduledConsent3(OBWriteDomesticScheduledConsent2 obWriteDomesticScheduledConsent2) { return (new OBWriteDomesticScheduledConsent3()) .data(toOBWriteDomesticScheduledConsent3Data(obWriteDomesticScheduledConsent2.getData())) .risk(obWriteDomesticScheduledConsent2.getRisk()); } public static OBWriteDomesticScheduledConsent3 toOBWriteDomesticScheduledConsent3(OBWriteDomesticScheduledConsent1 obWriteDomesticScheduledConsent1) { return (new OBWriteDomesticScheduledConsent3()) .data(toOBWriteDomesticScheduledConsent3Data(obWriteDomesticScheduledConsent1.getData())) .risk(obWriteDomesticScheduledConsent1.getRisk()); } public static OBWriteDomesticScheduledConsent4 toOBWriteDomesticScheduledConsent4(OBWriteDomesticScheduledConsent1 obWriteDomesticScheduledConsent1) { return (new OBWriteDomesticScheduledConsent4()) .data(toOBWriteDomesticScheduledConsent4Data(obWriteDomesticScheduledConsent1.getData())) .risk(obWriteDomesticScheduledConsent1.getRisk()); } public static OBWriteDomesticScheduledConsent4 toOBWriteDomesticScheduledConsent4(OBWriteDomesticScheduledConsent2 obWriteDomesticScheduledConsent2) { return (new OBWriteDomesticScheduledConsent4()) .data(toOBWriteDomesticScheduledConsent4Data(obWriteDomesticScheduledConsent2.getData())) .risk(obWriteDomesticScheduledConsent2.getRisk()); } public static OBWriteDomesticScheduled2 toOBWriteDomesticScheduled2(OBWriteDomesticScheduled1 obWriteDomesticScheduled1) { return (new OBWriteDomesticScheduled2()) .data(toOBWriteDomesticScheduled2Data(obWriteDomesticScheduled1.getData())) .risk(obWriteDomesticScheduled1.getRisk()); } public static OBWriteDataDomesticScheduledConsent1 toOBWriteDataDomesticScheduledConsent1(OBWriteDataDomesticScheduledConsent2 data) { return data == null ? null : (new OBWriteDataDomesticScheduledConsent1()) .permission(data.getPermission()) .initiation(toOBDomesticScheduled1(data.getInitiation())) .authorisation(data.getAuthorisation()); } public static OBWriteDataDomesticScheduledConsent1 toOBWriteDataDomesticScheduledConsent1(OBWriteDomesticScheduledConsent3Data data) { return data == null ? null : (new OBWriteDataDomesticScheduledConsent1()) .permission(data.getPermission()) .initiation(toOBDomesticScheduled1(data.getInitiation())) .authorisation(toOBAuthorisation1(data.getAuthorisation())); } public static OBWriteDataDomesticScheduledConsent1 toOBWriteDataDomesticScheduledConsent1(OBWriteDomesticScheduledConsent4Data data) { return data == null ? null : (new OBWriteDataDomesticScheduledConsent1()) .permission(data.getPermission()) .initiation(toOBDomesticScheduled1(data.getInitiation())) .authorisation(toOBAuthorisation1(data.getAuthorisation())); } public static OBWriteDataDomesticScheduledConsent2 toOBWriteDataDomesticScheduledConsent2(OBWriteDataDomesticScheduledConsent1 data) { return data == null ? null : (new OBWriteDataDomesticScheduledConsent2()) .permission(data.getPermission()) .initiation(toOBDomesticScheduled2(data.getInitiation())) .authorisation(data.getAuthorisation()); } public static OBWriteDomesticScheduledConsent3Data toOBWriteDomesticScheduledConsent3Data(OBWriteDataDomesticScheduledConsent1 data) { return data == null ? null : (new OBWriteDomesticScheduledConsent3Data()) .permission(data.getPermission()) .initiation(toOBWriteDomesticScheduled2DataInitiation(data.getInitiation())) .authorisation(toOBWriteDomesticConsent3DataAuthorisation(data.getAuthorisation())) .scASupportData(null); } public static OBWriteDomesticScheduledConsent4Data toOBWriteDomesticScheduledConsent4Data(OBWriteDataDomesticScheduledConsent1 data) { return data == null ? null : (new OBWriteDomesticScheduledConsent4Data()) .permission(data.getPermission()) .readRefundAccount(null) .initiation(toOBWriteDomesticScheduled2DataInitiation(data.getInitiation())) .authorisation(toOBWriteDomesticConsent4DataAuthorisation(data.getAuthorisation())) .scASupportData(null); } public static OBWriteDomesticScheduledConsent4Data toOBWriteDomesticScheduledConsent4Data(OBWriteDataDomesticScheduledConsent2 data) { return data == null ? null : (new OBWriteDomesticScheduledConsent4Data()) .permission(data.getPermission()) .readRefundAccount(null) .initiation(toOBWriteDomesticScheduled2DataInitiation(data.getInitiation())) .authorisation(toOBWriteDomesticConsent4DataAuthorisation(data.getAuthorisation())) .scASupportData(null); } public static OBWriteDomesticScheduledConsent3Data toOBWriteDomesticScheduledConsent3Data(OBWriteDataDomesticScheduledConsent2 data) { return data == null ? null : (new OBWriteDomesticScheduledConsent3Data()) .permission(data.getPermission()) .initiation(toOBWriteDomesticScheduled2DataInitiation(data.getInitiation())) .authorisation(toOBWriteDomesticConsent3DataAuthorisation(data.getAuthorisation())); } public static OBWriteDataDomesticScheduled2 toOBWriteDataDomesticScheduled2(OBWriteDataDomesticScheduled1 data) { return data == null ? null : (new OBWriteDataDomesticScheduled2()) .consentId(data.getConsentId()) .initiation(toOBDomesticScheduled2(data.getInitiation())); } public static OBWriteDomesticScheduled2Data toOBWriteDomesticScheduled2Data(OBWriteDataDomesticScheduled1 data) { return data == null ? null : (new OBWriteDomesticScheduled2Data()) .consentId(data.getConsentId()) .initiation(toOBWriteDomesticScheduled2DataInitiation(data.getInitiation())); } }
package plugins.fmp.fmpTools; import java.awt.Point; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.List; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.usermodel.DataConsolidateFunction; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFPivotTable; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import plugins.fmp.fmpSequence.Experiment; import plugins.fmp.fmpSequence.SequencePlus; import plugins.fmp.fmpSequence.SequenceVirtual; public class XLSExport { protected XLSExportOptions options = null; protected Experiment expAll = null; int nintervals = 0; List <XLSNameAndPosition> listOfStacks; public long getnearest(long value, int step) { long diff0 = (value /step)*step; long diff1 = diff0 + step; if ((value - diff0 ) < (diff1 - value)) value = diff0; else value = diff1; return value; } private void addDescriptorTitlestoExperimentDescriptors(XSSFSheet sheet, Point pt, boolean transpose) { XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.DATE.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.BOXID.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.EXPMT.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.COMMENT.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.STIM.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.CONC.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.CAM.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.CAP.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.CAGE.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.NFLIES.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.DUM1.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.DUM2.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.DUM3.toString()); pt.y++; XLSUtils.setValue(sheet, pt, transpose, EnumXLSExperimentDescriptors.DUM4.toString()); pt.y++; } protected Point addExperimentDescriptorsToHeader(Experiment exp, XSSFSheet sheet, Point pt, boolean transpose) { int col0 = pt.x; int row = pt.y; if (col0 == 0) addDescriptorTitlestoExperimentDescriptors(sheet, pt, transpose); pt.x++; pt.x++; pt.x++; int colseries = pt.x; Path path = Paths.get(exp.vSequence.getFileName()); String boxID = exp.vSequence.capillaries.boxID; String experiment = exp.vSequence.capillaries.experiment; String comment = exp.vSequence.capillaries.comment; String stimulusL = exp.vSequence.capillaries.stimulusL; String stimulusR = exp.vSequence.capillaries.stimulusR; String concentrationL = exp.vSequence.capillaries.concentrationL; String concentrationR = exp.vSequence.capillaries.concentrationR; SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy"); String date = df.format(exp.fileTimeImageFirst.toMillis()); String cam = getSubName(path, 2).substring(0, 5); String name1 = getSubName(path, 2); String name11 = getSubName(path, 3); String name111 = getSubName(path, 4); String sheetName = sheet.getSheetName(); for (SequencePlus seq: exp.kymographArrayList) { String name = seq.getName(); int col = getColFromKymoSequenceName(name); if (col >= 0) pt.x = colseries + col; pt.y = row; // date XLSUtils.setValue(sheet, pt, transpose, date); pt.y++; XLSUtils.setValue(sheet, pt, transpose, boxID); pt.y++; XLSUtils.setValue(sheet, pt, transpose, experiment); pt.y++; XLSUtils.setValue(sheet, pt, transpose, comment); pt.y++; // stimulus, conc String letter = name.substring(name.length() - 1); if (letter .equals("L")) XLSUtils.setValue(sheet, pt, transpose, stimulusL); else XLSUtils.setValue(sheet, pt, transpose, stimulusR); pt.y++; if (letter .equals("L")) XLSUtils.setValue(sheet, pt, transpose, concentrationL); else XLSUtils.setValue(sheet, pt, transpose, concentrationR); pt.y++; // cam XLSUtils.setValue(sheet, pt, transpose, cam); pt.y++; // cap XLSUtils.setValue(sheet, pt, transpose, letter); pt.y++; // cage int i = getCageFromCapillaryName(name); XLSUtils.setValue(sheet, pt, transpose, i); pt.y++; // nflies int j = 1; if (i < 1 || i > 8) j = 0; XLSUtils.setValue(sheet, pt, transpose, j); pt.y++; // dum1 XLSUtils.setValue(sheet, pt, transpose, name1); pt.y++; // dum2 XLSUtils.setValue(sheet, pt, transpose, name11); pt.y++; // dum3 XLSUtils.setValue(sheet, pt, transpose, name111); pt.y++; // dum4 XLSUtils.setValue(sheet, pt, transpose, sheetName); pt.y++; } pt.x = col0; return pt; } protected int getCageFromCapillaryName(String name) { if (!name .contains("line")) return -1; String num = name.substring(4, 5); int numFromName = Integer.parseInt(num); return numFromName; } protected String getSubName(Path path, int subnameIndex) { String name = "-"; if (path.getNameCount() >= subnameIndex) name = path.getName(path.getNameCount() -subnameIndex).toString(); return name; } protected String getShortenedName(SequenceVirtual seq, int t) { String cs = seq.getFileName(t); return cs.substring(cs.lastIndexOf(File.separator) + 1) ; } protected void xlsCreatePivotTable(XSSFWorkbook workBook, String workBookName, String fromWorkbook, DataConsolidateFunction function) { XSSFSheet pivotSheet = workBook.createSheet(workBookName); XSSFSheet sourceSheet = workBook.getSheet(fromWorkbook); int lastRowNum = sourceSheet.getLastRowNum(); int lastColumnNum = sourceSheet.getRow(0).getLastCellNum(); CellAddress lastcell = new CellAddress (lastRowNum, lastColumnNum-1); String address = "A1:"+lastcell.toString(); AreaReference source = new AreaReference(address, SpreadsheetVersion.EXCEL2007); CellReference position = new CellReference(0, 0); XSSFPivotTable pivotTable = pivotSheet.createPivotTable(source, position, sourceSheet); boolean flag = false; // ugly trick: switch mode when flag = true, ie when column "roi" has been found for (int i = 0; i< lastColumnNum; i++) { XSSFCell cell = XLSUtils.getCell(sourceSheet, 0, i); String text = cell.getStringCellValue(); if( !flag) { flag = text.contains("roi"); // ugly trick here if (text.contains(EnumXLSExperimentDescriptors.CAP.toString())) pivotTable.addRowLabel(i); if (text.contains(EnumXLSExperimentDescriptors.NFLIES.toString())) pivotTable.addRowLabel(i); continue; } pivotTable.addColumnLabel(function, i, text); } } protected Point writeGenericHeader (Experiment exp, XSSFSheet sheet, EnumXLSExportItems option, Point pt, boolean transpose, String charSeries) { pt = addExperimentDescriptorsToHeader(exp, sheet, pt, transpose); XLSUtils.setValue(sheet, pt, transpose, "rois"+charSeries); pt.x++; XLSUtils.setValue(sheet, pt, transpose, "timeMin"+charSeries); pt.x++; XLSUtils.setValue(sheet, pt, transpose, "filename" ); pt.x++; return pt; } protected void xlsCreatePivotTables(XSSFWorkbook workBook, String fromWorkbook) { xlsCreatePivotTable(workBook, "pivot_avg", fromWorkbook, DataConsolidateFunction.AVERAGE); xlsCreatePivotTable(workBook, "pivot_std", fromWorkbook, DataConsolidateFunction.STD_DEV); xlsCreatePivotTable(workBook, "pivot_n", fromWorkbook, DataConsolidateFunction.COUNT); } protected String getBoxIdentificator (Experiment exp) { Path path = Paths.get(exp.vSequence.getFileName()); String name = getSubName(path, 2); return name; } // TODO change protected Point getStackColumnPosition (Experiment exp, Point pt) { Point localPt = pt; String name = getBoxIdentificator (exp); boolean found = false; for (XLSNameAndPosition desc: listOfStacks) { if (name .equals(desc.name)) { found = true; localPt = new Point(desc.column, desc.row); if (desc.fileTimeImageLastMinutes < exp.fileTimeImageLastMinutes) { desc.fileTimeImageLastMinutes = exp.fileTimeImageLastMinutes; desc.fileTimeImageLast = exp.fileTimeImageLast; } if (desc.fileTimeImageFirstMinutes > exp.fileTimeImageFirstMinutes) { desc.fileTimeImageFirstMinutes = exp.fileTimeImageFirstMinutes; desc.fileTimeImageFirst = exp.fileTimeImageFirst; } long filespan = desc.fileTimeImageLastMinutes - desc.fileTimeImageFirstMinutes; if (filespan > desc.fileTimeSpan) desc.fileTimeSpan = filespan; break; } } if (!found) { XLSNameAndPosition desc = new XLSNameAndPosition(name, pt); desc.fileTimeImageFirstMinutes = exp.fileTimeImageFirstMinutes; desc.fileTimeImageFirst = exp.fileTimeImageFirst; desc.fileTimeSpan = desc.fileTimeImageLastMinutes - desc.fileTimeImageFirstMinutes; listOfStacks.add(desc); } return localPt; } // ? protected XLSNameAndPosition getStackGlobalSeriesDescriptor (Experiment exp) { String name = getBoxIdentificator (exp); for (XLSNameAndPosition desc: listOfStacks) { if (name .equals(desc.name)) { return desc; } } return null; } protected int getColFromKymoSequenceName(String name) { if (!name .contains("line")) return -1; String num = name.substring(4, 5); int numFromName = Integer.parseInt(num); String side = name.substring(5, 6); if (side != null) { if (side .equals("R")) { numFromName = numFromName* 2; numFromName += 1; } else if (side .equals("L")) numFromName = numFromName* 2; } return numFromName; } }
package com.lenovohit.hwe.treat.web.his; 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.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.hwe.org.web.rest.OrgBaseRestController; import com.lenovohit.hwe.treat.model.ChargeDetail; import com.lenovohit.hwe.treat.service.HisChargeDetailService; import com.lenovohit.hwe.treat.transfer.RestListResponse; @RestController @RequestMapping("/hwe/treat/his/charge/") public class ChargeHisController extends OrgBaseRestController { @Autowired private HisChargeDetailService hisChargeDetailService; /** * 缴费记录 * @param data * @return */ @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forList(@RequestParam(value = "data", defaultValue = "") String data) { ChargeDetail chager = JSONUtils.parseObject(data, ChargeDetail.class); RestListResponse<ChargeDetail> response = this.hisChargeDetailService.findList(chager); if(response.isSuccess()) return ResultUtils.renderSuccessResult(response.getList()); else return ResultUtils.renderFailureResult(response.getMsg()); } }
package com.myvodafone.android.model.service.fixed; /** * Created by kakaso on 4/30/2015. */ public class HOLBillingPayment { private String paymentProfileType; private String paymentProfileId; private String expirationYear; private String expirationMonth; private String owner; private String bank; private String cardType; private String hasBonus; private String cardNumber; public String getPaymentProfileType() { return paymentProfileType; } public void setPaymentProfileType(String paymentProfileType) { this.paymentProfileType = paymentProfileType; } public String getPaymentProfileId() { return paymentProfileId; } public void setPaymentProfileId(String paymentProfileId) { this.paymentProfileId = paymentProfileId; } public String getExpirationYear() { return expirationYear; } public void setExpirationYear(String expirationYear) { this.expirationYear = expirationYear; } public String getExpirationMonth() { return expirationMonth; } public void setExpirationMonth(String expirationMonth) { this.expirationMonth = expirationMonth; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getBank() { return bank; } public void setBank(String bank) { this.bank = bank; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public String getHasBonus() { return hasBonus; } public void setHasBonus(String hasBonus) { this.hasBonus = hasBonus; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } }
package com.bnrc.ui.rjz.other; /** * Created by yuyidong on 15/8/14. */ public class Bean { public String name; public Bean(String name) { this.name = name; } @Override public String toString() { return "Bean{" + "name='" + name + '\'' + '}'; } }
import org.junit.jupiter.api.Test; import java.util.*; import java.util.stream.Collectors; @SuppressWarnings("SpellCheckingInspection") public class MainTest { // food -> <ingredients> // Map<Set<String>, Set<String>> foods = new HashMap<>(); // allergen --> <foods> // Map<String, HashMap<String, Set<String>>> allergens = new HashMap<>(); @Test void tst() { // Map<Set<String>, Set<String>> foods = initFoodsExample(); Map<Set<String>, Set<String>> foods = initFoodsInp(); Map<String, String> confirmedAllergenIngredients = getConfirmedAllergenIngredients(foods); System.out.println(foods); System.out.println(confirmedAllergenIngredients); foods.keySet().forEach(k -> k.removeAll(confirmedAllergenIngredients.values())); System.out.println(foods.keySet()); long sum = foods.keySet().stream().mapToLong(Set::size).sum(); System.out.println(sum); String sortedValues = confirmedAllergenIngredients.keySet().stream().sorted().map(confirmedAllergenIngredients::get).collect(Collectors.joining(",")); System.out.println(sortedValues); } private Map<String, String> getConfirmedAllergenIngredients(Map<Set<String>, Set<String>> foods) { Map<String, Set<String>> allergenIngredients = new HashMap<>(); for (Map.Entry<Set<String>, Set<String>> foodsEntry : foods.entrySet()) { foodsEntry.getValue().forEach(allergen -> addOrMerge(allergenIngredients, allergen, foodsEntry.getKey())); } Map<String, String> confirmedAllergenIngredients = new HashMap<>(); while (true) { Set<String> confirmedAllergens = allergenIngredients.entrySet().stream() .filter(e -> 1 == e.getValue().size()) .map(Map.Entry::getKey) .collect(Collectors.toSet()); if (confirmedAllergens.isEmpty()) { break; } for (String confirmedAllergen : confirmedAllergens) { String confirmedFood = allergenIngredients.get(confirmedAllergen).iterator().next(); confirmedAllergenIngredients.put(confirmedAllergen, confirmedFood); allergenIngredients.remove(confirmedAllergen); for ( Set<String> ingredients : allergenIngredients.values()) { ingredients.remove(confirmedFood); } } } return confirmedAllergenIngredients; } private void addOrMerge(Map<String, Set<String>> map, String key, Set<String> value) { if (!map.containsKey(key)) { map.put(key, new HashSet<>(value)); } else { // map.get(key).addAll(value); map.get(key).retainAll(value); } } private Map<Set<String>, Set<String>> initFoodsExample() { // mxmxvkd kfcds sqjhc nhms (contains dairy, fish) // trh fvjkl sbzzf mxmxvkd (contains dairy) // sqjhc fvjkl (contains soy) // sqjhc mxmxvkd sbzzf (contains fish) Map<Set<String>, Set<String>> foods = new HashMap<>(); foods.put(new HashSet<>(Set.of("mxmxvkd", "kfcds", "sqjhc", "nhms")), Set.of("dairy", "fish")); foods.put(new HashSet<>(Set.of("trh", "fvjkl", "sbzzf", "mxmxvkd")), Set.of("dairy")); foods.put(new HashSet<>(Set.of("sqjhc", "fvjkl")), Set.of("soy")); foods.put(new HashSet<>(Set.of("sqjhc", "mxmxvkd", "sbzzf")), Set.of("fish")); return foods; } @Test void name() { System.out.println(initFoodsInp()); } // cqvc vmkt sbvbzcg (contains fish, soy, nuts) private Map<Set<String>, Set<String>> initFoodsInp() { Map<Set<String>, Set<String>> foods = new HashMap<>(); for (String line : Inp.INP.split("\n")) { String[] tokens = line.split("\\("); Set<String> ingredients = new HashSet<>(Arrays.asList(tokens[0].trim().split(" "))); String[] t1 = tokens[1].replace("contains", "").replace(" ", "").replace(")", "").split(","); Set<String> allergens = new HashSet<>(Arrays.asList(t1)); foods.put(ingredients, allergens); } return foods; } }
package verwalteStudent; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import source.studenten.VerwalteStudent; import exceptions.FalscherEintragException; public class LiefereStrassenAnteilUndRest { static VerwalteStudent gueltigerStudent = new VerwalteStudent(); static String kompletteAdresse; @Before public void initialisiereAdresse() { kompletteAdresse = "Markelstr. 34 70193 Stuttgart"; } @Test public void testStrassenAnteilKorrekt() throws FalscherEintragException { assertEquals("Markelstr.", gueltigerStudent .liefereStrassenAnteilUndRest(kompletteAdresse).get(0)); } @Test public void testRestOhneStrassenAnteilKorrekt() throws FalscherEintragException { assertEquals("34 70193 Stuttgart", gueltigerStudent .liefereStrassenAnteilUndRest(kompletteAdresse).get(1)); } }
package org.wuxinshui.boosters.test.http; import org.wuxinshui.boosters.http.HttpUtils; /** * @Description: * @Author:FujiRen * @Date:2017/4/27 11:44 */ public class HttpUtilsTest { public static void main(String[] args) { String jsonData="{\"startDate\":\"2017-04-25\",\"endDate\":\"2017-04-25\",\"refferalTypes\":[],\"refferalIds\":[],\"funnelTypes\":[]}"; String url="http://172.16.36.73:9090/dashboard/selectRefferalConvertRatio"; System.out.println(HttpUtils.executeCall(url,0,jsonData)); System.out.println(HttpUtils.responseJSON(url,0,jsonData)); } }
/* * MIT License * * Copyright (c) 2017-2019 nuls.io * * 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 io.nuls.common; import io.nuls.base.basic.AddressTool; import io.nuls.base.basic.NulsByteBuffer; import io.nuls.base.basic.NulsOutputStreamBuffer; import io.nuls.base.data.BaseNulsData; import io.nuls.consensus.model.bo.config.AssetsStakingLimitCfg; import io.nuls.core.crypto.HexUtil; import io.nuls.core.exception.NulsException; import io.nuls.core.model.StringUtils; import io.nuls.core.parse.SerializeUtils; import java.io.IOException; import java.math.BigInteger; import java.util.*; /** * Transaction module chain setting * @author: Charlie * @date: 2019/03/14 */ public class ConfigBean extends BaseNulsData { /** chain id*/ private int chainId; /** assets id*/ private int assetId; /*-------------------------[Block]-----------------------------*/ /** * 区块大小阈值 */ private long blockMaxSize; /** * 网络重置阈值 */ private long resetTime; /** * 分叉链比主链高几个区块就进行链切换 */ private byte chainSwtichThreshold; /** * 分叉链、孤儿链区块最大缓存数量 */ private int cacheSize; /** * 接收新区块的范围 */ private int heightRange; /** * 每次回滚区块最大值 */ private int maxRollback; /** * 一致节点比例 */ private byte consistencyNodePercent; /** * 系统运行最小节点数 */ private byte minNodeAmount; /** * 每次从一个节点下载多少区块 */ private byte downloadNumber; /** * 区块头中扩展字段的最大长度 */ private int extendMaxSize; /** * 为阻止恶意节点提前出块,设置此参数 * 区块时间戳大于当前时间多少就丢弃该区块 */ private int validBlockInterval; /** * 系统正常运行时最多缓存多少个从别的节点接收到的小区块 */ private byte smallBlockCache; /** * 孤儿链最大年龄 */ private byte orphanChainMaxAge; /** * 日志级别 */ private String logLevel; /** * 下载单个区块的超时时间 */ private int singleDownloadTimeout; /** * 等待网络稳定的时间间隔 */ private int waitNetworkInterval; /** * 创世区块配置文件路径 */ private String genesisBlockPath; /** * 区块同步过程中缓存的区块字节数上限 */ private long cachedBlockSizeLimit; /*-------------------------[Protocol]-----------------------------*/ /** * 统计区间 */ private short interval; /** * 每个统计区间内的最小生效比例 */ private byte effectiveRatioMinimum; /** * 协议生效要满足的连续区间数最小值 */ private short continuousIntervalCountMinimum; /*-------------------------[CrossChain]-----------------------------*/ /** * 最小链接数 * Minimum number of links * */ private int minNodes; /** * 最大链接数 * */ private int maxOutAmount; /** * 最大被链接数 * */ private int maxInAmount; /** * 跨链交易被打包多少块之后广播给其他链 * */ private int sendHeight; /** * 拜占庭比例 * */ private int byzantineRatio; /** * 最小签名数 * */ private int minSignature; /** * 主网验证人信息 * */ private String verifiers; /** * 主网拜占庭比例 * */ private int mainByzantineRatio; /** * 主网最大签名验证数 * */ private int maxSignatureCount; /** * 主网验证人列表 * */ private Set<String> verifierSet = new HashSet<>(); /*-------------------------[Consensus]-----------------------------*/ /** * 打包间隔时间 * Packing interval time */ private long packingInterval; /** * 获得红牌保证金锁定时间 * Lock-in time to get a red card margin */ private long redPublishLockTime; /** * 注销节点保证金锁定时间 * Log-off node margin locking time */ private long stopAgentLockTime; /** * 减少保证金锁定时间 * Reduce margin lock-in time */ private long reducedDepositLockTime; /** * 创建节点的保证金最小值 * Minimum margin for creating nodes */ private BigInteger depositMin; /** * 节点的保证金最大值 * Maximum margin for creating nodes */ private BigInteger depositMax; /** * 节点参与共识节点竞选最小委托金 * Minimum Trust Fund for node participating in consensus node campaign */ private BigInteger packDepositMin; /** * 委托最小金额 * Minimum amount entrusted */ private BigInteger entrustMin; /** * 种子节点 * Seed node */ private String seedNodes; /** * 种子节点对应公钥 */ private String pubKeyList; /** * 出块节点密码 */ private String password; /** * 打包区块最大值 */ private long blockConsensusMaxSize; /** * 创建节点资产ID * agent assets id */ private int agentAssetId; /** * 创建节点资产链ID * Create node asset chain ID */ private int agentChainId; /** * 共识奖励资产ID * Award asset chain ID */ private int awardAssetId; /** * 交易手续费单价 * Transaction fee unit price */ private long feeUnit; /** * 总通缩量 * Total inflation amount */ private BigInteger totalInflationAmount; /** * 初始通胀金额 * Initial Inflation Amount */ private BigInteger inflationAmount; /** * 通胀开始时间 */ private long initHeight; /** * 通缩比例 */ private double deflationRatio; /** * 通缩间隔时间 */ private long deflationHeightInterval; /** * 追加保证金最小金额 * Minimum amount of additional margin */ private BigInteger appendAgentDepositMin; /** * 退出保证金最小金额 * Minimum amount of withdrawal deposit */ private BigInteger reduceAgentDepositMin; private int byzantineRate; /** * 共识节点最大数量 */ private int agentCountMax; /** * 本链主资产的权重基数 */ private double localAssertBase; /** * 节点保证金基数 */ private double agentDepositBase; /** * 虚拟银行保证金基数 */ private double superAgentDepositBase; /** * 后备节点保证金基数 */ private double reservegentDepositBase; private int maxCoinToOfCoinbase; private long minRewardHeight; private long depositAwardChangeHeight; private long depositVerifyHeight; private Long v1_3_0Height; private Long v1_6_0Height; private Long v1_7_0Height; private BigInteger minStakingAmount; private BigInteger minAppendAndExitAmount; private Integer exitStakingLockHours; private List<AssetsStakingLimitCfg> limitCfgList; public List<AssetsStakingLimitCfg> getLimitCfgList() { return limitCfgList; } public Map<String, Integer> weightMap = new HashMap<>(); public void putWeight(int chainId, int assetId, int weight) { weightMap.put(chainId + "-" + assetId, weight); } public int getWeight(int chainId, int assetId) { Integer weight = weightMap.get(chainId + "-" + assetId); if (null == weight) { return 1; } return weight.intValue(); } public void setLimitCfgList(List<AssetsStakingLimitCfg> limitCfgList) { this.limitCfgList = limitCfgList; } public long getDepositAwardChangeHeight() { return depositAwardChangeHeight; } public void setDepositAwardChangeHeight(long depositAwardChangeHeight) { this.depositAwardChangeHeight = depositAwardChangeHeight; } public long getDepositVerifyHeight() { return depositVerifyHeight; } public void setDepositVerifyHeight(long depositVerifyHeight) { this.depositVerifyHeight = depositVerifyHeight; } public int getMaxCoinToOfCoinbase() { return maxCoinToOfCoinbase; } public void setMaxCoinToOfCoinbase(int maxCoinToOfCoinbase) { this.maxCoinToOfCoinbase = maxCoinToOfCoinbase; } public long getMinRewardHeight() { return minRewardHeight; } public void setMinRewardHeight(long minRewardHeight) { this.minRewardHeight = minRewardHeight; } public long getPackingInterval() { return packingInterval; } public void setPackingInterval(long packingInterval) { this.packingInterval = packingInterval; } public long getRedPublishLockTime() { return redPublishLockTime; } public void setRedPublishLockTime(long redPublishLockTime) { this.redPublishLockTime = redPublishLockTime; } public long getStopAgentLockTime() { return stopAgentLockTime; } public void setStopAgentLockTime(long stopAgentLockTime) { this.stopAgentLockTime = stopAgentLockTime; } public BigInteger getDepositMin() { return depositMin; } public void setDepositMin(BigInteger depositMin) { this.depositMin = depositMin; } public BigInteger getDepositMax() { return depositMax; } public void setDepositMax(BigInteger depositMax) { this.depositMax = depositMax; } public String getSeedNodes() { //不再配置种子节点地址,而是从公钥计算得到 if (StringUtils.isBlank(seedNodes)) { String[] pubkeys = this.pubKeyList.split(","); StringBuilder ss = new StringBuilder(""); for (String pub : pubkeys) { ss.append(",").append(AddressTool.getAddressString(HexUtil.decode(pub), this.chainId)); } this.seedNodes = ss.toString().substring(1); } return seedNodes; } public String getPubKeyList() { return pubKeyList; } public void setPubKeyList(String pubKeyList) { this.pubKeyList = pubKeyList; } public BigInteger getInflationAmount() { return inflationAmount; } public void setInflationAmount(BigInteger inflationAmount) { this.inflationAmount = inflationAmount; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public long getBlockConsensusMaxSize() { return blockConsensusMaxSize; } public void setBlockConsensusMaxSize(long blockConsensusMaxSize) { this.blockConsensusMaxSize = blockConsensusMaxSize; } public int getAgentAssetId() { return agentAssetId; } public void setAgentAssetId(int agentAssetId) { this.agentAssetId = agentAssetId; } public int getAgentChainId() { return agentChainId; } public void setAgentChainId(int agentChainId) { this.agentChainId = agentChainId; } public int getAwardAssetId() { return awardAssetId; } public void setAwardAssetId(int awardAssetId) { this.awardAssetId = awardAssetId; } public long getFeeUnit() { return feeUnit; } public void setFeeUnit(long feeUnit) { this.feeUnit = feeUnit; } public long getInitHeight() { return initHeight; } public void setInitHeight(long initHeight) { this.initHeight = initHeight; } public long getDeflationHeightInterval() { return deflationHeightInterval; } public void setDeflationHeightInterval(long deflationHeightInterval) { this.deflationHeightInterval = deflationHeightInterval; } public double getAgentDepositBase() { return agentDepositBase; } public void setAgentDepositBase(double agentDepositBase) { this.agentDepositBase = agentDepositBase; } public double getSuperAgentDepositBase() { return superAgentDepositBase; } public void setSuperAgentDepositBase(double superAgentDepositBase) { this.superAgentDepositBase = superAgentDepositBase; } public double getDeflationRatio() { return deflationRatio; } public void setDeflationRatio(double deflationRatio) { this.deflationRatio = deflationRatio; } public BigInteger getTotalInflationAmount() { return totalInflationAmount; } public void setTotalInflationAmount(BigInteger totalInflationAmount) { this.totalInflationAmount = totalInflationAmount; } public BigInteger getPackDepositMin() { return packDepositMin; } public void setPackDepositMin(BigInteger packDepositMin) { this.packDepositMin = packDepositMin; } public long getReducedDepositLockTime() { return reducedDepositLockTime; } public void setReducedDepositLockTime(long reducedDepositLockTime) { this.reducedDepositLockTime = reducedDepositLockTime; } public BigInteger getEntrustMin() { return entrustMin; } public void setEntrustMin(BigInteger entrustMin) { this.entrustMin = entrustMin; } public BigInteger getAppendAgentDepositMin() { return appendAgentDepositMin; } public void setAppendAgentDepositMin(BigInteger appendAgentDepositMin) { this.appendAgentDepositMin = appendAgentDepositMin; } public BigInteger getReduceAgentDepositMin() { return reduceAgentDepositMin; } public void setReduceAgentDepositMin(BigInteger reduceAgentDepositMin) { this.reduceAgentDepositMin = reduceAgentDepositMin; } public int getByzantineRate() { return byzantineRate; } public void setByzantineRate(int byzantineRate) { this.byzantineRate = byzantineRate; } public int getAgentCountMax() { return agentCountMax; } public void setAgentCountMax(int agentCountMax) { this.agentCountMax = agentCountMax; } public double getLocalAssertBase() { return localAssertBase; } public void setLocalAssertBase(double localAssertBase) { this.localAssertBase = localAssertBase; } public long getPackingIntervalMills() { return 1000 * this.getPackingInterval(); } public double getReservegentDepositBase() { return reservegentDepositBase; } public void setReservegentDepositBase(double reservegentDepositBase) { this.reservegentDepositBase = reservegentDepositBase; } public void setV130Height(Long v130Height) { this.v1_3_0Height = v130Height; } public Long getV130Height() { return v1_3_0Height; } public Long getV1_7_0Height() { return v1_7_0Height; } public void setV1_7_0Height(Long v1_7_0Height) { this.v1_7_0Height = v1_7_0Height; } public Long getV1_6_0Height() { return v1_6_0Height; } public void setV1_6_0Height(Long v1_6_0Height) { this.v1_6_0Height = v1_6_0Height; } public void setMinStakingAmount(BigInteger minStakingAmount) { this.minStakingAmount = minStakingAmount; } public BigInteger getMinStakingAmount() { return minStakingAmount; } public void setMinAppendAndExitAmount(BigInteger minAppendAndExitAmount) { this.minAppendAndExitAmount = minAppendAndExitAmount; } public BigInteger getMinAppendAndExitAmount() { return minAppendAndExitAmount; } public void setExitStakingLockHours(Integer exitStakingLockHours) { this.exitStakingLockHours = exitStakingLockHours; } public Integer getExitStakingLockHours() { return exitStakingLockHours; } @Override protected void serializeToStream(NulsOutputStreamBuffer stream) throws IOException { // block stream.writeUint16(chainId); stream.writeUint16(assetId); stream.writeUint32(blockMaxSize); stream.writeUint32(resetTime); stream.writeByte(chainSwtichThreshold); stream.writeUint16(cacheSize); stream.writeUint16(heightRange); stream.writeUint16(maxRollback); stream.writeByte(consistencyNodePercent); stream.writeByte(minNodeAmount); stream.writeByte(downloadNumber); stream.writeUint16(extendMaxSize); stream.writeUint16(validBlockInterval); stream.writeByte(smallBlockCache); stream.writeByte(orphanChainMaxAge); stream.writeString(logLevel); stream.writeUint16(singleDownloadTimeout); stream.writeUint16(waitNetworkInterval); stream.writeString(genesisBlockPath); stream.writeUint32(cachedBlockSizeLimit); // protocol stream.writeShort(interval); stream.writeByte(effectiveRatioMinimum); stream.writeShort(continuousIntervalCountMinimum); // cross stream.writeUint16(minNodes); stream.writeUint16(maxOutAmount); stream.writeUint16(maxInAmount); stream.writeUint16(sendHeight); stream.writeUint16(byzantineRatio); stream.writeUint16(minSignature); stream.writeString(verifiers); stream.writeUint16(mainByzantineRatio); stream.writeUint16(maxSignatureCount); int registerCount = verifierSet == null ? 0 : verifierSet.size(); stream.writeVarInt(registerCount); if(verifierSet != null){ for (String registerAgent:verifierSet) { stream.writeString(registerAgent); } } // consensus stream.writeUint32(packingInterval); stream.writeUint32(redPublishLockTime); stream.writeUint32(stopAgentLockTime); stream.writeUint32(reducedDepositLockTime); stream.writeBigInteger(depositMin); stream.writeBigInteger(depositMax); stream.writeBigInteger(packDepositMin); stream.writeBigInteger(entrustMin); stream.writeString(seedNodes); stream.writeString(pubKeyList); stream.writeString(password); stream.writeUint48(blockConsensusMaxSize); stream.writeUint16(agentAssetId); stream.writeUint16(agentChainId); stream.writeUint16(awardAssetId); stream.writeUint32(feeUnit); stream.writeBigInteger(totalInflationAmount); stream.writeBigInteger(inflationAmount); stream.writeUint32(initHeight); stream.writeDouble(deflationRatio); stream.writeUint32(deflationHeightInterval); stream.writeBigInteger(appendAgentDepositMin); stream.writeBigInteger(reduceAgentDepositMin); stream.writeUint16(byzantineRate); stream.writeUint16(agentCountMax); stream.writeDouble(0); stream.writeDouble(localAssertBase); stream.writeDouble(agentDepositBase); stream.writeDouble(superAgentDepositBase); stream.writeDouble(reservegentDepositBase); stream.writeUint32(this.maxCoinToOfCoinbase); stream.writeUint32(this.minRewardHeight); } @Override public void parse(NulsByteBuffer byteBuffer) throws NulsException { //block this.chainId = byteBuffer.readUint16(); this.assetId = byteBuffer.readUint16(); this.blockMaxSize = byteBuffer.readUint32(); this.resetTime = byteBuffer.readUint32(); this.chainSwtichThreshold = byteBuffer.readByte(); this.cacheSize = byteBuffer.readUint16(); this.heightRange = byteBuffer.readUint16(); this.maxRollback = byteBuffer.readUint16(); this.consistencyNodePercent = byteBuffer.readByte(); this.minNodeAmount = byteBuffer.readByte(); this.downloadNumber = byteBuffer.readByte(); this.extendMaxSize = byteBuffer.readUint16(); this.validBlockInterval = byteBuffer.readUint16(); this.smallBlockCache = byteBuffer.readByte(); this.orphanChainMaxAge = byteBuffer.readByte(); this.logLevel = byteBuffer.readString(); this.singleDownloadTimeout = byteBuffer.readUint16(); this.waitNetworkInterval = byteBuffer.readUint16(); this.genesisBlockPath = byteBuffer.readString(); this.cachedBlockSizeLimit = byteBuffer.readUint32(); //protocol this.interval = byteBuffer.readShort(); this.effectiveRatioMinimum = byteBuffer.readByte(); this.continuousIntervalCountMinimum = byteBuffer.readShort(); //cross this.minNodes = byteBuffer.readUint16(); this.maxOutAmount = byteBuffer.readUint16(); this.maxInAmount = byteBuffer.readUint16(); this.sendHeight = byteBuffer.readUint16(); this.byzantineRatio = byteBuffer.readUint16(); this.minNodes = byteBuffer.readUint16(); this.verifiers = byteBuffer.readString(); this.mainByzantineRatio = byteBuffer.readUint16(); this.maxSignatureCount = byteBuffer.readUint16(); int registerCount = (int) byteBuffer.readVarInt(); if(registerCount > 0){ Set<String> verifierSet = new HashSet<>(); for (int i = 0; i < registerCount; i++) { verifierSet.add(byteBuffer.readString()); } this.verifierSet = verifierSet; } this.packingInterval = byteBuffer.readUint32(); this.redPublishLockTime = byteBuffer.readUint32(); this.stopAgentLockTime = byteBuffer.readUint32(); this.reducedDepositLockTime = byteBuffer.readUint32(); this.depositMin = byteBuffer.readBigInteger(); this.depositMax = byteBuffer.readBigInteger(); this.packDepositMin = byteBuffer.readBigInteger(); this.entrustMin = byteBuffer.readBigInteger(); this.seedNodes = byteBuffer.readString(); this.pubKeyList = byteBuffer.readString(); this.password = byteBuffer.readString(); this.blockConsensusMaxSize = byteBuffer.readUint48(); this.agentAssetId = byteBuffer.readUint16(); this.agentChainId = byteBuffer.readUint16(); this.awardAssetId = byteBuffer.readUint16(); this.feeUnit = byteBuffer.readUint32(); this.totalInflationAmount = byteBuffer.readBigInteger(); this.inflationAmount = byteBuffer.readBigInteger(); this.initHeight = byteBuffer.readUint32(); this.deflationRatio = byteBuffer.readDouble(); this.deflationHeightInterval = byteBuffer.readUint32(); this.appendAgentDepositMin = byteBuffer.readBigInteger(); this.reduceAgentDepositMin = byteBuffer.readBigInteger(); this.byzantineRate = byteBuffer.readUint16(); this.agentCountMax = byteBuffer.readUint16(); byteBuffer.readDouble(); this.localAssertBase = byteBuffer.readDouble(); this.agentDepositBase = byteBuffer.readDouble(); this.superAgentDepositBase = byteBuffer.readDouble(); this.reservegentDepositBase = byteBuffer.readDouble(); this.maxCoinToOfCoinbase = (int) byteBuffer.readUint32(); this.minRewardHeight = byteBuffer.readUint32(); } @Override public int size() { // block int size = 36; size += SerializeUtils.sizeOfString(logLevel); size += SerializeUtils.sizeOfString(genesisBlockPath); // protocol size += 5; // cross size += SerializeUtils.sizeOfUint16() * 8; size += SerializeUtils.sizeOfString(verifiers); size += SerializeUtils.sizeOfVarInt(verifierSet == null ? 0 : verifierSet.size()); if(verifierSet != null){ for (String verifier:verifierSet) { size += SerializeUtils.sizeOfString(verifier); } } // consensus size += SerializeUtils.sizeOfUint48(); size += SerializeUtils.sizeOfUint32() * 6; size += SerializeUtils.sizeOfDouble(deflationRatio); size += SerializeUtils.sizeOfBigInteger() * 8; size += SerializeUtils.sizeOfString(seedNodes); size += SerializeUtils.sizeOfString(pubKeyList); size += SerializeUtils.sizeOfUint16() * 5; size += SerializeUtils.sizeOfString(password); size += SerializeUtils.sizeOfUint32(); size += SerializeUtils.sizeOfDouble(localAssertBase); size += SerializeUtils.sizeOfDouble(0.0); size += SerializeUtils.sizeOfDouble(agentDepositBase); size += SerializeUtils.sizeOfDouble(superAgentDepositBase); size += SerializeUtils.sizeOfDouble(reservegentDepositBase); size += SerializeUtils.sizeOfUint32(); size += SerializeUtils.sizeOfUint32(); return size; } public ConfigBean() { } public ConfigBean(int chainId, int assetId) { this.chainId = chainId; this.assetId = assetId; } public int getChainId() { return chainId; } public void setChainId(int chainId) { this.chainId = chainId; } public int getAssetId() { return assetId; } public void setAssetId(int assetId) { this.assetId = assetId; } public long getBlockMaxSize() { return blockMaxSize; } public void setBlockMaxSize(long blockMaxSize) { this.blockMaxSize = blockMaxSize; } public long getResetTime() { return resetTime; } public void setResetTime(long resetTime) { this.resetTime = resetTime; } public byte getChainSwtichThreshold() { return chainSwtichThreshold; } public void setChainSwtichThreshold(byte chainSwtichThreshold) { this.chainSwtichThreshold = chainSwtichThreshold; } public int getCacheSize() { return cacheSize; } public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } public int getHeightRange() { return heightRange; } public void setHeightRange(int heightRange) { this.heightRange = heightRange; } public int getMaxRollback() { return maxRollback; } public void setMaxRollback(int maxRollback) { this.maxRollback = maxRollback; } public byte getConsistencyNodePercent() { return consistencyNodePercent; } public void setConsistencyNodePercent(byte consistencyNodePercent) { this.consistencyNodePercent = consistencyNodePercent; } public byte getMinNodeAmount() { return minNodeAmount; } public void setMinNodeAmount(byte minNodeAmount) { this.minNodeAmount = minNodeAmount; } public byte getDownloadNumber() { return downloadNumber; } public void setDownloadNumber(byte downloadNumber) { this.downloadNumber = downloadNumber; } public int getExtendMaxSize() { return extendMaxSize; } public void setExtendMaxSize(int extendMaxSize) { this.extendMaxSize = extendMaxSize; } public int getValidBlockInterval() { return validBlockInterval; } public void setValidBlockInterval(int validBlockInterval) { this.validBlockInterval = validBlockInterval; } public byte getSmallBlockCache() { return smallBlockCache; } public void setSmallBlockCache(byte smallBlockCache) { this.smallBlockCache = smallBlockCache; } public byte getOrphanChainMaxAge() { return orphanChainMaxAge; } public void setOrphanChainMaxAge(byte orphanChainMaxAge) { this.orphanChainMaxAge = orphanChainMaxAge; } public String getLogLevel() { return logLevel; } public void setLogLevel(String logLevel) { this.logLevel = logLevel; } public int getSingleDownloadTimeout() { return singleDownloadTimeout; } public void setSingleDownloadTimeout(int singleDownloadTimeout) { this.singleDownloadTimeout = singleDownloadTimeout; } public int getWaitNetworkInterval() { return waitNetworkInterval; } public void setWaitNetworkInterval(int waitNetworkInterval) { this.waitNetworkInterval = waitNetworkInterval; } public String getGenesisBlockPath() { return genesisBlockPath; } public void setGenesisBlockPath(String genesisBlockPath) { this.genesisBlockPath = genesisBlockPath; } public long getCachedBlockSizeLimit() { return cachedBlockSizeLimit; } public void setCachedBlockSizeLimit(long cachedBlockSizeLimit) { this.cachedBlockSizeLimit = cachedBlockSizeLimit; } public short getInterval() { return interval; } public void setInterval(short interval) { this.interval = interval; } public byte getEffectiveRatioMinimum() { return effectiveRatioMinimum; } public void setEffectiveRatioMinimum(byte effectiveRatioMinimum) { this.effectiveRatioMinimum = effectiveRatioMinimum; } public short getContinuousIntervalCountMinimum() { return continuousIntervalCountMinimum; } public void setContinuousIntervalCountMinimum(short continuousIntervalCountMinimum) { this.continuousIntervalCountMinimum = continuousIntervalCountMinimum; } public int getMinNodes() { return minNodes; } public void setMinNodes(int minNodes) { this.minNodes = minNodes; } public int getMaxOutAmount() { return maxOutAmount; } public void setMaxOutAmount(int maxOutAmount) { this.maxOutAmount = maxOutAmount; } public int getMaxInAmount() { return maxInAmount; } public void setMaxInAmount(int maxInAmount) { this.maxInAmount = maxInAmount; } public int getSendHeight() { return sendHeight; } public void setSendHeight(int sendHeight) { this.sendHeight = sendHeight; } public int getByzantineRatio() { return byzantineRatio; } public void setByzantineRatio(int byzantineRatio) { this.byzantineRatio = byzantineRatio; } public int getMinSignature() { return minSignature; } public void setMinSignature(int minSignature) { this.minSignature = minSignature; } public String getVerifiers() { return verifiers; } public void setVerifiers(String verifiers) { this.verifiers = verifiers; } public int getMainByzantineRatio() { return mainByzantineRatio; } public void setMainByzantineRatio(int mainByzantineRatio) { this.mainByzantineRatio = mainByzantineRatio; } public int getMaxSignatureCount() { return maxSignatureCount; } public void setMaxSignatureCount(int maxSignatureCount) { this.maxSignatureCount = maxSignatureCount; } public Set<String> getVerifierSet() { return verifierSet; } public void setVerifierSet(Set<String> verifierSet) { this.verifierSet = verifierSet; } }
package company; public class Issue{ private String description; public Status status; public Issue(String description) { this.description = description; this.status=Status.PENDING; } public Issue(String description, Status status) { this.description = description; this.status= status; } @Override public String toString() { return description; }}
package com.theshoes.jsp.manager.model.service; import static com.theshoes.jsp.common.mybatis.Template.getSqlSession; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.theshoes.jsp.common.paging.SelectCriteria; import com.theshoes.jsp.manager.model.dao.ManagerDAO; import com.theshoes.jsp.manager.model.dto.WinnerDTO; public class DeliveryService { private final ManagerDAO mapper; public DeliveryService() { mapper = new ManagerDAO(); } public int selectdeliveryTotalCount() { SqlSession session = getSqlSession(); int totalCount = mapper.selectDeliveryTotalCount(session); session.close(); return totalCount; } public List<WinnerDTO> selectAllDeliveryList(SelectCriteria selectCriteria) { SqlSession session = getSqlSession(); List<WinnerDTO> winnerList = mapper.selectAllDeliveryList(session, selectCriteria); System.out.println("winnerList : " + winnerList); session.close(); return winnerList; } }
package com.ranpeak.ProjectX.activity.editProfile; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.EditText; import com.ranpeak.ProjectX.R; import com.ranpeak.ProjectX.activity.interfaces.Activity; public class EditProfilePasswordActivity extends AppCompatActivity implements Activity { private TextInputLayout oldPassword; private TextInputLayout newPassword; private EditText confirmPassword; private Button save; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_profile_password); findViewById(); } @Override public void findViewById() { oldPassword = findViewById(R.id.edit_profile_password_old_TextInputLayout); newPassword = findViewById(R.id.edit_profile_password_new_TextInputLayout); confirmPassword = findViewById(R.id.edit_profile_сonfirm_password_edit_text); save = findViewById(R.id.edit_profile_save_button); } @Override public void onListener() { } }
package com.kodilla.patterns2.adapter.bookclasifier; import com.kodilla.patterns2.adapter.MedianAdapter; import com.kodilla.patterns2.adapter.bookclasifier.librarya.Book; import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; public class MedianAdapterTestSuite { @Test void publicationYearMedianTest(){ //Given Book book = new Book("Adam Mickiewicz", "Pan Tadeusz", 1932,"signature"); Book book1 = new Book("John Smith", "Test", 1800, "signature"); Book book2 = new Book("John Smith", "Test1234", 2020, "signature"); Set<Book> books = new HashSet<>(); books.add(book); books.add(book1); books.add(book2); MedianAdapter medianAdapter = new MedianAdapter(); //When double median = medianAdapter.publicationYearMedian(books); //Then assertEquals(median, 1932); } }
// https://leetcode.com/problems/counting-bits/ // #dynamic-programming #bit-manipulation class Solution { /* f(5) = 1 + f(5 - 4) => f(7) = 1 + f(3) => */ public int[] countBits(int num) { int[] result = new int[num + 1]; int extr = 0; for (int i = 1; i <= num; i++) { if ((i & (i - 1)) == 0) { extr = i; result[i] = 1; } else { result[i] = result[i - extr] + 1; } } return result; } /* other way: f[k] = f[k/2] if k & 1: f[k] += 1 */ }
package com.codekarma.controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import com.codekarma.exception.InvalidOperationException; @ControllerAdvice public class ControllerExceptionHandler { //@ResponseStatus( value=HttpStatus.NOT_FOUND, reason="chips::s::s ") // 409 @ExceptionHandler(InvalidOperationException.class) public ModelAndView handleErrorPage(InvalidOperationException exception) { ModelAndView mav = new ModelAndView(); mav.addObject("exception", "Error occurred: " + exception.getFullMessage()); mav.setViewName("error-main"); return mav; } }
package xtrus.ex.cms.server.session; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.esum.framework.common.util.DateUtil; import xtrus.ex.cms.server.CmsSession; public class CmsSessionFactory { private static CmsSessionFactory instance = new CmsSessionFactory(); public static CmsSessionFactory getInstance() { return instance; } private Map<String, CmsSession> sessionMap = new ConcurrentHashMap<String, CmsSession>(); public synchronized void put(CmsSession session) { if(sessionMap.containsKey(session.getSessionId())) { return; } sessionMap.put(session.getSessionId(), session); } public synchronized void remove(String sessionId) { sessionMap.remove(sessionId); } public CmsSession get(String remoteAddress, int remotePort) { synchronized(this) { Iterator<String> i = sessionMap.keySet().iterator(); while(i.hasNext()) { String userId = i.next(); CmsSession session = sessionMap.get(userId); if(session.getRemoteAddress().equals(remoteAddress) && session.getRemotePort()==remotePort) { session.setLastUpdated(DateUtil.getCYMDHMS()); return session; } } } return null; } public synchronized void clear() { sessionMap.clear(); } }
/** * */ package datamodel.rucksack; import java.security.InvalidParameterException; import java.util.Vector; /** * class which represents the rucksack * * @author Jakob Karolus, Kevin Munk * @version 1.0 * */ public class Rucksack { private int capacity; private Vector<RucksackObject> objects= new Vector<RucksackObject>(); /** * constructor * * @param capacity * the max capacity of this rucksack * */ public Rucksack(int capacity) { if (capacity >= 0){ this.capacity = capacity; this.objects.clear(); } else { throw new InvalidParameterException("No legal capacity"); } } /** * @return the capacity of the Rucksack. */ public int getCapacity(){ return this.capacity; } /** * set the capacity of the Rucksack new, if it legal. * @param capacity * the new capacity. */ public void setCapacity(int capacity){ if (capacity >= 0 && capacity >= getWeight()){ this.capacity = capacity; } else { throw new InvalidParameterException("No legal capacity"); } } /** * @return the number of elements in the Rucksack. */ public int getSize(){ return objects.size(); } /** * @return the complete weight of the Rucksack. */ public int getWeight(){ int weight = 0; for (int i = 0; i < objects.size(); i++){ weight += objects.elementAt(i).getWeight(); } return weight; } /** * @return the complete value of all RucksackObjects. */ public int getValue(){ int value = 0; for (int i = 0; i < objects.size(); i++){ value += objects.elementAt(i).getValue(); } return value; } public Vector<RucksackObject> getElements(){ return objects; } /** * @param i * @return object at position i */ public RucksackObject getObject(int i){ if (i < objects.size()){ return objects.elementAt(i); } else { throw new InvalidParameterException("No RucksackObject at this index"); } } /** * Clones a Rucksack and inserts the elements of the old rucksack. */ @Override public Rucksack clone(){ Rucksack r = new Rucksack(this.capacity); for (int i = 0; i < objects.size(); i++){ r.insert(objects.elementAt(i)); } return r; } /** * removes a element at a specific position i * @param i */ public void removeAt(int i){ if (i < objects.size()){ objects.remove(i); } else { throw new InvalidParameterException("No RucksackObject at this index"); } } /** * remove all RucksackObjects */ public void removeAll(){ objects.clear(); } /** * Two rucksacks are equal, if the have equal elements at the same * positions. */ @Override public boolean equals(Object o){ if (this == null || o == null){ throw new InvalidParameterException("One or booth bags are null"); } if(o instanceof Rucksack) { Rucksack r = (Rucksack) o; if (r.getCapacity() != getCapacity() || r.objects.size() != objects.size() || r.getValue() != getValue() || r.getWeight() != getWeight()){ return false; } // capacity, size of objectsvector, value and weight is equal // so check if the objects are the same for (int i = 0; i < r.objects.size(); i++){ if (!(objects.contains(r.getObject(i)))){ return false; } if (!(r.objects.contains(getObject(i)))){ return false; } } return true; } else { return false; } } /** * tries to add this RucksackObject to the rucksack. * * @param o * the RucksackObject to insert * @return true if the object fits into the rucksack; otherwise false */ public boolean insert(RucksackObject o) { if (this != null && o != null){ if (objects.isEmpty() && o.getWeight() <= capacity){ objects.add(o); return true; } else { if (o.getWeight() + getWeight() <= capacity){ objects.add(o); return true; } } } return false; } /** * get the number of objects in the rucksack. */ public int getAmountOfObjects(){ return objects.size(); } }
package suffix; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ChordTable { Map<Set<Integer>,Integer> table; /** * Connects to the chord table text file and reads in each lines. * @throws FileNotFoundException */ public ChordTable() throws FileNotFoundException { table = new HashMap(); File file = new File("chordtable.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); br.lines().forEach(line -> addToTable(line)); } /** * Creates an internal chord table by adding each line to a map where * the set of notes creating a chord is the key and the root is the value. * @param line */ private void addToTable(String line) { String[] cut = line.split("-"); int note = Integer.parseInt(cut[1]); Set<Integer> chord = new HashSet(); for(String number: cut[0].split(",")) { chord.add(Integer.parseInt(number)); } table.put(chord, note); } /** * Looks up the root of the chord. * If the chord is not found in the table, returns 13. * @param chord * @return root note. */ public int getroot(Set<Integer> chord) { if(table.get(chord) == null) return 13; return table.get(chord); } /** * Returns the musical notation of a note. * @param note * @return Notes musical notation. */ public String translate(int note) { String sNote; switch (note) { case 0: sNote = "C"; break; case 1: sNote = "C#"; break; case 2: sNote = "D"; break; case 3: sNote = "D#"; break; case 4: sNote = "E"; break; case 5: sNote = "F"; break; case 6: sNote = "F#"; break; case 7: sNote = "G"; break; case 8: sNote = "G#"; break; case 9: sNote = "A"; break; case 10: sNote = "A#"; break; case 11: sNote = "B"; break; default: sNote = "X"; } return sNote; } }
package com.toni.programming.data; public enum Actions { ATTACK, DEFEND, ESCAPE, FLY, DIG, SWIM, HEAL, SLEEP, WEAKENED, EAT //Prova }
package com.bupsolutions.polaritydetection.features; import com.bupsolutions.polaritydetection.model.LabeledTextSet; import com.bupsolutions.polaritydetection.nlp.NLPProcessor; import opennlp.model.Event; import opennlp.model.ListEventStream; import java.util.stream.Collectors; public class FeatureStream extends ListEventStream { public FeatureStream(LabeledTextSet<?> data) { super(data.stream().map(c -> { String value = Integer.toString(c.getLabel().asInt()); String[] features = NLPProcessor.getInstance().process(c.getText()); return new Event(value, features); }) .collect(Collectors.toList())); } }
package com.davivienda.sara.entitys.seguridad; import java.io.Serializable; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; /** * ServicioAplicacion - 25/05/2008 * Descripción : * Versión : 1.0 * * @author jjvargas * Davivienda 2008 */ @Entity @Table(name = "SERVICIO_APLICACION") @NamedQueries({ @NamedQuery(name = "ServicioAplicacion.todos", query = "SELECT s FROM ServicioAplicacion s ORDER BY s.modulo, s.servicio "), @NamedQuery(name = "ServicioAplicacion.findByServicio", query = "SELECT s FROM ServicioAplicacion s WHERE s.servicio = :servicio"), @NamedQuery(name = "ServicioAplicacion.findByModulo", query = "SELECT s FROM ServicioAplicacion s WHERE s.modulo = :modulo"), @NamedQuery(name = "ServicioAplicacion.findByDescripcion", query = "SELECT s FROM ServicioAplicacion s WHERE s.descripcion = :descripcion")}) public class ServicioAplicacion implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "SERVICIO", nullable = false) private Long servicio; @Column(name = "MODULO", nullable = false) private String modulo; @Column(name = "DESCRIPCION", nullable = false) private String descripcion; @OneToMany(cascade = CascadeType.ALL, mappedBy = "servicioAplicacion", fetch=FetchType.EAGER) private Collection<ConfAccesoAplicacion> confAccesoAplicacionCollection; public ServicioAplicacion() { } public ServicioAplicacion(Long servicio) { this.servicio = servicio; } public ServicioAplicacion(Long servicio, String modulo, String descripcion) { this.servicio = servicio; this.modulo = modulo; this.descripcion = descripcion; } public Long getServicio() { return servicio; } public void setServicio(Long servicio) { this.servicio = servicio; } public String getModulo() { return modulo; } public void setModulo(String modulo) { this.modulo = modulo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Collection<ConfAccesoAplicacion> getConfAccesoAplicacionCollection() { return confAccesoAplicacionCollection; } public void setConfAccesoAplicacionCollection(Collection<ConfAccesoAplicacion> confAccesoAplicacionCollection) { this.confAccesoAplicacionCollection = confAccesoAplicacionCollection; } @Override public int hashCode() { int hash = 0; hash += (servicio != null ? servicio.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ServicioAplicacion)) { return false; } ServicioAplicacion other = (ServicioAplicacion) object; if ((this.servicio == null && other.servicio != null) || (this.servicio != null && !this.servicio.equals(other.servicio))) { return false; } return true; } @Override public String toString() { return "com.davivienda.sara.entitys.seguridad.ServicioAplicacion[servicio=" + servicio + "]"; } }
package com.company.tax.complain.entity; import java.sql.Timestamp; import java.util.Set; /** * 投诉实体,与投诉回复一对多关系 * @author Dongfuming * @date 2016-5-17 下午2:00:56 */ public class Complain { private String compId; private String compCompany; // 投诉人单位 private String compName; // 投诉人姓名 private String compMobile; // 投诉人手机 private Boolean isNm; // 是否匿名 private Timestamp compTime; // 投诉时间 private String compTitle; // 投诉标题 private String toCompName; // 被投诉人姓名 private String toCompDept; // 被投诉人部门 private String compContent; // 投诉内容 private String state; // 状态 private Set<ComplainReply> complainReplySet; // 一个投诉,多个回复 public Complain() { } public Complain(String compTitle) { this.compTitle = compTitle; } public Complain(String compCompany, String compName, String compMobile, Boolean isNm, Timestamp compTime, String compTitle, String toCompName, String toCompDept, String compContent, String state, Set<ComplainReply> complainReplySet) { this.compCompany = compCompany; this.compName = compName; this.compMobile = compMobile; this.isNm = isNm; this.compTime = compTime; this.compTitle = compTitle; this.toCompName = toCompName; this.toCompDept = toCompDept; this.compContent = compContent; this.state = state; this.complainReplySet = complainReplySet; } public String getCompId() { return this.compId; } public void setCompId(String compId) { this.compId = compId; } public String getCompCompany() { return this.compCompany; } public void setCompCompany(String compCompany) { this.compCompany = compCompany; } public String getCompName() { return this.compName; } public void setCompName(String compName) { this.compName = compName; } public String getCompMobile() { return this.compMobile; } public void setCompMobile(String compMobile) { this.compMobile = compMobile; } public Boolean getIsNm() { return this.isNm; } public void setIsNm(Boolean isNm) { this.isNm = isNm; } public Timestamp getCompTime() { return this.compTime; } public void setCompTime(Timestamp compTime) { this.compTime = compTime; } public String getCompTitle() { return this.compTitle; } public void setCompTitle(String compTitle) { this.compTitle = compTitle; } public String getToCompName() { return this.toCompName; } public void setToCompName(String toCompName) { this.toCompName = toCompName; } public String getToCompDept() { return this.toCompDept; } public void setToCompDept(String toCompDept) { this.toCompDept = toCompDept; } public String getCompContent() { return this.compContent; } public void setCompContent(String compContent) { this.compContent = compContent; } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public Set<ComplainReply> getComplainReplySet() { return complainReplySet; } public void setComplainReplySet(Set<ComplainReply> complainReplySet) { this.complainReplySet = complainReplySet; } @Override public String toString() { return "Complain [compId=" + compId + ", compCompany=" + compCompany + ", compName=" + compName + ", compMobile=" + compMobile + ", compTitle=" + compTitle + ", toCompName=" + toCompName + ", toCompDept=" + toCompDept + ", compContent=" + compContent + "]"; } }
package com.example.DemoCountdown; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { public static final String COUNTER_VALUE = "TIMER_INTERVAR"; int intervalInteger = 0; String intervalString = ""; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void doCountdownActivity(View view) { Intent countdownIntent = new Intent("com.example.CountdownActivity"); EditText counterEditText = (EditText) findViewById(R.id.interval_edittext); // System.out.println("Value: " + intervalString); try { intervalInteger = Integer.parseInt(counterEditText.getText().toString()); } catch (NumberFormatException e) { // counterEditText.setHint("Enter an integer!"); counterEditText.setText("0"); counterEditText.setHintTextColor(0); return; } // intervalInteger = 22;//(int) intervalString; // System.out.println("Value: " + intervalInteger); countdownIntent.putExtra(COUNTER_VALUE, intervalInteger); // setResult(Activity.RESULT_OK, countdownIntent); // startActivity(countdownIntent); startActivityForResult(countdownIntent,1); } public void doFinishActivity(View view) { Intent result = new Intent(); result.putExtra(COUNTER_VALUE, intervalInteger); setResult(Activity.RESULT_OK, result); finish(); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if(resultCode == RESULT_OK){ // String result=data.getStringExtra("previous_countdown"); int previous_cnt = data.getIntExtra("previous_countdown",0); TextView textPreviousCount = (TextView) findViewById(R.id.main_count_text); textPreviousCount.setText("Previous count: " + previous_cnt); EditText editText = (EditText) findViewById(R.id.interval_edittext); editText.setText(""); } if (resultCode == RESULT_CANCELED) { //Write your code if there's no result } } }//onActivityResult }
package com.example.demo.config; import java.util.UUID; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.aws.core.env.ResourceIdResolver; import org.springframework.cloud.aws.messaging.core.NotificationMessagingTemplate; import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.util.Topics; import com.amazonaws.services.sqs.AmazonSQSAsync; import com.amazonaws.services.sqs.model.CreateQueueResult; import com.amazonaws.services.sqs.model.GetQueueUrlResult; @Configuration public class SpringCloudAwsConfig { @Autowired private AmazonSQSAsync amazonSqsAsync; @Autowired private AmazonSNS amazonSNS; @Autowired private ResourceIdResolver resourceIdResolver; private String subscriptionArn; public static final String QUEUE_NAME = "cibp-busrefresh-queue-"+UUID.randomUUID().toString(); @Bean public QueueMessagingTemplate queueMessagingTemplate(AmazonSQSAsync amazonSqsAsync, ResourceIdResolver resourceIdResolver) { return new QueueMessagingTemplate(amazonSqsAsync, resourceIdResolver); } @Bean public NotificationMessagingTemplate notificationMessagingTemplate(AmazonSNS amazonSNS, ResourceIdResolver resourceIdResolver) { return new NotificationMessagingTemplate(amazonSNS, resourceIdResolver); } @PostConstruct public void configure( ) { CreateQueueResult queueCreateResult = amazonSqsAsync.createQueue(QUEUE_NAME); String snsTopicArn = resourceIdResolver.resolveToPhysicalResourceId("SnsTopic"); this.subscriptionArn = Topics.subscribeQueue(amazonSNS, amazonSqsAsync, snsTopicArn, queueCreateResult.getQueueUrl()); System.setProperty("my.param.name", QUEUE_NAME); } @PreDestroy public void onDestroy( ){ this.amazonSNS.unsubscribe(subscriptionArn); GetQueueUrlResult queueUrlResult = this.amazonSqsAsync.getQueueUrl(QUEUE_NAME); this.amazonSqsAsync.deleteQueue(queueUrlResult.getQueueUrl()); } }
package PageFactoryPOM; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class PayPOM { WebDriver driver; /******Payment*****/ @FindBy(xpath="//*[@id='__next']/div[1]/div/div[1]/div/div[1]/div[2]/div/input") WebElement EnterMobile; @FindBy(xpath="//*[@id='__next']/div[1]/div/div[1]/div/div[1]/div[3]/button") WebElement Login; @FindBy(xpath="//*[@id='__next']/div[1]/div/div[1]/div/div[1]/div[2]/button") WebElement Verify; @FindBy(xpath="//*[@id='__next']/div[1]/div/div[1]/div[2]/div/div[1]/div[2]") WebElement PaymentOptionA; @FindBy(xpath="//*[@id='__next']/div[1]/div/div[1]/div[2]/div/div[1]/div[3]") WebElement PaymentOptionB; @FindBy WebElement PaymentOptionCard; @FindBy(xpath="//*[@id='__next']/div[1]/div/div[1]/div[2]/div/div[1]/div[4]") WebElement PaymentOptionC; @FindBy(xpath="//*[@id='__next']/div[1]/div/div[1]/div[2]/div/div[1]/div[5]") WebElement PaymentOptionD; /********Methods*******/ public PayPOM(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } public void EnterMobileNumber(String number) { EnterMobile.sendKeys(number); } public void Login() { Login.click(); } public void Verify() { Verify.click(); } public void PaymentOptions() throws Throwable { PaymentOptionA.click(); Thread.sleep(2000); PaymentOptionB.click(); Thread.sleep(2000); PaymentOptionC.click(); Thread.sleep(2000); PaymentOptionD.click(); Thread.sleep(2000); } public void PaymentMenu() throws Throwable { PaymentOptionC.click(); Thread.sleep(2000); PaymentOptionB.click(); } }
package netistrar.clientapi.objects.utility; import netistrar.clientapi.objects.utility.BulkOperationProgressItem; import java.util.Map; /** * Encodes information about the current progress of a bulk operation. This includes the status of all contained <a href="object:Netistrar/WebServices/Common/Objects/Utility/BulkOperationProgressItem">BulkOperationProgressItem</a> objects which make up the bulk operation as well as general information about the progress of the whole operation both as a percentage and as a number of completed items for use in progressively updating GUIs etc. */ public class BulkOperationProgress { /** * The overall status of this bulk operation. This will be set to one of the following values.<br /> * <b>PENDING:</b> When the bulk operation has been created but not yet started. * <b>RUNNING:</b> When the bulk operation has been started. * <b>COMPLETED:</b> When the bulk operation has finished. */ protected String status; /** * The total number of progress items making up this bulk operation. */ protected Integer totalNumberOfItems; /** * The number of completed progress items (either successfully or not). */ protected Integer completedItems; /** * The current percentage (between 0 and 100) of progress through the bulk operation. */ protected Float percentageComplete; /** * An indicator as to whether or not there are currently any failed items in this bulk operation (useful for changing colours of progress bars etc). */ protected Boolean hasFailedItems; /** * An array of <a href="object:Netistrar/WebServices/Common/Objects/Utility/BulkOperationProgressItem">BulkOperationProgressItem</a> items each representing the progress for an individual element within a bulk operation. */ protected BulkOperationProgressItem[] progressItems; /** * Blank Constructor * */ public BulkOperationProgress(){ } /** * Get the status * * @return status */ public String getStatus(){ return this.status; } /** * Get the totalNumberOfItems * * @return totalNumberOfItems */ public Integer getTotalNumberOfItems(){ return this.totalNumberOfItems; } /** * Get the completedItems * * @return completedItems */ public Integer getCompletedItems(){ return this.completedItems; } /** * Get the percentageComplete * * @return percentageComplete */ public Float getPercentageComplete(){ return this.percentageComplete; } /** * Get the hasFailedItems * * @return hasFailedItems */ public Boolean getHasFailedItems(){ return this.hasFailedItems; } /** * Get the progressItems * * @return progressItems */ public BulkOperationProgressItem[] getProgressItems(){ return this.progressItems; } /** * Overridden equals method for doing field based equals comparison. */ public boolean equals(Object otherObject) { if (otherObject == this) return true; if (!(otherObject instanceof BulkOperationProgress)) return false; BulkOperationProgress castObject = (BulkOperationProgress)otherObject; boolean equals = true; equals = equals && ( (this.getStatus() == null && castObject.getStatus() == null) || (this.getStatus() != null && this.getStatus().equals(castObject.getStatus()))); equals = equals && ( (this.getTotalNumberOfItems() == null && castObject.getTotalNumberOfItems() == null) || (this.getTotalNumberOfItems() != null && this.getTotalNumberOfItems().equals(castObject.getTotalNumberOfItems()))); equals = equals && ( (this.getCompletedItems() == null && castObject.getCompletedItems() == null) || (this.getCompletedItems() != null && this.getCompletedItems().equals(castObject.getCompletedItems()))); equals = equals && ( (this.getPercentageComplete() == null && castObject.getPercentageComplete() == null) || (this.getPercentageComplete() != null && this.getPercentageComplete().equals(castObject.getPercentageComplete()))); equals = equals && ( (this.getHasFailedItems() == null && castObject.getHasFailedItems() == null) || (this.getHasFailedItems() != null && this.getHasFailedItems().equals(castObject.getHasFailedItems()))); equals = equals && ( (this.getProgressItems() == null && castObject.getProgressItems() == null) || (this.getProgressItems() != null && this.getProgressItems().equals(castObject.getProgressItems()))); return equals; } }
package org.bitbucket.alltra101ify.advancedsatelliteutilization.moditems; import org.bitbucket.alltra101ify.advancedsatelliteutilization.reference.ModInfo; import org.bitbucket.alltra101ify.advancedsatelliteutilization.reference.moditemblockreference.ModBasicItemTemplate; import net.minecraft.creativetab.CreativeTabs; public class SpacialFocusingModule extends ModBasicItemTemplate { public SpacialFocusingModule() { setUnlocalizedName("SpacialFocusingModule"); setTextureName(ModInfo.MODID + ":" + getUnlocalizedName().substring(5)); setMaxStackSize(16); } }
package lab411.androidserver.loadsharing; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import android.os.Environment; public class WritePerform extends Thread{ FileWriter fw1, fw2; BufferedWriter bw1, bw2; public boolean run; public WritePerform(String cpuFile, String memFile) throws IOException { File sdcard = Environment.getExternalStorageDirectory(); File fo1 = new File(sdcard, cpuFile); File fo2 = new File(sdcard, memFile); if (!fo1.exists()) fo1.createNewFile(); if (!fo2.exists()) fo2.createNewFile(); fw1 = new FileWriter(fo1.getAbsoluteFile()); fw2 = new FileWriter(fo2.getAbsoluteFile()); bw1 = new BufferedWriter(fw1); bw2 = new BufferedWriter(fw2); } @Override public void run() { run = true; // TODO Auto-generated method stub try { while (run) { bw1.write(String.format("%.2f", Performance.cpu) + "\n"); bw2.write(String.format("%.2f", Performance.memProcess) + "\n"); Thread.sleep(100); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { bw1.close(); fw1.close(); bw2.close(); fw2.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package org.kuali.ole.describe.bo; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrServerException; import org.kuali.ole.docstore.discovery.service.QueryService; import org.kuali.ole.docstore.discovery.service.QueryServiceImpl; import org.kuali.ole.docstore.model.bo.*; import org.kuali.ole.docstore.model.enums.DocCategory; import org.kuali.ole.docstore.model.enums.DocType; import org.kuali.ole.describe.service.DocstoreHelperService; import org.kuali.rice.core.api.util.tree.Node; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created with IntelliJ IDEA. * User: Sreekanth * Date: 12/20/12 * Time: 11:11 AM * To change this template use File | Settings | File Templates. */ public class DocumentSelectionTree { private Node<DocumentTreeNode, String> rootNode; public DocumentSelectionTree() { initTree(); } protected void initTree() { rootNode = new Node<DocumentTreeNode, String>(new DocumentTreeNode()); } public Node<DocumentTreeNode, String> add(Collection<String> uuidList, String docType) throws SolrServerException { List<Node<DocumentTreeNode, String>> nodeList = null; Node<DocumentTreeNode, String> node = null; if (!StringUtils.isBlank(docType)) { if (docType.equalsIgnoreCase(DocType.BIB.getDescription())) { List<WorkBibDocument> bibDocumentList = buildDocTreeList(DocCategory.WORK.getCode(), docType, uuidList); nodeList = buildNodeList(bibDocumentList); for (Node<DocumentTreeNode, String> bibNode : nodeList) { rootNode.addChild(bibNode); } } if (docType.equalsIgnoreCase((DocType.INSTANCE.getCode()))) { List<WorkInstanceDocument> instanceDocumentList = buildInstanceTreeList(DocCategory.WORK.getCode(), docType, uuidList); for (WorkInstanceDocument workInstanceDocument : instanceDocumentList) { node = buildInstanceNode(workInstanceDocument); rootNode.addChild(node); } } if (docType.equalsIgnoreCase(DocType.ITEM.getCode())) { List<WorkItemDocument> itemDocumentList = buildItemTreeList(DocCategory.WORK.getCode(), docType, uuidList); for (WorkItemDocument workItemDocument : itemDocumentList) { node = buildItemNode(workItemDocument); rootNode.addChild(node); } } if (docType.equalsIgnoreCase((DocType.EINSTANCE.getCode()))) { List<WorkEInstanceDocument> instanceDocumentList = buildEInstanceTreeList(DocCategory.WORK.getCode(), docType, uuidList); for (WorkEInstanceDocument workEInstanceDocument : instanceDocumentList) { node = buildEInstanceNode(workEInstanceDocument); rootNode.addChild(node); } } } return rootNode; } /** * @param category * @param docType * @param uuidList * @return */ private List<WorkBibDocument> buildDocTreeList(String category, String docType, Collection<String> uuidList) { DocstoreHelperService docstoreHelperService = new DocstoreHelperService(); List<WorkBibDocument> workBibDocumentList = new ArrayList<WorkBibDocument>(); if (uuidList != null && uuidList.size() > 0) { for (String uuid : uuidList) { WorkBibDocument workBibDocument = new WorkBibDocument(); workBibDocument.setId(uuid); workBibDocument = docstoreHelperService.getInfoForBibTree(workBibDocument); workBibDocumentList.add(workBibDocument); } } return workBibDocumentList; } private List<WorkInstanceDocument> buildInstanceTreeList(String category, String docType, Collection<String> uuidList) throws SolrServerException { List<WorkInstanceDocument> workInstanceDocumentList = new ArrayList<WorkInstanceDocument>(); QueryService queryService = QueryServiceImpl.getInstance(); for (String uuid : uuidList) { WorkInstanceDocument workInstanceDocument = new WorkInstanceDocument(); workInstanceDocument.setId(uuid); workInstanceDocumentList.add(queryService.queryForInstanceTree(workInstanceDocument)); } return workInstanceDocumentList; } private List<WorkItemDocument> buildItemTreeList(String category, String docType, Collection<String> uuidList) throws SolrServerException { List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>(); QueryService queryService = QueryServiceImpl.getInstance(); for (String uuid : uuidList) { WorkItemDocument workItemDocument = new WorkItemDocument(); workItemDocument.setId(uuid); workItemDocumentList.add(queryService.queryForItemTree(workItemDocument)); } return workItemDocumentList; } private List<WorkEInstanceDocument> buildEInstanceTreeList(String category, String docType, Collection<String> uuidList) throws SolrServerException { List<WorkEInstanceDocument> workEInstanceDocumentList = new ArrayList<WorkEInstanceDocument>(); QueryService queryService = QueryServiceImpl.getInstance(); for (String uuid : uuidList) { WorkEInstanceDocument workEInstanceDocument = new WorkEInstanceDocument(); workEInstanceDocument.setId(uuid); workEInstanceDocumentList.add(queryService.queryForEInstanceTree(workEInstanceDocument)); } return workEInstanceDocumentList; } public void remove() { } /** * @param bibDocumentList * @return */ public List<Node<DocumentTreeNode, String>> buildNodeList(List<WorkBibDocument> bibDocumentList) { List<Node<DocumentTreeNode, String>> nodeList = new ArrayList<Node<DocumentTreeNode, String>>(); DocumentTreeNode dst = new DocumentTreeNode(); for (WorkBibDocument workBibDocument : bibDocumentList) { DocumentTreeNode bibDocumentNode = new DocumentTreeNode(); bibDocumentNode.setWorkBibDocument(workBibDocument); String title = workBibDocument.getTitle(); Node<DocumentTreeNode, String> bibNode = new Node<DocumentTreeNode, String>( new DocumentTreeNode(), bibDocumentNode.getTitle()); bibNode.setNodeType(bibDocumentNode.getUuid()); bibNode.setNodeLabel(bibDocumentNode.getTitle()); List<WorkInstanceDocument> workInstanceDocumentList = workBibDocument.getWorkInstanceDocumentList(); Node<DocumentTreeNode, String> instanceNode; Node<DocumentTreeNode, String> itemNode = null; if (workInstanceDocumentList != null) { for (WorkInstanceDocument workInstanceDocument : workInstanceDocumentList) { instanceNode = buildInstanceNode(workInstanceDocument); bibNode.addChild(instanceNode); } } nodeList.add(bibNode); } return nodeList; } private Node<DocumentTreeNode, String> buildInstanceNode(WorkInstanceDocument workInstanceDocument) { Node<DocumentTreeNode, String> instanceNode; List<WorkItemDocument> workItemDocumentList; DocumentTreeNode instanceDocumentNode = new DocumentTreeNode(); instanceDocumentNode.setWorkInstanceDocument(workInstanceDocument); instanceNode = new Node<DocumentTreeNode, String>( new DocumentTreeNode(), instanceDocumentNode.getTitle()); instanceNode.setNodeType(instanceDocumentNode.getUuid()); instanceNode.setNodeLabel(instanceDocumentNode.getTitle()); workItemDocumentList = workInstanceDocument.getItemDocumentList(); if (workItemDocumentList != null) { Node<DocumentTreeNode, String> itemNode; for (WorkItemDocument workItemDocument : workItemDocumentList) { itemNode = buildHoldingsNode(workItemDocument, workInstanceDocument.getHoldingsDocument()); instanceNode.addChild(itemNode); } } return instanceNode; } private Node<DocumentTreeNode, String> buildItemNode(WorkItemDocument workItemDocument) { Node<DocumentTreeNode, String> itemNode; DocumentTreeNode itemDocumentNode = new DocumentTreeNode(); itemDocumentNode.setWorkItemDocument(workItemDocument); itemNode = new Node<DocumentTreeNode, String>(new DocumentTreeNode(), itemDocumentNode.getTitle()); itemNode.setNodeType(itemDocumentNode.getUuid()); itemNode.setNodeLabel(itemDocumentNode.getTitle()); return itemNode; } private Node<DocumentTreeNode, String> buildHoldingsNode(WorkItemDocument workItemDocument, WorkHoldingsDocument workHoldingsDocument) { Node<DocumentTreeNode, String> itemNode; DocumentTreeNode itemDocumentNode = new DocumentTreeNode(); itemDocumentNode.setWorkHoldingsDocument(workItemDocument, workHoldingsDocument); itemNode = new Node<DocumentTreeNode, String>(new DocumentTreeNode(), itemDocumentNode.getTitle()); itemNode.setNodeType(itemDocumentNode.getUuid()); itemNode.setNodeLabel(itemDocumentNode.getTitle()); return itemNode; } private Node<DocumentTreeNode, String> buildEInstanceNode(WorkEInstanceDocument workEInstanceDocument) { Node<DocumentTreeNode, String> eInstanceNode; DocumentTreeNode instanceDocumentNode = new DocumentTreeNode(); instanceDocumentNode.setWorkEInstanceDocument(workEInstanceDocument); eInstanceNode = new Node<DocumentTreeNode, String>( new DocumentTreeNode(), instanceDocumentNode.getTitle()); eInstanceNode.setNodeType(instanceDocumentNode.getUuid()); eInstanceNode.setNodeLabel(instanceDocumentNode.getTitle()); return eInstanceNode; } public Node<DocumentTreeNode, String> addForTransfer(List<String> uuidList) { List<WorkBibDocument> bibDocumentList = buildDocTreeList(DocCategory.WORK.getCode(), DocType.BIB.getDescription(), uuidList); List<Node<DocumentTreeNode, String>> nodeList = buildNodeListForTransfer(bibDocumentList); for (Node<DocumentTreeNode, String> node : nodeList) { rootNode.addChild(node); } return rootNode; } /** * @param bibDocumentList * @return */ public List<Node<DocumentTreeNode, String>> buildNodeListForTransfer(List<WorkBibDocument> bibDocumentList) { List<Node<DocumentTreeNode, String>> nodeList = new ArrayList<Node<DocumentTreeNode, String>>(); DocumentTreeNode dst = new DocumentTreeNode(); int count = 0; for (WorkBibDocument workBibDocument : bibDocumentList) { DocumentTreeNode bibDocumentNode = new DocumentTreeNode(); bibDocumentNode.setWorkBibDocument(workBibDocument); String title = workBibDocument.getTitle(); Node<DocumentTreeNode, String> bibNode = new Node<DocumentTreeNode, String>(new DocumentTreeNode(), bibDocumentNode.getTitle()); bibNode.setNodeType(bibDocumentNode.getUuid()); bibNode.setNodeLabel(bibDocumentNode.getTitle()); List<WorkInstanceDocument> workInstanceDocumentList = workBibDocument.getWorkInstanceDocumentList(); WorkHoldingsDocument workHoldingsDocument = new WorkHoldingsDocument(); List<WorkItemDocument> workItemDocumentList = new ArrayList<WorkItemDocument>(); Node<DocumentTreeNode, String> instanceNode; Node<DocumentTreeNode, String> itemNode = null; if (workInstanceDocumentList != null) { for (WorkInstanceDocument workInstanceDocument : workInstanceDocumentList) { DocumentTreeNode instanceDocumentNode = new DocumentTreeNode(); instanceDocumentNode.setWorkInstanceDocument(workInstanceDocument); instanceNode = new Node<DocumentTreeNode, String>(new DocumentTreeNode(), instanceDocumentNode.getTitle()); instanceNode.setNodeType(instanceDocumentNode.getUuid()); instanceNode.setNodeLabel(instanceDocumentNode.getTitle()); workItemDocumentList = workInstanceDocument.getItemDocumentList(); if (workItemDocumentList != null) { for (WorkItemDocument workItemDocument : workItemDocumentList) { DocumentTreeNode itemDocumentNode = new DocumentTreeNode(); itemDocumentNode.setWorkItemDocument(workItemDocument); itemNode = new Node<DocumentTreeNode, String>(new DocumentTreeNode(), itemDocumentNode.getTitle()); itemNode.setNodeType(itemDocumentNode.getUuid()); itemNode.setNodeLabel(itemDocumentNode.getTitle()); instanceNode.addChild(itemNode); } } bibNode.addChild(instanceNode); } } nodeList.add(bibNode); } return nodeList; } }
package com.soldevelo.vmi.testclient.facade; import com.soldevelo.vmi.enumerations.DiagnosticState; import com.soldevelo.vmi.enumerations.Direction; import com.soldevelo.vmi.packets.TestResult; import com.soldevelo.vmi.testclient.execution.HttpDownloadWorker; import com.soldevelo.vmi.testclient.execution.HttpTestWorker; import com.soldevelo.vmi.testclient.execution.HttpUploadWorker; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @Service public class HttpTestFacadeImpl implements HttpTestFacade { private static final Logger LOG = LoggerFactory.getLogger(HttpTestFacade.class); @Override public TestResult executeDownloadTest(String downloadUrl, long downloadSize, int threadNumber) { LOG.info("Executing http download test using " + threadNumber + " threads"); return executeTest(downloadUrl, downloadSize, threadNumber, Direction.DOWNLOAD); } @Override public TestResult executeUploadTest(String uploadUrl, long uploadSize, int threadNumber) { LOG.info("Executing http upload test using " + threadNumber + " threads"); return executeTest(uploadUrl, uploadSize, threadNumber, Direction.UPLOAD); } private TestResult executeTest(String url, long size, int threadNumber, String direction) { ExecutorService executorService = null; List<HttpTestWorker> workers = new ArrayList<HttpTestWorker>(); for (int i = 0; i < threadNumber; i++) { HttpTestWorker worker = (StringUtils.equals(direction, Direction.DOWNLOAD)) ? new HttpDownloadWorker(url, size) : new HttpUploadWorker(url, size); workers.add(worker); } try { executorService = Executors.newFixedThreadPool(threadNumber); List<Future<TestResult>> futures = executorService.invokeAll(workers); List<TestResult> testResults = new ArrayList<TestResult>(); for (Future<TestResult> future : futures) { testResults.add(future.get()); } return buildTestResult(testResults); } catch (Exception e) { LOG.error("Error while executing tests", e); return failureTestResult(url); } finally { if (executorService != null) { executorService.shutdown(); } } } private TestResult buildTestResult(List<TestResult> results) { TestResult testResult = new TestResult(); TestResult firstResult = results.get(0); TestResult lastResult = results.get(results.size() - 1); testResult.setDownloadOrUploadUrl(firstResult.getDownloadOrUploadUrl()); testResult.setDestinationPort(firstResult.getDestinationPort()); testResult.setBomTime(firstResult.getBomTime()); testResult.setEomTime(lastResult.getEomTime()); testResult.setRomTime(lastResult.getRomTime()); testResult.setTcpOpenRequestTime(testResult.getBomTime()); testResult.setTcpOpenResponseTime(testResult.getEomTime()); testResult.setDiagnosticState(selectDiagnosticState(results)); testResult.setTotalBytesReceivedOrSent(countTotalBytesReceivedOrSent(results)); testResult.setTestBytesReceivedOrFileLength(countTestBytesReceivedOrFileLength(results)); return testResult; } private String selectDiagnosticState(List<TestResult> testResults) { String diagnosticState = testResults.get(0).getDiagnosticState(); if (DiagnosticState.COMPLETED.equals(diagnosticState)) { for (TestResult testResult : testResults) { if (DiagnosticState.COMPLETED.equals(testResult.getDiagnosticState())) { diagnosticState = testResult.getDiagnosticState(); break; } } } return diagnosticState; } private long countTotalBytesReceivedOrSent(List<TestResult> testResults) { long sum = 0; for (TestResult testResult : testResults) { sum += testResult.getTotalBytesReceivedOrSent(); } return sum; } private long countTestBytesReceivedOrFileLength(List<TestResult> testResults) { long sum = 0; for (TestResult testResult : testResults) { sum += testResult.getTestBytesReceivedOrFileLength(); } return sum; } private TestResult failureTestResult(String url) { TestResult testResult = new TestResult(); testResult.setDiagnosticState(DiagnosticState.ERROR_INIT_CONNECTION_FAILED); testResult.setRomTime(""); testResult.setBomTime(""); testResult.setEomTime(""); testResult.setTcpOpenResponseTime(""); testResult.setTcpOpenRequestTime(""); testResult.setDownloadOrUploadUrl(url); return testResult; } private enum TestType { UPLOAD, DOWNLOAD } }
package com.zhongyp.jvm; /** * @author zhongyp. * @date 2019/8/10 */ public interface ClassStructureDemoSuperInterface { int a = 1; public void interfaceFunc(); }
package com.k2data.k2app.exception; import com.k2data.k2app.constant.ResponseCode; /** * data not found exception * * @author WangShengguo */ public class DataNotFoundException extends K2ResponseException { private static final long serialVersionUID = -5999409754794135010L; private static final String SEPARATOR = ": "; public DataNotFoundException() { super(ResponseCode.GENERAL_RESULT_NOT_FOUND, ResponseCode.MSG_RESULT_NOT_FOUND); } public DataNotFoundException(String extraMessage) { super(ResponseCode.GENERAL_RESULT_NOT_FOUND, ResponseCode.MSG_RESULT_NOT_FOUND + SEPARATOR + extraMessage); } }
package com.needii.dashboard.view; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.view.document.AbstractXlsView; import com.needii.dashboard.components.Messages; import com.needii.dashboard.model.Product; public class ProductExportExcel extends AbstractXlsView { @Autowired Messages messages; @Override protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setHeader("Content-Disposition", "attachment; filename=\"product-list.xls\""); @SuppressWarnings("unchecked") List<Product> products = (List<Product>) model.get("products"); Sheet sheet = workbook.createSheet("Product list"); // Create header row Row header = sheet.createRow(0); header.createCell(0).setCellValue("Mã sản phẩm"); header.createCell(1).setCellValue("Tên sản phẩm"); header.createCell(2).setCellValue("Nhà cung cấp"); header.createCell(3).setCellValue("Trạng thái"); header.createCell(4).setCellValue("Danh mục"); header.createCell(5).setCellValue("Số lượng tồn kho"); header.createCell(6).setCellValue("Số lượng đã bán"); header.createCell(7).setCellValue("Cash back"); header.createCell(8).setCellValue("Giá sản phẩm"); header.createCell(9).setCellValue("Giá khuyến mãi"); header.createCell(10).setCellValue("Số tiền khuyến mãi"); header.createCell(11).setCellValue("% giảm giá"); header.createCell(12).setCellValue("Mã sku"); // Create data cells int rowCount = 1; for (Product product : products){ Row courseRow = sheet.createRow(rowCount++); courseRow.createCell(0).setCellValue(product.getId()); courseRow.createCell(1).setCellValue(product.getData().getName()); courseRow.createCell(2).setCellValue(product.getSupplier().getFullName()); courseRow.createCell(3).setCellValue(product.getProductStatusString()); courseRow.createCell(4).setCellValue(product.getCategory().getData().getName()); courseRow.createCell(5).setCellValue(product.getQuantity()); courseRow.createCell(6).setCellValue(product.getSellCount()); courseRow.createCell(7).setCellValue(product.getCashbackAmount()); courseRow.createCell(8).setCellValue(product.amountToCurrencyString(product.getPrice())); courseRow.createCell(9).setCellValue(product.amountToCurrencyString(product.getLastPrice())); courseRow.createCell(10).setCellValue(product.amountToCurrencyString(product.getDiscountPercent() * product.getPrice())); courseRow.createCell(11).setCellValue(product.getDiscountPercent()); String skuId = ""; for (int i = 0; i < product.getSkuses().size(); i++) { skuId += product.getSkuses().get(i).getSkuCode() + "-"; } courseRow.createCell(12).setCellValue(skuId); } } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.expression.spel.ast; import java.math.BigDecimal; import java.math.BigInteger; import org.springframework.asm.MethodVisitor; import org.springframework.expression.EvaluationException; import org.springframework.expression.Operation; import org.springframework.expression.TypedValue; import org.springframework.expression.spel.CodeFlow; import org.springframework.expression.spel.ExpressionState; import org.springframework.util.Assert; import org.springframework.util.NumberUtils; /** * The minus operator supports: * <ul> * <li>subtraction of numbers * <li>subtraction of an int from a string of one character * (effectively decreasing that character), so 'd'-3='a' * </ul> * * <p>It can be used as a unary operator for numbers. * The standard promotions are performed when the operand types vary (double-int=double). * For other options it defers to the registered overloader. * * @author Andy Clement * @author Juergen Hoeller * @author Giovanni Dall'Oglio Risso * @author Sam Brannen * @since 3.0 */ public class OpMinus extends Operator { public OpMinus(int startPos, int endPos, SpelNodeImpl... operands) { super("-", startPos, endPos, operands); } @Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { SpelNodeImpl leftOp = getLeftOperand(); if (this.children.length < 2) { // if only one operand, then this is unary minus Object operand = leftOp.getValueInternal(state).getValue(); if (operand instanceof Number number) { if (number instanceof BigDecimal bigDecimal) { return new TypedValue(bigDecimal.negate()); } else if (number instanceof BigInteger bigInteger) { return new TypedValue(bigInteger.negate()); } else if (number instanceof Double) { this.exitTypeDescriptor = "D"; return new TypedValue(0 - number.doubleValue()); } else if (number instanceof Float) { this.exitTypeDescriptor = "F"; return new TypedValue(0 - number.floatValue()); } else if (number instanceof Long) { this.exitTypeDescriptor = "J"; return new TypedValue(0 - number.longValue()); } else if (number instanceof Integer) { this.exitTypeDescriptor = "I"; return new TypedValue(0 - number.intValue()); } else if (number instanceof Short) { return new TypedValue(0 - number.shortValue()); } else if (number instanceof Byte) { return new TypedValue(0 - number.byteValue()); } else { // Unknown Number subtype -> best guess is double subtraction return new TypedValue(0 - number.doubleValue()); } } return state.operate(Operation.SUBTRACT, operand, null); } Object left = leftOp.getValueInternal(state).getValue(); Object right = getRightOperand().getValueInternal(state).getValue(); if (left instanceof Number leftNumber && right instanceof Number rightNumber) { if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) { BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class); BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class); return new TypedValue(leftBigDecimal.subtract(rightBigDecimal)); } else if (leftNumber instanceof Double || rightNumber instanceof Double) { this.exitTypeDescriptor = "D"; return new TypedValue(leftNumber.doubleValue() - rightNumber.doubleValue()); } else if (leftNumber instanceof Float || rightNumber instanceof Float) { this.exitTypeDescriptor = "F"; return new TypedValue(leftNumber.floatValue() - rightNumber.floatValue()); } else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) { BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class); BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class); return new TypedValue(leftBigInteger.subtract(rightBigInteger)); } else if (leftNumber instanceof Long || rightNumber instanceof Long) { this.exitTypeDescriptor = "J"; return new TypedValue(leftNumber.longValue() - rightNumber.longValue()); } else if (CodeFlow.isIntegerForNumericOp(leftNumber) || CodeFlow.isIntegerForNumericOp(rightNumber)) { this.exitTypeDescriptor = "I"; return new TypedValue(leftNumber.intValue() - rightNumber.intValue()); } else { // Unknown Number subtypes -> best guess is double subtraction return new TypedValue(leftNumber.doubleValue() - rightNumber.doubleValue()); } } if (left instanceof String theString && right instanceof Integer theInteger && theString.length() == 1) { // Implements character - int (ie. b - 1 = a) return new TypedValue(Character.toString((char) (theString.charAt(0) - theInteger))); } return state.operate(Operation.SUBTRACT, left, right); } @Override public String toStringAST() { if (this.children.length < 2) { // unary minus return "-" + getLeftOperand().toStringAST(); } return super.toStringAST(); } @Override public SpelNodeImpl getRightOperand() { if (this.children.length < 2) { throw new IllegalStateException("No right operand"); } return this.children[1]; } @Override public boolean isCompilable() { if (!getLeftOperand().isCompilable()) { return false; } if (this.children.length > 1) { if (!getRightOperand().isCompilable()) { return false; } } return (this.exitTypeDescriptor != null); } @Override public void generateCode(MethodVisitor mv, CodeFlow cf) { getLeftOperand().generateCode(mv, cf); String leftDesc = getLeftOperand().exitTypeDescriptor; String exitDesc = this.exitTypeDescriptor; Assert.state(exitDesc != null, "No exit type descriptor"); char targetDesc = exitDesc.charAt(0); CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, leftDesc, targetDesc); if (this.children.length > 1) { cf.enterCompilationScope(); getRightOperand().generateCode(mv, cf); String rightDesc = getRightOperand().exitTypeDescriptor; cf.exitCompilationScope(); CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc); switch (targetDesc) { case 'I' -> mv.visitInsn(ISUB); case 'J' -> mv.visitInsn(LSUB); case 'F' -> mv.visitInsn(FSUB); case 'D' -> mv.visitInsn(DSUB); default -> throw new IllegalStateException( "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'"); } } else { switch (targetDesc) { case 'I' -> mv.visitInsn(INEG); case 'J' -> mv.visitInsn(LNEG); case 'F' -> mv.visitInsn(FNEG); case 'D' -> mv.visitInsn(DNEG); default -> throw new IllegalStateException( "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'"); } } cf.pushDescriptor(this.exitTypeDescriptor); } }
package com.miyatu.tianshixiaobai.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.chad.library.adapter.base.BaseViewHolder; import com.miyatu.tianshixiaobai.R; import com.miyatu.tianshixiaobai.entity.CommonFunctionsEntity; import java.util.List; public class CommonFunctionsAdapter extends RecyclerView.Adapter<BaseViewHolder> { private Context context; private int viewType; private List<CommonFunctionsEntity> dataList; private OnItemClickListener itemListener; private OnClickListener listener; public static final int TYPE_COMMON_FUNCTIONS = 1; public int getItemViewType(int position) { return viewType; } public void setViewType(int viewType) { this.viewType = viewType; } public CommonFunctionsAdapter(Context context, List<CommonFunctionsEntity> data, int viewType) { this.context = context; this.viewType = viewType; if (viewType == TYPE_COMMON_FUNCTIONS) { this.dataList = data; } } public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { switch (viewType) { case TYPE_COMMON_FUNCTIONS: View view = LayoutInflater.from(context).inflate(R.layout.item_common_functions, parent, false); return new CommonFunctionsHolder(view); } return null; } @Override public void onBindViewHolder(@NonNull final BaseViewHolder holder, final int position) { if (holder instanceof CommonFunctionsHolder) { CommonFunctionsEntity entity = dataList.get(position); ((CommonFunctionsHolder) holder).image.setImageResource(entity.getImage()); ((CommonFunctionsHolder) holder).text.setText(entity.getText()); ((CommonFunctionsHolder) holder).linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onClick(position,v); } }); } } @Override public int getItemCount() { if (viewType == TYPE_COMMON_FUNCTIONS) { return dataList.size(); } else { return 0; } } class CommonFunctionsHolder extends BaseViewHolder { private ImageView image; private TextView text; private LinearLayout linearLayout; public CommonFunctionsHolder(@NonNull View itemView) { super(itemView); image = itemView.findViewById(R.id.imageView); text = itemView.findViewById(R.id.textView); linearLayout = itemView.findViewById(R.id.linearLayout); } } public void setOnItemClickListener(OnItemClickListener itemListener) { this.itemListener = itemListener; } public void setOnClickListener(OnClickListener listener) { this.listener = listener; } public interface OnItemClickListener { void onItemClick(int position); } public interface OnClickListener { void onClick(int position, View view); } }
package kr.co.shop.batch.order.repository.master; import java.util.List; import org.apache.ibatis.annotations.Mapper; import kr.co.shop.batch.order.model.master.OcOrderProduct; import kr.co.shop.batch.order.repository.master.base.BaseOcOrderProductDao; @Mapper public interface OcOrderProductDao extends BaseOcOrderProductDao { /** * 기본 insert, update, delete 메소드는 BaseOcOrderProductDao 클래스에 구현 되어있습니다. * BaseOcOrderProductDao는 절대 수정 불가 하며 새로운 메소드 추가 하실 경우에는 해당 소스에서 작업 하시면 됩니다. * */ public OcOrderProduct selectByPrimaryKey(OcOrderProduct ocOrderProduct) throws Exception; /** * * @Desc : 주문상품 데이터 조회 * @Method Name : selectPurchaseConfirmOrderProductDataList * @Date : 2019. 5. 20. * @Author : 주상곤 * @param OcOrderProduct * @return * @throws Exception */ public List<OcOrderProduct> selectPurchaseConfirmOrderProductDataList(OcOrderProduct OcOrderProduct) throws Exception; /** * * @Desc : * @Method Name : updateOrderProduct * @Date : 2019. 7. 1. * @Author : NKB * @param OcOrderProduct * @return * @throws Exception */ public int updateOrderProduct(OcOrderProduct OcOrderProduct) throws Exception; /** * @Desc : * @Method Name : getOrderProductList * @Date : 2019. 7. 8. * @Author : 유성민 * @param orderNo * @return */ public List<OcOrderProduct> getOrderProductList(String orderNo) throws Exception; }
package com.example.fragsrcsimplity; import android.os.Bundle; import android.view.View; import android.widget.Button; /** * Created by zhouzhou on 2016/11/6. */ public class ActivityMain extends FragTestActivity { //FragmentActivity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_frag_test); Button btnLoadFrag1 = (Button) findViewById(R.id.id_btn_show_fragment1); btnLoadFrag1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragTestManager manager = getSupportFragTestManager(); FragTestTransaction transaction = manager.beginTransaction(); FragTest1 fragment1 = new FragTest1(); transaction.add(R.id.id_fragment_container, fragment1); transaction.commit(); } }); } }
import org.apache.kafka.clients.producer.*; import java.util.Properties; /** * 生产者的配置和提交(简单提交,同步提交和异步提交) */ public class KafkaProducerDemo { public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "broker1:9092,broker2:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props); ProducerRecord<String, String> record = new ProducerRecord<String, String>("CustomerCountry", "Precision Products", "France"); simpleSendMessage(producer, record); synSendMessage(producer, record); asynSendMessage(producer, record); } /** * 异步提交消息 * @param producer * @param record */ private static void asynSendMessage(KafkaProducer<String, String> producer, ProducerRecord<String, String> record) { try { producer.send(record, new DemoProducerCallback()); } catch (Exception e) { e.printStackTrace(); } } /** * 同步提交消息 * @param producer * @param record */ private static void synSendMessage(KafkaProducer<String, String> producer, ProducerRecord<String, String> record) { try { producer.send(record).get(); } catch (Exception e) { e.printStackTrace(); } } /** * 普通发送消息 * @param producer * @param record */ private static void simpleSendMessage(KafkaProducer<String, String> producer, ProducerRecord<String, String> record) { try { producer.send(record); } catch (Exception e) { e.printStackTrace(); } } private static class DemoProducerCallback implements Callback { public void onCompletion(RecordMetadata recordMetadata, Exception e) { if (e != null) { e.printStackTrace(); } } } }
package io.github.biezhi.java8.concurrent; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * ConcurrentMap * <p> * forEach * putIfAbsent * getOrDefault * replaceAll * compute * merge * search * reduce * * @author biezhi * @date 2018/3/5 */ public class ConcurrentMapExample { public static void main(String[] args) { ConcurrentMap<String, String> map = new ConcurrentHashMap<>(); map.put("foo", "bar"); map.put("han", "solo"); map.put("r2", "d2"); map.put("c3", "p0"); map.forEach((key, value) -> System.out.printf("%s = %s\n", key, value)); } }
package GradleTest; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class Test { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","F:\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://leaftaps.com/opentaps/control/main"); driver.findElement(By.id("username")).sendKeys("DemoSalesManager"); driver.findElement(By.id("password")).sendKeys("crmsfa"); driver.findElement(By.className("decorativeSubmit")).click(); driver.findElement(By.xpath("//img[@src='/opentaps_images/integratingweb/crm.png']")).click(); driver.findElement(By.linkText("Marketing")).click(); driver.findElement(By.linkText("Create Campaign")).click(); driver.findElement(By.id("createMarketingCampaignForm_campaignName")).sendKeys("siva"); driver.findElement(By.id("createMarketingCampaignForm_fromDate")).sendKeys("03/12/20"); WebElement hour=driver.findElement(By.name("fromDate_c_hour")); WebElement min=driver.findElement(By.name("fromDate_c_minutes")); //WebElement ampm=driver.findElement(By.name("fromDate_c_ampm"); Select hr=new Select(hour); Select mi=new Select(min); //Select ap=new Select(ampm); hr.selectByVisibleText("9"); mi.selectByVisibleText("56"); //ap.selectByVisibleText("PM"); } }
package app.com.thetechnocafe.eventos.Dialogs; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.widget.DatePicker; import java.util.Calendar; /** * Created by gurleensethi on 22/08/16. */ public class DialogDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener { private static final String DATE_TAG = "datetag"; private static final String DATE_MONTH_TAG = "datemonth"; private static final String DATE_DAY_TAG = "dateday"; private static final String DATE_YEAR_TAG = "dateyear"; private static Calendar mSelectedDate; public static DialogDatePicker getInstance(Calendar date) { DialogDatePicker dialogDatePicker = new DialogDatePicker(); mSelectedDate = date; return dialogDatePicker; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar calendar = Calendar.getInstance(); calendar.setTime(calendar.getTime()); int day = calendar.get(Calendar.DAY_OF_MONTH); int month = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR); DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day); return datePickerDialog; } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Intent intent = new Intent(); intent.putExtra(DATE_DAY_TAG, dayOfMonth); intent.putExtra(DATE_MONTH_TAG, monthOfYear); intent.putExtra(DATE_YEAR_TAG, year); getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent); } public static Calendar getDate(Intent intent, Calendar calendar) { calendar.setTime(mSelectedDate.getTime()); calendar.set(intent.getIntExtra(DATE_YEAR_TAG, 0), intent.getIntExtra(DATE_MONTH_TAG, 0), intent.getIntExtra(DATE_DAY_TAG, 0)); return calendar; } }
package org.sky.base.service; import org.apache.log4j.Logger; import java.sql.Timestamp; import java.util.List; import org.sky.sys.client.SysCommonMapper; import org.sky.base.client.BaseMsgMapper; import org.sky.sys.exception.ServiceException; import org.sky.base.model.BaseMsg; import org.sky.base.model.BaseMsgExample; import org.sky.sys.utils.PageListData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.sky.sys.utils.BspUtils; import org.sky.sys.utils.CommonUtils; import org.sky.sys.utils.StringUtils; @Service public class BaseMsgService { private final Logger logger=Logger.getLogger(BaseMsgService.class); @Autowired private BaseMsgMapper basemsgmapper; @Autowired private SysCommonMapper syscommonmapper; /** *分页查询 **/ public PageListData getBaseMsgByPage(BaseMsgExample ep){ long totalCount = basemsgmapper.countByExample(ep); List list = basemsgmapper.selectByExample(ep); PageListData pld = new PageListData(); pld.setTotal(totalCount); pld.setRows(list); return pld; } /** *保存列表新增及修改 **/ @Transactional public void saveBaseMsg(List<BaseMsg> addlist, List<BaseMsg> updatelist) throws ServiceException{ try{ if(null!=addlist&&addlist.size()>0){ for(BaseMsg add:addlist){ basemsgmapper.insertSelective(add); } } if(null!=updatelist&&updatelist.size()>0){ for(BaseMsg update:updatelist){ basemsgmapper.updateByPrimaryKeySelective(update); } } }catch(Exception e){ logger.error("保存列表新增及修改执行失败",e); if(e.getMessage().contains("的值太大")){ throw new ServiceException("输入的字段值过长!"); } throw new ServiceException(e.getMessage()); } } /** *保存添加单个对象 **/ @Transactional public void saveAddBaseMsg(BaseMsg add) throws ServiceException{ try{ basemsgmapper.insertSelective(add); }catch(Exception e){ logger.error("保存添加单个对象执行失败",e); if(e.getMessage().contains("违反唯一约束条件")){ throw new ServiceException("违反唯一约束条件"); }else{ throw new ServiceException(e.getMessage()); } } } /** *保存新增/编辑单个对象 **/ @Transactional public void saveAddEditBaseMsg(BaseMsg edit) throws ServiceException{ try{ Timestamp ts = syscommonmapper.queryTimestamp(); if(StringUtils.isNull(edit.getId())){ //新增 edit.setId(CommonUtils.getUUID(32)); edit.setCreater(BspUtils.getLoginUser().getCode()); edit.setCreateTime(ts); edit.setUpdater(BspUtils.getLoginUser().getCode()); edit.setUpdateTime(ts); basemsgmapper.insertSelective(edit); }else{ //修改 edit.setUpdater(BspUtils.getLoginUser().getCode()); edit.setUpdateTime(ts); basemsgmapper.updateByPrimaryKeySelective(edit); } }catch(Exception e){ logger.error("保存新增/编辑单个对象执行失败",e); throw new ServiceException(e.getMessage()); } } /** *根据主键批量删除对象 **/ @Transactional public void delBaseMsgById(List<BaseMsg> delList){ for(BaseMsg del:delList){ basemsgmapper.deleteByPrimaryKey(del.getId()); } } /** *根据主键查询对象 **/ public BaseMsg getBaseMsgById(String id){ BaseMsg bean = basemsgmapper.selectByPrimaryKey(id); return bean; } }
package com.example.root.parliament; public class Attendance { String seat; String name; String state,constituency; String signed; public Attendance(String seat, String name, String state, String constituency, String signed) { this.seat = seat; this.name = name; this.state = state; this.constituency = constituency; this.signed = signed; } public Attendance() { } public String getSeat() { return seat; } public void setSeat(String seat) { this.seat = seat; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getConstituency() { return constituency; } public void setConstituency(String constituency) { this.constituency = constituency; } public String getSigned() { return signed; } public void setSigned(String signed) { this.signed = signed; } }
package com.gaoshin.cloud.web.job.bean; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Task { private Long id; private String name; private Long jobId; private String handler; private int numOfRetries = 1; private int execOrder; private long expectedDuration; private int retryInterval = 0; private boolean errorHandlingTask = false; private String args; private boolean disabled = false; private String description; public void setHandler(String handler) { this.handler = handler; } public String getHandler() { return handler; } public void setNumOfRetries(int numOfRetries) { this.numOfRetries = numOfRetries; } public int getNumOfRetries() { return numOfRetries; } public void setExpectedDuration(long expectedDuration) { this.expectedDuration = expectedDuration; } public long getExpectedDuration() { return expectedDuration; } public void setRetryInterval(int retryInterval) { this.retryInterval = retryInterval; } public int getRetryInterval() { return retryInterval; } public void setErrorHandlingTask(boolean errorHandlingTask) { this.errorHandlingTask = errorHandlingTask; } public boolean isErrorHandlingTask() { return errorHandlingTask; } public void setArgs(String args) { this.args = args; } public String getArgs() { return args; } public void setExecOrder(int execOrder) { this.execOrder = execOrder; } public int getExecOrder() { return execOrder; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public boolean isDisabled() { return disabled; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public Long getJobId() { return jobId; } public void setJobId(Long cronJobId) { this.jobId = cronJobId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
package dev.fujioka.eltonleite.application.controller; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import dev.fujioka.eltonleite.domain.model.product.Product; import dev.fujioka.eltonleite.domain.service.ProductService; import dev.fujioka.eltonleite.infrastructure.service.ResponseService; import dev.fujioka.eltonleite.presentation.assembler.ProductAssembler; import dev.fujioka.eltonleite.presentation.dto.product.ProductRequestTO; import dev.fujioka.eltonleite.presentation.dto.product.ProductResponseTO; import dev.fujioka.eltonleite.presentation.dto.shared.ResponseTO; @RestController @RequestMapping("/api/products") public class ProductController { private final ProductService service; private final ResponseService responseService; public ProductController(final ProductService service, final ResponseService responseService) { this.service = service; this.responseService = responseService; } @GetMapping("/{id}") public ResponseEntity<ResponseTO<ProductResponseTO>> find(@PathVariable Long id) { return responseService.ok(ProductAssembler.from(service.findBy(id))); } @GetMapping public ResponseEntity<ResponseTO<List<ProductResponseTO>>> findAll() { return responseService.ok(ProductAssembler.from(service.findAll())); } @GetMapping(params = "manufactureYear") public ResponseEntity<ResponseTO<List<ProductResponseTO>>> findAll( @RequestParam(value = "manufactureYear") Integer manufactureYear) { return responseService.ok(ProductAssembler.from(service.findByManufactureYear(manufactureYear))); } @GetMapping(params = { "startYear", "endYear", }) public ResponseEntity<ResponseTO<List<ProductResponseTO>>> findAll( @RequestParam(value = "startYear") Integer startYear, @RequestParam(value = "endYear") Integer endYear) { return responseService.ok(ProductAssembler.from(service.findByManufactureYearBetween(startYear, endYear))); } @PostMapping public ResponseEntity<ResponseTO<ProductResponseTO>> save(@RequestBody ProductRequestTO requestTO) { Product product = ProductAssembler.from(requestTO); return responseService.ok(ProductAssembler.from(service.save(product))); } @PutMapping("/{id}") public ResponseEntity<ResponseTO<ProductResponseTO>> update(@PathVariable Long id, @RequestBody ProductRequestTO requestTO) { Product product = ProductAssembler.from(requestTO); return responseService.ok(ProductAssembler.from(service.update(id, product))); } @DeleteMapping("/{id}") @ResponseStatus(value = HttpStatus.NO_CONTENT) public void delete(@PathVariable Long id) { service.delete(id); } }
package vnfoss2010.smartshop.serverside.test; /** * @author VoMinhTam */ public class Media2 { public String name; public String link; public Media2(String name, String link) { this.name = name; this.link = link; } public static void main(String[] args) { String t = "http://127.0.0.1:8888/image_host/product/img1.jpg"; System.out.println(t); } }
package graph_package; import java.util.HashMap; import java.util.List; public class Graph_Undirected { private HashMap<Node_Graph, List<Node_Graph>> mygraph = new HashMap<>(); public void add_Node(Node_Graph a) { if(!mygraph.containsKey(a)) { this.mygraph.put(a, null); } } public void add_Neighbour(Node_Graph p, Node_Graph n) { if(!mygraph.containsKey(p)) { add_Node(p); } if(!(mygraph.get(p)).contains(n)) { this.mygraph.get(p).add(n); } if(!mygraph.containsKey(n)) { add_Node(n); } if(!(mygraph.get(n)).contains(p)) { this.mygraph.get(n).add(p); } } public void add_Neighbour_List(Node_Graph p, List<Node_Graph> list) { if(!mygraph.containsKey(p)) { add_Node(p); } for(int i=0; i<list.size(); i++) { if(!(mygraph.get(p)).contains(list.get(i))) { this.mygraph.get(p).add(list.get(i)); } if(!mygraph.containsKey(list.get(i))) { add_Node(list.get(i)); } if(!mygraph.get(list.get(i)).contains(p)) { this.mygraph.get(list.get(i)).add(p); } } } public List<Node_Graph> get_Neighbours(Node_Graph n) { if(mygraph.containsKey(n)) { return mygraph.get(n); } return null; } public void delete_Neighbour(Node_Graph p, Node_Graph n) { if(mygraph.containsKey(p)) { this.mygraph.get(p).remove(n); } if(mygraph.containsKey(n)) { this.mygraph.get(n).remove(p); } } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.testfixture.beans.factory.aot; import java.util.function.Consumer; import org.springframework.javapoet.TypeSpec; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * {@link TypeSpec.Builder} {@link Consumer} that can be used to defer the to * another consumer that is set at a later point. * * @author Phillip Webb * @since 6.0 */ public class DeferredTypeBuilder implements Consumer<TypeSpec.Builder> { @Nullable private Consumer<TypeSpec.Builder> type; @Override public void accept(TypeSpec.Builder type) { Assert.notNull(this.type, "No type builder set"); this.type.accept(type); } public void set(Consumer<TypeSpec.Builder> type) { this.type = type; } }
// No matter decode or encode, we have to consider two cases: // 1. to make the char[] short 2. to make the char[] long. // we need to handle two cases respecitively. // Usually, tackle short one is kind of easy, just using fast and slow pointer. // For the long case, we need to resize the array, and create new one , then traverse from the end of array. class Solution { public String decompress(String s) { if(s == null || s.length() <= 1) { return s; } char[] arr = s.toCharArray(); int lenshort = decodeShort(arr); return decodeLong(arr, lenshort); } private int getDigit(char chr) { return chr - '0'; } private int decodeShort(char[] arr) { int slow = 0; for(int i = 0; i < arr.length; i += 2) { int digit = getDigit(arr[i + 1]); if(digit >= 0 && digit <= 2) { for(int j = 0; j < digit; j++) { arr[slow++] = arr[i]; } }else { arr[slow++] = arr[i]; arr[slow++] = arr[i + 1]; } } return slow; } private String decodeLong(char[] arr, int len) { int newlen = len; for(int i = 0; i < len; i++) { int digit = getDigit(arr[i]); if(digit > 2 && digit <= 9) { newlen += digit - 2; } } char[] res = new char[newlen]; int slow = newlen - 1; for(int j = len - 1; j >= 0; j--) { int digit = getDigit(arr[j]); if(digit > 2 && digit <= 9) { j--; for(int k = 0; k < digit; k++) { / ## for 中condition条件句, k < X, X用定值,不要用容易改变的值,用到一半条件就跑了 res[slow--] = arr[j]; } }else { res[slow--] = arr[j]; } } return new String(res); } }
class Student { String firstName; String lastName; Address addr; Date dob; //date of birth String[] skills; Qualification[] qual; Project[] projects; String eMail; String contactNo ; int skillnum,qualnum,projectnum; Student() { firstName=null; lastName=null; addr=new Address(); dob=new Date(); skills=null; skillnum=0; qualnum=0; projectnum=0; qual=new Qualification[0]; projects =new Project[0]; eMail=null; contactNo=null; } Student(String a,String b,Address c,Date d,String[] e,int elen,Qualification[] f,int flen ,Project [] g,int glen,String h,String i ) { int k; firstName=a; lastName=b; addr=c; dob=d; skillnum=elen; qualnum=flen; projectnum=glen; String[] skills =new String[skillnum]; Qualification[] qual=new Qualfication[qualnum]; Project[] projects=new Project[projectnum]; for(k=0;k<skillnum;k++) { skills[k]=e[k]; } for(k=0;k<qualnum;k++) { qual[k]=f[k]; } for(k=0;k<projectnum;k++) { project[k]=g[k]; } eMail=h; contactNo=i; } Student(String a,String b,Address c,Date d, String[] e,int elen,Quaification []f , int flen,String i, String j) { int k; firstName=a; lastName=b; addr=c; dob=d; skillnum=elen; qualnum=flen; String [] skills =new String[elen]; Qualification[] qual=new Qualification[flen]; for(k=0;k<skillnum;k++) { skills[k]=e[k]; } for(k=0;k<qualnum;k++) { qual[k]=f[k]; } eMail=i; contactNo=j; } void display() { System.out.println("Firstname: "+firstName); System.out.println("last name:"+lastName); System.out.println("Address: "); addr.display(); System.out.println("Date of Birth: "); dob.display(); Sytem.out.println("Skills: "); if(skillnum>0) { for(int i=0;i<skillnum;i++) { System.out.println((i+1)+" "); } } if (qualnum>0) { for(int i=0;i<qualnum;i++) { System.out.println((i+1)+" "); qual[i].display(); } } if(projectnum>0) { for(int i=0;i<projectnum;i++) { System.out.println((i+1)+" "); projects[i].display(); } } System.out.println("Email ID : "+eMail); System.out.println("Contact No. : "+contactNo); } }
package springboot_hazelcast; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import springboot_hazelcast.imdgconfig.IMDGConfig; //@ComponentScan({ "springboot_hazelcast.mapstore.*", "springboot_hazelcast.controller.*", // "springboot_hazelcast.imdgconfig.*", "springboot_hazelcast.wrapper.*", "springboot_hazelcast.*" }) @EnableConfigurationProperties @SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class }) public class ApplicationStarter implements CommandLineRunner { @Autowired IMDGConfig imdgConfig; // static { // System.setProperty("spring.config.location", // "file:D://MYAPPLICATIONS//Practice_On_SpringBoot//springboot_hazelcast//src//main//resources//properties.yml"); // } public static void main(String[] args) { // SpringApplication.run(ApplicationStarter.class, args); new SpringApplicationBuilder(ApplicationStarter.class).properties("spring.config.name=application,,properties") .run(args); } @Override public void run(String... args) throws Exception { HazelcastInstance instance = imdgConfig.getInstance(); IMap<Object, Object> map = instance.getMap("Employees"); Map<String, Object> m = new HashMap<String, Object>(); m.put("eid", "124"); m.put("name", "knr"); m.put("dep", "development"); map.put("empdata", m); System.out.println(map.get("empdata")); System.out.println("successfully retrived"); // instance.shutdown(); } }
package com.test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.lenovohit.ssm.payment.support.bankPay.config.Constants; import com.lenovohit.ssm.payment.support.bankPay.model.builder.BankRefundRequestBuilder; import com.lenovohit.ssm.payment.support.bankPay.model.result.BankRefundResult; import com.lenovohit.ssm.payment.support.bankPay.service.BankTradeService; import com.lenovohit.ssm.payment.support.bankPay.service.impl.BankTradeServiceImpl; /** * Created by zyus. * 简单main函数,用于测试银行Socket 接口 */ public class BankServiceTest { private static Log log = LogFactory.getLog(BankServiceTest.class); public static void main(String[] args) { BankServiceTest main = new BankServiceTest(); // 系统商商测试交易保障接口api // main.test_monitor_sys(); // POS厂商测试交易保障接口api // main.test_monitor_pos(); // 测试交易保障接口调度 // main.test_monitor_schedule_logic(); // 测试当面付2.0支付(使用未集成交易保障接口的当面付2.0服务) // main.test_trade_pay(tradeService); // 测试查询当面付2.0交易 // main.test_trade_query(); // 测试当面付2.0退货 // main.test_trade_refund(); // 测试当面付2.0生成支付二维码 main.test_trade_refund(); } // 测试当面付2.0退款 public void test_trade_refund() { BankRefundRequestBuilder builder = new BankRefundRequestBuilder() .setLength("136").setCode(Constants.TRADE_CODE_REFUND) .setHisCode(Constants.HIS_CODE).setBankCode("1030") .setOutTradeNo("SR17040812345678") .setOutTradeDate("20170408") .setOutTradeTime("173430") .setCardBankCode("1030") .setAccount("acconut") .setAccountName("AccountName") .setAmount("12.00"); BankTradeServiceImpl.ClientBuilder clientBuilder = new BankTradeServiceImpl.ClientBuilder() .setFrontIp("127.0.0.1") .setFrontPort(2017); BankTradeService bankTradeService = new BankTradeServiceImpl.ClientBuilder().build(clientBuilder); BankRefundResult result = bankTradeService.tradeRefund(builder); System.out.println("service response" + result); switch (result.getTradeStatus()) { case SUCCESS: log.info("银行退款成功,退款流水号: "); break; case REFUNDING: log.info("银行退款处理中,退款流水号: "); break; case FAILED: log.error("银行退款失败!!!"); break; case UNKNOWN: log.error("系统异常,银行退款状态未知!!!"); break; } } }
import java.util.*; public class Disarium { public static void main() { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); sc.close(); int s=0; int c=n; String ns=""+n; int f=ns.length(); while(n!=0) { s=s+(int)(Math.pow((n%10),f--)); n/=10; } if(s==c) System.out.println("Yes it is Disarium Number"); else System.out.println("Not a Disarium Number"); } }
package com.lenovohit.hcp.material.manager.print.impl; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.hcp.base.dto.PrintData; import com.lenovohit.hcp.base.manager.impl.AbstractPrintDataManagerImpl; import com.lenovohit.hcp.base.model.HcpUser; import com.lenovohit.hcp.material.model.MatBuyDetail; //采购单打印-物资 @Service("matAuitdPrintDataManager") public class MatAuitdPrintDataManager extends AbstractPrintDataManagerImpl { @Autowired private GenericManager<MatBuyDetail, String> matBuyDetailManager; @Override public PrintData getPrintData(String bizId, HcpUser user) { String hql = "select a from MatBuyDetail a left join a.matInfo b where a.buyBill=?"; // String hql = "select a from MatBuyDetail a left join a.MatInfo where a.buyBill=?"; // select regFree from RegFree regFree regFree.itemInfo itemInfo where 1=1 String sql = "" +" select " +" com.COMPANY_NAME a0," +" dept.DEPT_NAME a1," +" CONVERT(varchar(12),buy.CREATE_TIME,111 ) a2," +" CONVERT(varchar(12),buy.AUITD_TIME,111 ) a3," +" buy.CREATE_OPER a4," +" buy.AUITD_OPER a5," +" sum(detail.AUITD_NUM*detail.BUY_PRICE) a6," +" sum(detail.BUY_NUM*detail.BUY_PRICE) a7" +" from MATERIAL_BUYBILL buy JOIN MATERIAL_BUYDETAIL detail on buy.ID=detail.BILL_ID left join b_deptinfo dept on buy.DEPT_ID=dept.ID left join B_COMPANY com on buy.COMPANY=com.ID " +" where buy.BUY_BILL='"+bizId+"'" +" group by" +" com.COMPANY_NAME," +" dept.DEPT_NAME," +" buy.CREATE_TIME," +" buy.AUITD_TIME," +" buy.CREATE_OPER," +" buy.AUITD_OPER"; List<Object> values = new ArrayList<Object>(); values.add(bizId); PrintData data = new PrintData(); double _AUITD_NUM = 0; if (!"undefined".equals(bizId) && bizId != null) { List<Object> objList = (List<Object>) matBuyDetailManager.findBySql(sql); String _COMPANY_NAME = "", _DEPT_NAME = "", _CREATE_TIME = "", _AUITD_TIME = "", CREATE_OPER = "", AUITD_OPER = ""; BigDecimal _sum1 =new BigDecimal(0), _sum2 = new BigDecimal(0); if (objList != null && objList.size() > 0) { Object[] obj = (Object[]) objList.get(0); _COMPANY_NAME = PrintUtil.getNotNull((String)obj[0]);//公司名称 _DEPT_NAME = PrintUtil.getNotNull((String)obj[1]);//部门名称 if(obj[2]!=null){ _CREATE_TIME = PrintUtil.getNotNull(obj[2].toString()); } if(obj[3]!=null){ _AUITD_TIME = PrintUtil.getNotNull(obj[3].toString()); } if(obj[4]!=null){ CREATE_OPER = PrintUtil.getNotNull(obj[4].toString()); } if(obj[5]!=null){ AUITD_OPER = PrintUtil.getNotNull(obj[5].toString()); } if(obj[6]!=null){ _sum1 =(BigDecimal)obj[6];//申请金额 } if(obj[7]!=null){ _sum2 =(BigDecimal)obj[7];//审批金额 } } DecimalFormat myformat=new DecimalFormat("0.00"); String _outHtml = "<style> table,td,th {border: 0px solid black;border-style: solid;border-collapse: collapse}</style>" + "<table border=\"0\" width=\"100%\">" + "<tr>" + " <th>审批单号:</th>" + " <td>" + bizId + "</td>" + " <th>供应商:</th>" + " <td>" + _COMPANY_NAME + "</td>" + " <th>采购科室:</th>" + " <td>" + _DEPT_NAME + "</td>" + " <th>审批金额:</th>" + " <td>" + PrintUtil.getAmount(_sum2) + "</td>"; _outHtml += "<tr>" + " <th>申请人:</th>" + " <td>" + CREATE_OPER + "</td>" + " <th>申请时间:</th>" + " <td>" + _CREATE_TIME + "</td>" + " <th>审批人:</th>" + " <td>" + AUITD_OPER + "</td>" + " <th>审批时间:</th>" + " <td>" + _AUITD_TIME + "</td></tr>" + "</table>"; data.setT1(_outHtml); List<MatBuyDetail> _list = matBuyDetailManager.find(hql, values); if (_list != null) { _outHtml = "<style> table,td,th {border: 1px solid black;border-style: solid;border-collapse: collapse}</style>" + "<table border=\"1\" width=\"100%\">" + "<tr>" + " <th>药品名称</th>" + " <th>规格</th>" + " <th>单位</th>" + "<th>生产厂家</th>" + " <th>计划数量</th>" + " <th>审批数量</th><th>采购价</th>" + " <th>金额</th>" + "</tr>\n"; BigDecimal _sum =new BigDecimal(0); for (MatBuyDetail _detail : _list) { BigDecimal _count=new BigDecimal(0); if (_detail.getBuyCost() != null) { _count = _detail.getBuyPrice().multiply(new BigDecimal(_detail.getBuyNum())); _sum =_sum.add(_count); } String companyName = ""; if(_detail.getMatInfo().getCompanyInfo()!=null){ companyName = PrintUtil.getNotNull(_detail.getMatInfo().getCompanyInfo().getCompanyName()); } _outHtml += "<tr>" + " <td>" + _detail.getTradeName() + "</td>" + " <td>" + PrintUtil.getNotNull(_detail.getMaterialSpec()) + "</td>" + " <td>" + PrintUtil.getNotNull(_detail.getMinUnit()) + "</td>" + " <td>" + companyName + "</td>" + " <td>" + _detail.getBuyNum() + "</td>" + " <td>" + _detail.getAuitdNum() + "</td>" + " <td>" + PrintUtil.getAmount(_detail.getBuyPrice()) + "</td><td>" + myformat.format(_count) + "</td>" + "</tr>\n"; } _outHtml += "<tr>" + " <th colspan=2>合计</th>" + " <td></td>" + " <td></td>" + " <td></td>" + " <td></td>" + " <td></td>" + " <td>" +PrintUtil.getAmount(_sum) + "</td>" + "</tr>\n"; _outHtml += "</table>"; data.setT2(_outHtml); } } return data; } }
/* * @lc app=leetcode.cn id=33 lang=java * * [33] 搜索旋转排序数组 */ // @lc code=start class Solution { public int search(int[] nums, int target) { int len =nums.length; if(len == 0) return -1; int rotate_index = searchRotatePoint(nums,0,len-1); if(rotate_index == 0) return BinarySearch(nums,0,len - 1,target); if(nums[0] <= target) return BinarySearch(nums,0, rotate_index-1,target); else return BinarySearch(nums,rotate_index, len -1,target); } public int searchRotatePoint(int[] nums, int left, int right) { if(left > right) return -1; if (nums[left] <= nums[right]) return 0; while (left < right) { int medium = (left + right) / 2; if ((left + 1) == right) { return nums[left] > nums[right] ? right : left; } if (nums[medium] < nums[left]) { right = medium; } else if (nums[medium] > nums[left]) left = medium; } return - 1; } public int BinarySearch(int[] nums,int left,int right,int target){ while(left <= right){ int medium = (left + right) / 2; if(left == right && nums[medium] != target) return -1; if(nums[medium] == target) return medium; else if(nums[medium] < target) left = medium + 1; else if(nums[medium] > target) right = medium; } return -1; } } // @lc code=end
package com.gsn.utils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * 使用基于Log4j的Logger记录不同级别的log信息 * * @author GSN */ public class LogUtils { private static final Logger logger = LogManager.getLogger(); private LogUtils() {} public static void debug(String message) { log(Level.DEBUG, message); } public static void debug(String message, Throwable e) { log(Level.DEBUG, message, e); } public static void info(String message) { log(Level.INFO, message); } public static void info(String message, Throwable e) { log(Level.INFO, message, e); } public static void warn(String message) { log(Level.WARN, message); } public static void warn(String message, Throwable e) { log(Level.WARN, message, e); } public static void error(String message) { log(Level.ERROR, message); } public static void error(String message, Throwable e) { log(Level.ERROR, message, e); } private static void log(Level level, String message) { logger.log(level, message); } private static void log(Level level, String message, Throwable e) { logger.log(level, message, e); } }
package ydtak.grapeguice.juice; public interface Juice { String get(); }
/* * 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 go; /** * * @author NguyenQuoc */ class ExceptionNoPierreExist extends Exception { public ExceptionNoPierreExist() { } }
package com.funnums.funnums.classes; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Bitmap; import com.funnums.funnums.maingame.GameActivity; import java.util.Random; /** * Created by Rabia on 11/02/19. */ public class Cloud { public float x, y; private static final int VEL_X = -1; private static Random r = new Random(); public int maxYSpawn; public int minYSpawn; public int size; private Bitmap image; public Cloud(float x, float y, String imageName) { this.x = x; this.y = y; this.image = com.funnums.funnums.maingame.GameView.loadBitmap(imageName, false); } public void update() { //float delta = deltaTime*1.0f / com.funnums.funnums.maingame.GameView.NANOS_TO_SECONDS; x += VEL_X; //* delta; if (x <= -image.getWidth()) { // wrap x so that cloud respawns on right side of the screen x += GameActivity.screenX + image.getWidth(); } } public void draw(Canvas canvas, Paint paint){ canvas.drawBitmap(image, x, y, paint); } public int getWidth(){ return image.getWidth(); } }
package com.example.praty.githubrepo.helper; import android.view.View; //interface for the click listener of an item in the recyclerview public interface ItemClickListener { void onItemClick(View v, int position); }
package com.nick.java.handler; import com.nick.java.File; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class FileHandler implements ActionListener { File f; public FileHandler(File f) { this.f = f; } public void actionPerformed(ActionEvent ae) { Object o = ae.getSource(); if (o==f.t9) { System.exit(0); } } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.appcloud.integration.test.utils.clients; //import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.CharEncoding; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import org.wso2.appcloud.integration.test.utils.AppCloudIntegrationTestConstants; import org.wso2.appcloud.integration.test.utils.AppCloudIntegrationTestException; import org.wso2.appcloud.integration.test.utils.AppCloudIntegrationTestUtils; import org.wso2.carbon.automation.engine.context.AutomationContext; import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class BaseClient { private static final Log log = LogFactory.getLog(BaseClient.class); protected static final String HEADER_SET_COOKIE = "Set-Cookie"; protected static final String HEADER_COOKIE = "Cookie"; protected static final String HEADER_CONTENT_TYPE = "Content-Type"; protected static final String MEDIA_TYPE_X_WWW_FORM = "application/x-www-form-urlencoded"; protected static final String PARAM_NAME_ACTION = "action"; protected static final String ACTION_NAME_LOGIN = "login"; protected static final String PARAM_EQUALIZER = "="; protected static final String PARAM_SEPARATOR = "&"; protected static final String PARAM_NAME_USER_NAME = "userName"; protected static final String PARAM_NAME_PASSWORD = "password"; private String backEndUrl; private Map<String, String> requestHeaders = new HashMap<String, String>(); private static AutomationContext context; static { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); } protected String getBackEndUrl() { return backEndUrl; } protected void setBackEndUrl(String backEndUrl) { this.backEndUrl = backEndUrl; } protected Map<String, String> getRequestHeaders() { return requestHeaders; } protected void setHTTPHeader(String headerName, String value) { requestHeaders.put(headerName, value); } protected String getHTTPHeader(String headerName) { return requestHeaders.get(headerName); } protected void removeHTTPHeader(String headerName) { requestHeaders.remove(headerName); } /** * Get session. * * @param responseHeaders response headers * @return session */ protected String getSession(Map<String, String> responseHeaders) { return responseHeaders.get(HEADER_SET_COOKIE); } /** * Set session. * * @param session session */ protected void setSession(String session) { requestHeaders.put(HEADER_COOKIE, session); } /** * Construct authenticates REST client to invoke appmgt functions. * * @param backEndUrl backend url * @param username username * @param password password * @throws Exception */ public BaseClient(String backEndUrl, String username, String password) throws Exception { setBackEndUrl(backEndUrl); if (getRequestHeaders().get(HEADER_CONTENT_TYPE) == null) { getRequestHeaders().put(HEADER_CONTENT_TYPE, MEDIA_TYPE_X_WWW_FORM); } login(username, password); } protected void checkErrors(HttpResponse response) throws AppCloudIntegrationTestException { JSONObject jsonObject = new JSONObject(response.getData()); if (jsonObject.keySet().contains("error")) { log.error("Response received as: " + response.getData()); throw new AppCloudIntegrationTestException("Operation not successful: " + jsonObject.get(AppCloudIntegrationTestConstants.RESPONSE_MESSAGE_NAME).toString()); } } /** * login to app mgt. * * @param userName username * @param password password * @throws Exception */ protected void login(String userName, String password) throws Exception { HttpResponse response = HttpRequestUtil.doPost( new URL(getBackEndUrl() + AppCloudIntegrationTestConstants.APPMGT_URL_SURFIX + AppCloudIntegrationTestConstants.APPMGT_USER_LOGIN), PARAM_NAME_ACTION + PARAM_EQUALIZER + ACTION_NAME_LOGIN + PARAM_SEPARATOR + PARAM_NAME_USER_NAME + PARAM_EQUALIZER + userName + PARAM_SEPARATOR + PARAM_NAME_PASSWORD + PARAM_EQUALIZER + password, getRequestHeaders()); if (response.getResponseCode() == HttpStatus.SC_OK) { JSONObject jsonObject = new JSONObject(response.getData()); if (jsonObject.get("error").equals("false")) { String session = getSession(response.getHeaders()); if (session == null) { throw new AppCloudIntegrationTestException("No session cookie found with response"); } setSession(session); } else { throw new AppCloudIntegrationTestException("Login failed " + response.getData()); } } else { throw new AppCloudIntegrationTestException("Login failed " + response.getData()); } } /** * Do post request to appfactory. * * @param urlSuffix url suffix from the block layer * @param keyVal post body * @return httpResponse */ public HttpResponse doPostRequest(String urlSuffix, Map<String, String> keyVal) throws AppCloudIntegrationTestException { String postBody = generateMsgBody(keyVal); try { return HttpRequestUtil.doPost(new URL(getBackEndUrl() + AppCloudIntegrationTestConstants.APPMGT_URL_SURFIX + urlSuffix), postBody, getRequestHeaders()); } catch (Exception e) { final String msg = "Error occurred while doing a post :"; log.error(msg, e); throw new AppCloudIntegrationTestException(msg, e); } } /** * Returns a String that is suitable for use as an application/x-www-form-urlencoded list of parameters in an HTTP PUT or HTTP POST. * * @param keyVal parameter map * @return message body */ public String generateMsgBody(Map<String, String> keyVal) { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> keyValEntry : keyVal.entrySet()) { qparams.add(new BasicNameValuePair(keyValEntry.getKey(), keyValEntry.getValue())); } return URLEncodedUtils.format(qparams, CharEncoding.UTF_8); } public HttpResponse doPostRequest(String endpoint, List<NameValuePair> nameValuePairs) throws AppCloudIntegrationTestException { HttpClient httpclient = null; int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod(); try { httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) .build(); HttpPost httppost = new HttpPost(endpoint); httppost.setConfig(requestConfig); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE)); org.apache.http.HttpResponse httpResponse = (httpclient.execute(httppost)); return new HttpResponse(EntityUtils.toString(httpResponse.getEntity(),"UTF-8").replaceAll("\\s+", ""), httpResponse.getStatusLine().getStatusCode()); }catch (ConnectTimeoutException | java.net.SocketTimeoutException e1){ // In most of the cases, even though connection is timed out, actual activity is completed. log.warn("Failed to get 200 ok response from endpoint:"+endpoint, e1); return new HttpResponse(e1.getMessage(), HttpStatus.SC_REQUEST_TIMEOUT); } catch(IOException e) { log.error("Failed to invoke API endpoint:" + endpoint, e); throw new AppCloudIntegrationTestException("Failed to invoke API endpoint:" + endpoint, e); } finally { HttpClientUtils.closeQuietly(httpclient); } } public HttpResponse doGetRequest(String endpoint, Header[] headers) throws AppCloudIntegrationTestException { HttpClient httpclient = null; int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod(); try { httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) .build(); HttpGet httpGet = new HttpGet(endpoint); httpGet.setConfig(requestConfig); httpGet.setHeaders(headers); httpGet.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE)); org.apache.http.HttpResponse httpResponse = (httpclient.execute(httpGet)); return new HttpResponse(EntityUtils.toString(httpResponse.getEntity()), httpResponse.getStatusLine().getStatusCode()); } catch (IOException e) { log.error("Failed to invoke API endpoint:" + endpoint, e); throw new AppCloudIntegrationTestException("Failed to invoke API endpoint:" + endpoint, e); } finally { HttpClientUtils.closeQuietly(httpclient); } } }
package com.penglai.haima.callback; import android.app.Activity; import com.lzy.okgo.model.Response; import com.lzy.okgo.request.base.Request; import com.penglai.haima.base.BaseActivity; /** * 描 述:对于网络请求是否需要弹出加载框 */ public abstract class DialogCallback<T> extends JsonCallback<T> { public DialogCallback(Activity activity) { super(activity); } public DialogCallback(Activity mActivity, boolean showStatue) { super(mActivity, showStatue); } @Override public void onStart(Request<T, ? extends Request> request) { super.onStart(request); if (mActivity != null) { ((BaseActivity) mActivity).getDialog().show(); } //网络请求前显示对话框 } @Override public void onError(Response<T> response) { super.onError(response); if (mActivity != null) { ((BaseActivity) mActivity).getDialog().dismiss();//请求框架可能出现 OnError回调后,OnFinish 不回调情况,这边补充关闭 dialog. } } @Override public void onFinish() { super.onFinish(); //网络请求结束后关闭对话框 if (mActivity != null) { ((BaseActivity) mActivity).getDialog().dismiss(); } } }
package com.shilong.jysgl.service; import java.util.List; import com.shilong.jysgl.pojo.po.Dictinfo; import com.shilong.jysgl.pojo.po.Dicttype; public interface DictInfoService { public void insertDictInfo(String dictInfo,String typecode) throws Exception;//添加字典名称 public void updateDictInfo(String dictcode,String dictInfo) throws Exception;//修改字典名称 public List<Dictinfo> findDictInfoList(String typeCode) throws Exception;//字典名称列表 public List<Dicttype> findDictTypeList() throws Exception;//字典类型列表 public Dictinfo getDictInfoById(String dictcode) throws Exception;//根据字典代码查询字典名称 public void deleteDictInfoById(String dictcode) throws Exception;//根据字典代码删除字典名称 }
/** */ package Metamodell.model.metamodell.impl; import Metamodell.model.metamodell.Hardware; import Metamodell.model.metamodell.MetamodellPackage; import Metamodell.model.metamodell.Software; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>System</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link Metamodell.model.metamodell.impl.SystemImpl#getSystem_hw <em>System hw</em>}</li> * <li>{@link Metamodell.model.metamodell.impl.SystemImpl#getSystem_sw <em>System sw</em>}</li> * </ul> * </p> * * @generated */ public class SystemImpl extends EObjectImpl implements Metamodell.model.metamodell.System { /** * The cached value of the '{@link #getSystem_hw() <em>System hw</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSystem_hw() * @generated * @ordered */ protected Hardware system_hw; /** * The cached value of the '{@link #getSystem_sw() <em>System sw</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSystem_sw() * @generated * @ordered */ protected Software system_sw; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SystemImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EClass eStaticClass() { return MetamodellPackage.Literals.SYSTEM; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Hardware getSystem_hw() { return system_hw; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSystem_hw(Hardware newSystem_hw, NotificationChain msgs) { Hardware oldSystem_hw = system_hw; system_hw = newSystem_hw; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MetamodellPackage.SYSTEM__SYSTEM_HW, oldSystem_hw, newSystem_hw); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSystem_hw(Hardware newSystem_hw) { if (newSystem_hw != system_hw) { NotificationChain msgs = null; if (system_hw != null) msgs = ((InternalEObject)system_hw).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MetamodellPackage.SYSTEM__SYSTEM_HW, null, msgs); if (newSystem_hw != null) msgs = ((InternalEObject)newSystem_hw).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MetamodellPackage.SYSTEM__SYSTEM_HW, null, msgs); msgs = basicSetSystem_hw(newSystem_hw, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MetamodellPackage.SYSTEM__SYSTEM_HW, newSystem_hw, newSystem_hw)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Software getSystem_sw() { return system_sw; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSystem_sw(Software newSystem_sw, NotificationChain msgs) { Software oldSystem_sw = system_sw; system_sw = newSystem_sw; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MetamodellPackage.SYSTEM__SYSTEM_SW, oldSystem_sw, newSystem_sw); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSystem_sw(Software newSystem_sw) { if (newSystem_sw != system_sw) { NotificationChain msgs = null; if (system_sw != null) msgs = ((InternalEObject)system_sw).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MetamodellPackage.SYSTEM__SYSTEM_SW, null, msgs); if (newSystem_sw != null) msgs = ((InternalEObject)newSystem_sw).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MetamodellPackage.SYSTEM__SYSTEM_SW, null, msgs); msgs = basicSetSystem_sw(newSystem_sw, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MetamodellPackage.SYSTEM__SYSTEM_SW, newSystem_sw, newSystem_sw)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MetamodellPackage.SYSTEM__SYSTEM_HW: return basicSetSystem_hw(null, msgs); case MetamodellPackage.SYSTEM__SYSTEM_SW: return basicSetSystem_sw(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MetamodellPackage.SYSTEM__SYSTEM_HW: return getSystem_hw(); case MetamodellPackage.SYSTEM__SYSTEM_SW: return getSystem_sw(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void eSet(int featureID, Object newValue) { switch (featureID) { case MetamodellPackage.SYSTEM__SYSTEM_HW: setSystem_hw((Hardware)newValue); return; case MetamodellPackage.SYSTEM__SYSTEM_SW: setSystem_sw((Software)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void eUnset(int featureID) { switch (featureID) { case MetamodellPackage.SYSTEM__SYSTEM_HW: setSystem_hw((Hardware)null); return; case MetamodellPackage.SYSTEM__SYSTEM_SW: setSystem_sw((Software)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean eIsSet(int featureID) { switch (featureID) { case MetamodellPackage.SYSTEM__SYSTEM_HW: return system_hw != null; case MetamodellPackage.SYSTEM__SYSTEM_SW: return system_sw != null; } return super.eIsSet(featureID); } } //SystemImpl
package by.bytechs.xfs; import at.o2xfs.xfs.pin.WFSPINSTATUS; import at.o2xfs.xfs.ptr.PaperStatus; import at.o2xfs.xfs.service.ServiceNotFoundException; import at.o2xfs.xfs.service.XfsServiceManager; import at.o2xfs.xfs.service.cdm.CdmService; import at.o2xfs.xfs.service.cdm.xfs3.CdmStatusCommand; import at.o2xfs.xfs.service.idc.IDCService; import at.o2xfs.xfs.service.idc.cmd.IDCStatusCommand; import at.o2xfs.xfs.service.pin.PINService; import at.o2xfs.xfs.service.pin.cmd.PINStatusCommand; import at.o2xfs.xfs.service.ptr.PTRService; import at.o2xfs.xfs.service.ptr.PTRStatusCallable; import at.o2xfs.xfs.service.siu.SIUService; import at.o2xfs.xfs.service.siu.SIUStatusCallable; import at.o2xfs.xfs.siu.SIUStatus; import at.o2xfs.xfs.siu.SIUUPSState; import at.o2xfs.xfs.v3_00.cdm.CdmStatus3; import at.o2xfs.xfs.v3_00.cdm.OutputPosition3; import at.o2xfs.xfs.v3_00.idc.Status3; import at.o2xfs.xfs.v3_00.ptr.PtrStatus3; import by.bytechs.xfs.deviceStatus.cdmStatus.*; import by.bytechs.xfs.deviceStatus.idcStatus.*; import by.bytechs.xfs.deviceStatus.pinStatus.PINDevicePositionStatus; import by.bytechs.xfs.deviceStatus.pinStatus.PINDeviceStatus; import by.bytechs.xfs.deviceStatus.pinStatus.PINEncryptStatus; import by.bytechs.xfs.deviceStatus.ptrStatus.*; import by.bytechs.xfs.deviceStatus.siuStatus.*; import by.bytechs.xfs.interfaces.XfsDeviceStatusService; import by.bytechs.xml.entity.CommandResultXml; import by.bytechs.xml.entity.deviceStatus.ComponentXml; import by.bytechs.xml.entity.deviceStatus.MonitoringXml; import by.bytechs.xml.entity.deviceStatus.ResultXml; import by.bytechs.xml.interfaces.XmlBindingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.xml.bind.JAXBException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.TreeSet; ; /** * @author Romanovich Andrei */ @Service public class XfsDeviceStatusServiceImpl extends XfsCommandService implements XfsDeviceStatusService { @Autowired private XfsServiceManager xfsServiceManager; @Autowired private XmlBindingService xmlBindingService; @Override public MonitoringXml getObjectDeviceStatus(String terminalId, int requestId) { List<CommandResultXml> commandResultXmlList = new ArrayList<>(); commandResultXmlList.add(getIDCStatus(requestId)); commandResultXmlList.add(getPINStatus(requestId)); commandResultXmlList.add(getPTRStatus(requestId)); commandResultXmlList.add(getCDMStatus(requestId)); commandResultXmlList.add(getSIUStatus(requestId)); ResultXml resultXml = new ResultXml(OK_CODE, RESULT_DESCRIPTION, SOURCE, OK_STATUS); return new MonitoringXml(terminalId, resultXml, commandResultXmlList); } @Override public String getXmlDeviceStatus(String terminalId, int requestId) { try { MonitoringXml monitoringXml = getObjectDeviceStatus(terminalId, requestId); return xmlBindingService.xmlMarshaller(MonitoringXml.class, monitoringXml); } catch (JAXBException e) { e.printStackTrace(); return null; } } @Override public CommandResultXml getIDCStatus(int requestId) { try { IDCService xfsService = xfsServiceManager.getService(IDCService.class); IDCStatusCommand idcStatusCommand = new IDCStatusCommand(xfsService); Status3 idcStatus = idcStatusCommand.call(); CommandResultXml commandResultXml = getCommandResultStatus("IDC", requestId, COMMAND_DEVICE_STATUS_DESCRIPTION); commandResultXml.getStatusElm().getComponentElmList().add(IDCDeviceStatus.getDescription(idcStatus.getDeviceState())); commandResultXml.getStatusElm().getComponentElmList().add(IDCMediaStatus.getDescription(idcStatus.getMedia())); commandResultXml.getStatusElm().getComponentElmList().add(IDCRetainBinStatus.getDescription(idcStatus.getRetainBin())); commandResultXml.getStatusElm().getComponentElmList().add(IDCSecurityStatus.getDescription(idcStatus.getSecurity())); commandResultXml.getStatusElm().getComponentElmList().add(new ComponentXml(idcStatus.getCards(), RETAIN_CARDS, "retaincards")); commandResultXml.getStatusElm().getComponentElmList().add(IDCChipPowerStatus.getDescription(idcStatus.getChipPower())); return commandResultXml; } catch (ServiceNotFoundException e) { return getUnknownDevice("IDC", requestId); } catch (Exception e) { e.printStackTrace(); return null; } } @Override public CommandResultXml getPINStatus(int requestId) { try { PINService pinService = xfsServiceManager.getService(PINService.class); PINStatusCommand pinStatusCommand = new PINStatusCommand(pinService); WFSPINSTATUS pinStatus = pinStatusCommand.call(); CommandResultXml commandResultXml = getCommandResultStatus("PIN", requestId, COMMAND_DEVICE_STATUS_DESCRIPTION); commandResultXml.getStatusElm().getComponentElmList().add(PINDeviceStatus.getDescription(pinStatus.getDevice())); commandResultXml.getStatusElm().getComponentElmList().add(PINEncryptStatus.getDescription(pinStatus.getEncStat())); commandResultXml.getStatusElm().getComponentElmList().add(PINDevicePositionStatus.getDescription(pinStatus.getDevicePosition())); return commandResultXml; } catch (ServiceNotFoundException e) { return getUnknownDevice("PIN", requestId); } catch (Exception e) { e.printStackTrace(); return null; } } @Override public CommandResultXml getPTRStatus(int requestId) { try { PTRService prrService = xfsServiceManager.getService(PTRService.class); PTRStatusCallable ptrStatusCallable = new PTRStatusCallable(prrService); PtrStatus3 prrStatus = ptrStatusCallable.call(); CommandResultXml commandResultXml = getCommandResultStatus("PTR", requestId, COMMAND_DEVICE_STATUS_DESCRIPTION); commandResultXml.getStatusElm().getComponentElmList().add(PTRDeviceStatus.getDescription(prrStatus.getDevice())); commandResultXml.getStatusElm().getComponentElmList().add(PTRMediaStatus.getDescription(prrStatus.getMedia())); for (PaperStatus paperStatus : new TreeSet<>(Arrays.asList(prrStatus.getPaper()))) { commandResultXml.getStatusElm().getComponentElmList().add(PTRPaperStatus.getDescription(paperStatus)); } commandResultXml.getStatusElm().getComponentElmList().add(PTRTonnerStatus.getDescription(prrStatus.getToner())); commandResultXml.getStatusElm().getComponentElmList().add(PTRInkStatus.getDescription(prrStatus.getInk())); commandResultXml.getStatusElm().getComponentElmList().add(PTRLampStatus.getDescription(prrStatus.getLamp())); return commandResultXml; } catch (ServiceNotFoundException e) { return getUnknownDevice("PTR", requestId); } catch (Exception e) { e.printStackTrace(); return null; } } @Override public CommandResultXml getCDMStatus(int requestId) { try { CdmService cdmService = xfsServiceManager.getService(CdmService.class); CdmStatusCommand cdmStatusCommand = new CdmStatusCommand(cdmService); CdmStatus3 cdmStatus = cdmStatusCommand.call(); CommandResultXml commandResultXml = getCommandResultStatus("CDM", requestId, COMMAND_DEVICE_STATUS_DESCRIPTION); commandResultXml.getStatusElm().getComponentElmList().add(CDMDeviceStatus.getDescription(cdmStatus.getDeviceState())); commandResultXml.getStatusElm().getComponentElmList().add(CDMSafeDoorStatus.getDescription(cdmStatus.getSafeDoor())); commandResultXml.getStatusElm().getComponentElmList().add(CDMDispenserStatus.getDescription(cdmStatus.getDispenser())); commandResultXml.getStatusElm().getComponentElmList().add(CDMStackerStatus.getDescription(cdmStatus.getIntermediateStacker())); for (OutputPosition3 outputPosition : cdmStatus.getPositions()) { commandResultXml.getStatusElm().getComponentElmList().add(CDMPositionStatus.getDescription(outputPosition.getPosition())); commandResultXml.getStatusElm().getComponentElmList().add(CDMShutterStatus.getDescription(outputPosition.getShutter())); commandResultXml.getStatusElm().getComponentElmList().add(CDMPositionStatusState.getDescription(outputPosition.getPositionStatus())); commandResultXml.getStatusElm().getComponentElmList().add(CDMTransportStatus.getDescription(outputPosition.getTransport())); commandResultXml.getStatusElm().getComponentElmList().add(CDMTransportStatusState.getDescription(outputPosition.getTransportStatus())); } return commandResultXml; } catch (ServiceNotFoundException e) { return getUnknownDevice("CDM", requestId); } catch (Exception e) { e.printStackTrace(); return null; } } @Override public CommandResultXml getSIUStatus(int requestId) { try { SIUService siuService = xfsServiceManager.getService(SIUService.class); SIUStatusCallable siuStatusCallable = new SIUStatusCallable(siuService); SIUStatus siuStatus = siuStatusCallable.call(); CommandResultXml commandResultXml = getCommandResultStatus("SIU", requestId, COMMAND_DEVICE_STATUS_DESCRIPTION); commandResultXml.getStatusElm().getComponentElmList().add(SIUDeviceStatus.getDescription(siuStatus.getDevice())); commandResultXml.getStatusElm().getComponentElmList().add(SIUCabinetDoorStatus.getDescription(siuStatus.getDoorStatus().getCabinetDoorsState())); commandResultXml.getStatusElm().getComponentElmList().add(SIUSafeDoorStatus.getDescription(siuStatus.getDoorStatus().getSafeDoorsState())); commandResultXml.getStatusElm().getComponentElmList().add(SIUVandalShieldStatus.getDescription(siuStatus.getDoorStatus().getVandalShieldState())); for (SIUUPSState siuupsState : siuStatus.getAuxiliaryStatus().getUPSStates()) { commandResultXml.getStatusElm().getComponentElmList().add(SIUUpsStatus.getDescription(siuupsState)); } return commandResultXml; } catch (ServiceNotFoundException e) { return getUnknownDevice("SIU", requestId); } catch (Exception e) { e.printStackTrace(); return null; } } }
package com.webcheckers.ui.login; import com.webcheckers.appl.Constants; import com.webcheckers.appl.GameCenter; import com.webcheckers.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; import spark.ModelAndView; import spark.Request; import spark.Response; import spark.Session; import java.util.Map; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LoginControllerTest { // attributes holding mock objects private Request request; private Session session; private Response response; private LoginController CuT = new LoginController(new GameCenter()); @Before public void setUp() throws Exception { request = mock(Request.class); session = mock(Session.class); when(request.session()).thenReturn(session); response = mock(Response.class); } @Test public void has_no_user() { request.attribute(Constants.SESSION_USER,new User(Constants.SESSION_USER)); final ModelAndView result = CuT.handle(request, response); // Analyze the results: // * result is non-null assertNotNull(result); // * model is a non-null Map final Object model = result.getModel(); assertNotNull(model); assertTrue(model instanceof Map); // * model contains all necessary View-Model data final Map<String, Object> vm = (Map<String, Object>) model; assertEquals(Constants.DEFAULT_LOGIN_VM.get(Constants.TITLE_ATTR),vm.get(Constants.TITLE_ATTR)); } }
/* * 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 app.action; import app.model.Comment; import app.model.Project; import app.model.User; import com.opensymphony.xwork2.ActionSupport; import core.DB; import core.LoginManager; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Result; /** * * @author bruceoutdoors */ @Result(name = "redirect", location = "${url}", type = "redirect") public class CommentAction extends ActionSupport { public String id; public String url; public User user = LoginManager.getCurrentUser(); public String create() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); String projectId = request.getParameter("project.projectId"); Comment c = new Comment(); c.setCommentDescription(request.getParameter("comment.commentDescription")); c.setProjectId((Project) DB.getInstance() .createNamedQuery("Project.findByProjectId") .setParameter("projectId", Integer.parseInt(projectId)) .getSingleResult()); c.setUserId(user); DB.getInstance().persist(c); url = "/viewboard/" + projectId; return "redirect"; } }
package com.gsccs.sme.plat.svg.service; import java.util.List; import com.gsccs.sme.api.domain.StatistGroup; import com.gsccs.sme.plat.svg.model.SclassT; public interface SclassService { public void insert(SclassT sclassT); public void update(SclassT sclassT); public void delSclass(Long id); public SclassT findById(Long id); public List<SclassT> find(SclassT sclassT,String orderstr, int page, int pagesize); public List<SclassT> find(SclassT sclassT); public List<SclassT> findSubList(Long parid); public int count(SclassT sclassT); public List<SclassT> findByParids(String string); public List<StatistGroup> statistAppealTopicNum(); }
package com.aof.webapp.action.prm; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.hibernate.HibernateException; import net.sf.hibernate.Transaction; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.util.MessageResources; import org.apache.struts.validator.DynaValidatorForm; import com.aof.component.domain.party.Party; import com.aof.component.domain.party.UserLogin; import com.aof.core.persistence.Persistencer; import com.aof.core.persistence.hibernate.Hibernate2Session; import com.aof.core.persistence.jdbc.SQLExecutor; import com.aof.core.persistence.jdbc.SQLResults; import com.aof.core.persistence.util.EntityUtil; import com.aof.util.Constants; import com.aof.util.UtilDateTime; import com.aof.webapp.action.BaseAction; public class ProjectChooseDialogueAction extends BaseAction { public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // Extract attributes we will need Logger log = Logger.getLogger(PRMProjectListAction.class.getName()); Locale locale = getLocale(request); MessageResources messages = getResources(); String action = request.getParameter("FormAction"); DynaValidatorForm actionForm = (DynaValidatorForm) form; HttpSession session = request.getSession(); List projectSelectArr = new ArrayList(); List result = new ArrayList(); String UserId = request.getParameter("UserId"); String DataPeriod = request.getParameter("DataPeriod"); String nowTimestampString = UtilDateTime.nowTimestamp().toString(); String DateStart = ""; if (UserId == null) UserId = ""; if (DataPeriod == null) { DateStart = nowTimestampString; } else { DateStart = DataPeriod + " 00:00:00.000"; } try { net.sf.hibernate.Session hs = Hibernate2Session.currentSession(); Transaction tx = null; String lStrOpt = request.getParameter("rad"); String srchproj = request.getParameter("srchproj"); String dep_name = request.getParameter("dep_name"); String bid_id = request.getParameter("bid"); String bid_name = request.getParameter("bname"); String bid_no = request.getParameter("bno"); if (lStrOpt == null) lStrOpt = "2"; if (srchproj == null) srchproj = ""; if(dep_name==null) dep_name = ""; String QryStr = ""; if (!srchproj.equals("")) { if (lStrOpt.equals("2")) { // QryStr = QryStr + " and (p.projId like '%" + srchproj // + "%' or p.projName like '%" + srchproj + "%')"; QryStr = QryStr + " and (pm.proj_Id like '%" + srchproj + "%' or pm.proj_name like '%" + srchproj + "%'" + " or cust.description like '%"+ srchproj +"'" + ")"; } else { // QryStr = QryStr + " and (p.projId = '" + srchproj // + "' or p.projName = '" + srchproj + "')"; QryStr = QryStr + " and (pm.proj_Id = '" + srchproj + "' or pm.proj_name ='" + srchproj + "')" + " "; } } if(!dep_name.equalsIgnoreCase("")) { if (lStrOpt.equals("2")) { QryStr = QryStr + " and dpt.description like '%"+ dep_name.trim() +"%'"; } else { QryStr = QryStr + " and dpt.description = '"+dep_name.trim()+"'"; } } if((bid_id!=null)&&(!bid_id.equalsIgnoreCase(""))) QryStr += " and cp.cp_bid_id="+bid_id; UserLogin userLogin = (UserLogin) request.getSession().getAttribute(Constants.USERLOGIN_KEY); request.setAttribute("result", initSelect(userLogin.getUserLoginId(), DateStart, QryStr,bid_id)); request.setAttribute("bid",bid_id); request.setAttribute("bname",bid_name); request.setAttribute("bno",bid_no); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); return (mapping.findForward("success")); } finally { try { Hibernate2Session.closeSession(); } catch (HibernateException e1) { log.error(e1.getMessage()); e1.printStackTrace(); } catch (SQLException e1) { log.error(e1.getMessage()); e1.printStackTrace(); } } return (mapping.findForward("success")); } private SQLResults initSelect(String UserId, String DateStart, String AddCondition,String bid_id) { try { SQLExecutor sqlExec = new SQLExecutor(Persistencer .getSQLExecutorConnection(EntityUtil .getConnectionByName("jdbc/aofdb"))); String SqlStr; SqlStr = "select cust.party_id as cust_id,cust.description as description," + "pm.proj_id,pm.proj_name,pm.dep_id,dpt.description as dep_name from proj_mstr as pm "+ " inner join party as cust on pm.cust_id = cust.party_Id"+ " inner join party as dpt on pm.dep_id = dpt.party_Id"; if((bid_id!=null)&&(!bid_id.equalsIgnoreCase(""))) SqlStr+=" inner join contract_profile as cp on pm.proj_contract_no = cp.cp_no "; UserLogin ul = (UserLogin)Hibernate2Session.currentSession().load(UserLogin.class, UserId); if(ul.getParty().getPartyId().equals("014")){ SqlStr+=" where proj_category = 'c' and pm.dep_id in ('014','005','006','007') "; }else{ SqlStr+=" where proj_category = 'c' and pm.dep_id in ('"+ul.getParty().getPartyId()+"') "; } /* SqlStr = " select cust.party_id as cust_id,cust.description as description,pm.proj_id as projid ,pm.proj_name as projname,pm.dep_id,dpt.description as dep_name from proj_mstr as pm inner join party as cust" + " on pm.cust_id = cust.party_Id inner join party as dpt on pm.dep_id = dpt.party_id inner join contract_profile as cp on pm.proj_contract_no = cp.cp_no " + " where pm.proj_category = 'c' and proj_status <> 'close'"; */ if (!AddCondition.trim().equals("")) SqlStr = SqlStr + AddCondition; SqlStr = SqlStr + " and pm.proj_id not in (select distinct(proj_id) from proj_plan_bom_mstr where proj_id is not null)"+ " order by cust.description asc"; System.out.println(SqlStr); SQLResults sr = sqlExec.runQueryCloseCon(SqlStr); return sr; } catch (Exception e) { e.printStackTrace(); return null; } } }
package es.upm.grise.profundizacion2019.ex3; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Time { // El formato del tiempo y fecha es constante private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); // La instancia usada para calcular la diferencia de tiempo private LocalDateTime time; // Un constructor que inyecta la dependencia public Time(final LocalDateTime time) { this.time = time; } // Un constructor vacío utiliza el tiempo actual por defecto public Time() { this(LocalDateTime.now()); } // Un método que computa un tiempo futuro // PD: Teoricamente la clase LocalDateTime es inmutable, por lo que he // asumo que hay que asignar el objeto retornado por "plusSeconds" public String getFutureTime(final long seconds) { final LocalDateTime future = time.plusSeconds(seconds); return formatter.format(future); } }
package advert; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 服务器端,实现基于UDP的用户登录 Created by Jim Calark on 2017/3/19. */ public class UDPServer { private static final Logger logger = LoggerFactory.getLogger(UDPServer.class); public static void main(String[] args) throws SocketException, IOException { // 1、创建服务器端DatagramSocket,指定端口 DatagramSocket datagramSocket = new DatagramSocket(8999); // datagramSocket.setReceiveBufferSize(32*1024); // 2、创建数据报,用于接受客户端发送的数据 byte[] data = new byte[8192];// 创建字节数组,指定接受的数据报的大小 DatagramPacket datagramPacket = new DatagramPacket(data, data.length); // 3、接收客户端发送的数据 System.out.println("服务器已经开启,等待客户端的连接"); int i = 0; while(true) { // 此方法在接收到数据之前会一直阻塞 datagramSocket.receive(datagramPacket); // 4、读取客户端发送的数据 // 参数: data 要转换的数组 0 从数组的下标0 开始 datagramPacket.getLength() 长度为接收到的长度 String info = new String(data, 0, datagramPacket.getLength()); i++; logger.info(i+" ========" + info); } /** * 向客户端进行响应 *//* // 1、定义客户端的地址、端口号、数据 // 获取客户端 ip地址 InetAddress inetAddress = datagramPacket.getAddress(); // 获取客户端端口号 int port = datagramPacket.getPort(); // 将要响应的内容保存到byte数组中 byte[] data2 = "欢迎您!".getBytes(); // 2创建数据报,包含响应的数据信息 DatagramPacket datagramPacket12 = new DatagramPacket(data2, data2.length, inetAddress, port); // 3、响应客户端 datagramSocket.send(datagramPacket12); // 4、关闭资源 datagramSocket.close();*/ } }
package org.jmmo.tuple; import org.jmmo.function.Consumer5; import org.jmmo.function.Function5; import java.util.Comparator; import java.util.Iterator; import java.util.Objects; public class Tuple5<T0, T1, T2, T3, T4> implements Tuple, Comparable<Tuple5<T0, T1, T2, T3, T4>> { private static final long serialVersionUID = 8215132094283212974L; private final T0 value0; private final T1 value1; private final T2 value2; private final T3 value3; private final T4 value4; protected Tuple5(T0 value0, T1 value1, T2 value2, T3 value3, T4 value4) { this.value0 = value0; this.value1 = value1; this.value2 = value2; this.value3 = value3; this.value4 = value4; } public static <V0, V1, V2, V3, V4> Tuple5<V0, V1, V2, V3, V4> of(V0 v0, V1 v1, V2 v2, V3 v3, V4 v4) { return new Tuple5<>(v0, v1, v2, v3, v4); } @SuppressWarnings("unchecked") public static <A, V0 extends A, V1 extends A, V2 extends A, V3 extends A, V4 extends A> Tuple5<V0, V1, V2, V3, V4> fromArray(A[] values) { return new Tuple5<>((V0) values[0], (V1) values[1], (V2) values[2], (V3) values[3], (V4) values[4]); } @SuppressWarnings("unchecked") public static <A, V0 extends A, V1 extends A, V2 extends A, V3 extends A, V4 extends A> Tuple5<V0, V1, V2, V3, V4> fromIterator(Iterator<A> iterator) { return new Tuple5<>((V0) iterator.next(), (V1) iterator.next(), (V2) iterator.next(), (V3) iterator.next(), (V4) iterator.next()); } public void unfold(Consumer5<T0, T1, T2, T3, T4> valueConsumer) { valueConsumer.accept(getValue0(), getValue1(), getValue2(), getValue3(), getValue4()); } public <R> R unfoldResult(Function5<T0, T1, T2, T3, T4, R> valueFunction) { return valueFunction.apply(getValue0(), getValue1(), getValue2(), getValue3(), getValue4()); } public T0 getValue0() { return value0; } public T1 getValue1() { return value1; } public T2 getValue2() { return value2; } public T3 getValue3() { return value3; } public T4 getValue4() { return value4; } @Override public int getSize() { return 5; } @SuppressWarnings("unchecked") @Override public <E> E get(int i) { switch (i) { case 0: return (E) getValue0(); case 1: return (E) getValue1(); case 2: return (E) getValue2(); case 3: return (E) getValue3(); case 4: return (E) getValue4(); } throw new IndexOutOfBoundsException("Tuple5 contains five elements but " + i + " element requested"); } @Override public Object[] toArray() { return new Object[] { getValue0(), getValue1(), getValue2(), getValue3(), getValue4() }; } @SuppressWarnings("unchecked") private static final Comparator<Tuple5> comparator = Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue0(), Tuple1.nullComparator) .thenComparing( Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue1(), Tuple1.nullComparator)) .thenComparing( Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue2(), Tuple1.nullComparator)) .thenComparing( Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue3(), Tuple1.nullComparator)) .thenComparing( Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue4(), Tuple1.nullComparator)); @SuppressWarnings("unchecked") @Override public int compareTo(Tuple5<T0, T1, T2, T3, T4> o) { return comparator.compare(this, o); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Tuple5)) return false; Tuple5<?, ?, ?, ?, ?> tuple5 = (Tuple5<?, ?, ?, ?, ?>) o; return Objects.deepEquals(getValue0(), tuple5.getValue0()) && Objects.deepEquals(getValue1(), tuple5.getValue1()) && Objects.deepEquals(getValue2(), tuple5.getValue2()) && Objects.deepEquals(getValue3(), tuple5.getValue3()) && Objects.deepEquals(getValue4(), tuple5.getValue4()); } @Override public int hashCode() { return Tuple.hashCode(this); } @Override public String toString() { return Tuple.toString(this); } }
package com.git.cloud.handler.automation.se.db; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.git.cloud.foundation.common.WebApplicationManager; import com.git.cloud.handler.automation.LinkRouteType; import com.git.cloud.handler.automation.RemoteAbstractAutomationHandler; import com.git.cloud.handler.automation.se.common.StorageConstants; import com.git.cloud.handler.automation.se.common.StorageDBRACEnum; import com.git.cloud.handler.automation.se.dao.StorageDAO; import com.git.cloud.handler.automation.se.vo.StorageMgrVo; import com.git.cloud.handler.service.AutomationService; import com.git.cloud.handler.service.StorageService; import com.git.cloud.resmgt.network.model.vo.DeviceNetIP; import com.git.cloud.resmgt.network.model.vo.NetIPInfo; import com.git.support.common.MesgFlds; import com.git.support.common.MesgRetCode; import com.git.support.common.PMFlds.NwAddrType; import com.git.support.common.SEOpration; import com.git.support.sdo.impl.BodyDO; import com.git.support.sdo.impl.DataObject; import com.git.support.sdo.impl.HeaderDO; import com.git.support.sdo.inf.IDataObject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class ConfigNASHeartBeatVolumeHandler extends RemoteAbstractAutomationHandler { private static Logger log = LoggerFactory .getLogger(ConfigNASHeartBeatVolumeHandler.class); private List<String> deviceIdList = Lists.newArrayList(); private String deviceId; public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public List<String> getDeviceIdList() { return deviceIdList; } public void setDeviceIdList(List<String> deviceIdList) { this.deviceIdList = deviceIdList; } private List<Map<String,Object>> list = Lists.newArrayList(); private StringBuffer rtn_sb = new StringBuffer(); // private IIpAllocToVMService ipAllocToVMService = (IIpAllocToVMService) FrameworkContext.getApplicationContext().getBean( // "IpToVMPowervmRacServiceImpl"); private StorageDAO storageDao = (StorageDAO) WebApplicationManager.getBean("storageDAO"); private StorageService storageService = (StorageService)WebApplicationManager.getBean("storageService"); // 生产地址的数量 private static final int PRODUCT_IP_COUNT = 3; @SuppressWarnings("unchecked") @Override protected IDataObject buildRequestData(Map<String, Object> contenxtParmas) throws Exception { // TODO Auto-generated method stub AutomationService automationService = (AutomationService) WebApplicationManager.getBean("automationServiceImpl"); IDataObject reqData = DataObject.CreateDataObject(); HeaderDO header = HeaderDO.CreateHeaderDO(); String rrinfoId = (String) contenxtParmas.get(RRINFO_ID); try { // 增加数据中心路由标识 String queueIdentify = this.getQueueIdent(rrinfoId); header.set(LinkRouteType.DATACENTER_QUEUE_IDEN.getValue(), queueIdentify); } catch (Exception e) { throw new Exception("get LinkRouteType error!", e); } header.setResourceClass("SE"); header.setResourceType(StorageConstants.RESOURCE_TYPE_STORAGE_NETAPP); header.setOperation(SEOpration.CONF_VOLUME); reqData.setDataObject(MesgFlds.HEADER, header); BodyDO body = BodyDO.CreateBodyDO(); String deviceId = getDeviceId(); Map<String, Object> deviceParams = (Map<String, Object>) contenxtParmas .get(String.valueOf(deviceId)); String finished = (String)deviceParams.get(StorageConstants.CREATE_HEARTBEAT_VOL_FINISHED); if(StringUtils.isBlank(finished)){ throw new Exception("未完成RAC-NAS-HEARTBEAT创建!"); } String config_finished = (String)deviceParams.get(StorageConstants.CONFIG_RAC_HEARTBEAT_VOL_FINISHED); if(StringUtils.isNotBlank(config_finished)){ throw new Exception("已完成RAC-NAS-HEARTBEAT配置!"); } // 获取数据中心 String dcenter_ename = (String) deviceParams .get(StorageConstants.DATACENTER_ENAME); body.setString(StorageConstants.DATACENTER_ENAME, dcenter_ename); // STORAGE_MODEL_NETAPP_FAS String storage_model = (String)deviceParams.get(StorageConstants.RAC_NAS_MODEL); body.setString("NAS_MODEL", storage_model); //DATA_TYPE = NASHeartbeat String heartbeat_name = (String)deviceParams.get(StorageDBRACEnum.NAS_HEARTBEAT_NAME.name()); body.setString("DATA_TYPE", heartbeat_name); //RAC_NAS_SN String nas_sn =(String)deviceParams.get(StorageConstants.RAC_NAS_SN); body.setString("NAS_SN", nas_sn); rtn_sb.append("NAS SN:"+nas_sn).append("\n"); //根据NAS设备sn号获取登陆名密码 log.info("nas_sn:"+nas_sn); log.info("nwaddr_type_code:NM"); log.info("vm_ms_type_code:4"); //根据NAS设备sn号获取登陆名密码 // Map<String,String> mgr_info = service.getNASMgrLoginInfo(nas_sn, // StorageConstants.IP_ADDR_TYPE_CODE_NM, // StorageConstants.IP_STORAGE_TYPE); String storageId = storageDao.findStorageDevBySn(nas_sn).getId(); Map<String,String> mgr_info = Maps.newHashMap(); if(storageId!=null){ mgr_info.put("deviceId", storageId); } StorageMgrVo mgrVo = storageDao.findStorageMgrInfoByParam(mgr_info); if(mgr_info==null||mgr_info.isEmpty()){ throw new Exception("获取存储sn:["+nas_sn+"] 管理机登陆信息失败!"); } body.setString(StorageConstants.SERVICE_IP, mgrVo.getManagerIp()); body.setString(StorageConstants.USERNAME, mgrVo.getUserName()); body.setString(StorageConstants.USERPASSWD, mgrVo.getPassword()); // Map<String,Object> vol_info = getHeartBeatVolInfo(deviceParams); // List<Map<String,Object>> vol_info_list = Lists.newArrayList(); // vol_info_list.add(vol_info); // list.addAll(vol_info_list); //List<Map<String,String>> deviceIpList = getDeviceProductIP(contenxtParmas,"P"); Map<String,String> snapshot = getSnapshot_info(); list = getConfigVolInfo(deviceParams, snapshot,contenxtParmas); body.setList("VOL_INFO", list); log.debug(JSONObject.toJSONString(body)); reqData.setDataObject(MesgFlds.BODY, body); return reqData; } @SuppressWarnings("unchecked") public List<Map<String,String>> getDeviceProductIP(Map<String, Object> contenxtParmas,String pm_type) throws Exception{ List<Map<String,String>> list = Lists.newArrayList(); List<String> ip_list = Lists.newArrayList(); for(String deviceId:deviceIdList){ Map<String,Object> devInfo = (Map<String,Object>)contenxtParmas.get(String.valueOf(deviceId)); String dev_type = (String)devInfo.get("DEV_TYPE"); String os_name = (String)devInfo.get("OS_NAME"); if(os_name.contains(StorageConstants.OS_NAME_HP_UX)){ os_name = StorageConstants.OS_NAME_HP_UX; }else if(os_name.equalsIgnoreCase(StorageConstants.OS_NAME_LINUX)){ os_name = StorageConstants.OS_NAME_LINUX; } List<String> host_ip_list = storageService.getDeviceIPs(deviceId); if(null==host_ip_list|| host_ip_list.size()==0){ throw new Exception("deviceId:["+deviceId+"] "+os_name+","+dev_type+","+pm_type+" 获取IP地址信息失败!"); } ip_list.addAll(host_ip_list); } for(String ip:ip_list){ Map<String,String> host_map = Maps.newHashMap(); host_map.put("HOST_IP", ip); list.add(host_map); } return list; } // public List<Map<String, String>> getDeviceProductIPByContextParmas( // Map<String, Object> contenxtParmas, String pm_type) { // List<Map<String,String>> list = Lists.newArrayList(); // List<String> ip_list = Lists.newArrayList(); // try { // List<DeviceNetIP> deviceNetIps = ipAllocToVMService.qryAllocedIP(deviceIdList); // for(DeviceNetIP deviceNetIP :deviceNetIps){ // List<NetIPInfo> vmIPs = deviceNetIP.getNetIPs().get(NwAddrType.VM_PROD.getValue()); // if (vmIPs != null && vmIPs.size() == PRODUCT_IP_COUNT) { // for (NetIPInfo netIp: vmIPs) { // ip_list.add(netIp.getIp()); // } // } else { // throw new Exception("vioc生产ip为空或生产ip数量 != 3。"); // } // } // } catch (Exception e) { // // TODO Auto-generated catch block // throw new Exception(e); // } // // for(String ip:ip_list){ // Map<String,String> host_map = Maps.newHashMap(); // host_map.put("HOST_IP", ip); // list.add(host_map); // } // return list; // } public Map<String,String> getSnapshot_info(){ Map<String,String> map = Maps.newHashMap(); map.put("SNAPSHOT_RESERVE_PERCENT", "0"); map.put("SNAPSHOT_SCHEDULE_WEEKS", "0"); map.put("SNAPSHOT_SCHEDULE_DAYS", "0"); map.put("SNAPSHOT_SCHEDULE_HOURS", "0"); return map; } public List<Map<String, Object>> getExportfs_info(String vol_name, List<String> qtree_name_list,Map<String, Object> contenxtParmas,String cloud_service_type) throws Exception { List<Map<String, Object>> list = Lists.newArrayList(); for (String qtree_name : qtree_name_list) { Map<String, Object> map = Maps.newHashMap(); map.put("PERSISTENT_FLAG", Boolean.TRUE); map.put("PATH_NAME", "/" + vol_name + "/" + qtree_name); // List<Map<String,String>> root_hosts =Lists.newArrayList(); // if(cloud_service_type.equals(StorageConstants.CLOUD_SERVICE_TYPE_STORAGE_INSTALL)){ // root_hosts = getDeviceProductIP(contenxtParmas, "P"); // }else if(cloud_service_type.equals(StorageConstants.CLOUD_SERVICE_TYPE_VM_INSTALL)){ // root_hosts = this.getDeviceProductIPByContextParmas(contenxtParmas, "P"); // } // map.put("ROOT_HOSTS", root_hosts); // List<Map<String,String>> rw_hosts = Lists.newArrayList(); // if(cloud_service_type.equals(StorageConstants.CLOUD_SERVICE_TYPE_STORAGE_INSTALL)){ // rw_hosts = getDeviceProductIP(contenxtParmas, "P"); // }else if(cloud_service_type.equals(StorageConstants.CLOUD_SERVICE_TYPE_VM_INSTALL)){ // rw_hosts = this.getDeviceProductIPByContextParmas(contenxtParmas, "P"); // } // getDeviceProductIP(contenxtParmas, "P"); // map.put("RW_HOSTS", rw_hosts); List<Map<String,String>> root_hosts =getDeviceProductIP(contenxtParmas, "P"); map.put("ROOT_HOSTS", root_hosts); List<Map<String,String>> rw_hosts = getDeviceProductIP(contenxtParmas, "P"); map.put("RW_HOSTS", rw_hosts); list.add(map); rtn_sb.append("PERSISTENT_FLAG:"+Boolean.TRUE).append("\n"); rtn_sb.append("PATH_NAME:"+ "/"+vol_name+"/"+qtree_name).append("\n"); rtn_sb.append("RW_HOSTS:"+ rw_hosts).append("\n"); rtn_sb.append("ROOT_HOSTS:"+ root_hosts).append("\n"); } return list; } @SuppressWarnings({ "unchecked", "rawtypes" }) public List<Map<String,Object>> getConfigVolInfo(Map<String, Object> deviceParams,Map<String,String> snapshot,Map<String,Object> contenxtParmas) throws Exception{ String create_vol_info_str = (String)deviceParams.get(StorageConstants.CREATE_HEARTBEAT_VOL_INFO); if(StringUtils.isBlank(create_vol_info_str)){ throw new Exception("获取创建的vol信息错误!"); } log.debug("CREATE_HEARTBEAT_VOL_INFO:"+create_vol_info_str); String cloud_service_type = (String)deviceParams.get(StorageConstants.CLOUD_SERVICE_TYPE); if(StringUtils.isBlank(cloud_service_type)){ throw new Exception("获取[CLOUD_SERVICE_TYPE]参数错误!"); } List<Map<String,Object>> rtn_list = Lists.newArrayList(); List<Map> l = JSONObject.parseArray(create_vol_info_str, Map.class); for(Map m : l){ Map<String,Object> map = Maps.newHashMap(); //添加vol_name String vol_name = String.valueOf(m.get("VOL_NAME")); map.put("VOL_NAME", vol_name); rtn_sb.append("VOL_NAME:"+vol_name).append("\n"); //添加快照信息 map.put("SNAPSHOT_INFO", snapshot); rtn_sb.append("SNAPSHOT_INFO:").append("\n"); for(String key:snapshot.keySet()){ rtn_sb.append(key+":"+snapshot.get(key)); } //添加主机mount到qtree的主机ip地址信息 List<Map<String,String>> qtree_map_list = (List<Map<String,String>>)m.get("QTREES"); List<String> qtree_name_list = Lists.newArrayList(); for(Map<String,String> qtree_map : qtree_map_list){ qtree_name_list.add(qtree_map.get("QTREE_NAME")); rtn_sb.append("QTREE_NAME:"+qtree_map.get("QTREE_NAME")); } List<Map<String, Object>> exports_info= getExportfs_info(vol_name,qtree_name_list,contenxtParmas,cloud_service_type); map.put("EXPORTFS_INFO", exports_info); rtn_list.add(map); } return rtn_list; } // public Map<String,Object> getHeartBeatVolInfo(Map<String,Object> deviceParams){ // Map<String,Object> vol_info = Maps.newHashMap(); // //获取应用名称 // String app_name = (String)deviceParams.get(StorageConstants.PROJECTABBR); // //获取主机挂载点 // String mountpoint = (String)deviceParams.get(StorageConstants.NAS_HEARTBEAT_MOUNTPOINT); // // //组装vol-name // String[] point_array = mountpoint.split("/"); // String last_point = point_array[point_array.length-1]; // String vol_name = app_name+"_"+last_point; // vol_info.put("VOL_NAME", vol_name); // // //卷大小 // String vol_size = (String)deviceParams.get("NAS_HEARTBEAT_CAPACITY"); // vol_info.put("VOL_SIZE", vol_size); // // //pool_name // String vol_pool_str = (String)deviceParams.get(StorageConstants.RAC_NAS_VOL_POOL); // JSONObject vol_pool_map = JSONObject.parseObject(vol_pool_str); // String pool_name = String.valueOf(vol_pool_map.get(vol_name)); // if(StringUtils.isBlank(pool_name)){ // throw new Exception("获取VOL_NAME:"+vol_name+"所在POOL信息失败!"); // } // vol_info.put("POOL_NAME", pool_name); // // //qtree info // String qtree_name = last_point; // String qtree_mode = StorageConstants.QTREE_MODE; // Map<String,String> qtree_info_map = Maps.newHashMap(); // qtree_info_map.put("QTREE_NAME", qtree_name); // qtree_info_map.put("QTREE_MODE", qtree_mode); // List<Map<String,String>> qtree_info_list = Lists.newArrayList(); // qtree_info_list.add(qtree_info_map); // // vol_info.put("QTREES", qtree_info_list); // return vol_info; // } @Override protected void handleResonpse(Map<String, Object> contenxtParmas, IDataObject responseDataObject) throws Exception { HeaderDO header = responseDataObject.getDataObject(MesgFlds.HEADER, HeaderDO.class); log.info(header.getRetMesg()); if (!MesgRetCode.SUCCESS.equalsIgnoreCase(header.getRetCode())) { String errorMsg = header.getRetMesg(); throw new Exception(errorMsg); } Calendar c = Calendar.getInstance(); Date d = c.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String exportfs_time = sdf.format(d); for (int i = 0; i < deviceIdList.size(); i++) { String deviceId = String.valueOf(deviceIdList.get(i)); setHandleResultParam(deviceId, StorageConstants.CONFIG_HEARTBEAT_VOL_INFO, JSONObject.toJSONString(list)); setHandleResultParam(deviceId, StorageConstants.EXPORTFS_TIME,exportfs_time); setHandleResultParam(deviceId, StorageConstants.CONFIG_RAC_HEARTBEAT_VOL_FINISHED,"FINISHED"); } } public String execute(HashMap<String, Object> contenxtParmas) { Map<String, Object> rtn_map = Maps.newHashMap(); if(contenxtParmas!=null){ String flowInstId = (String) contenxtParmas.get(FLOW_INST_ID); String nodeId = (String) contenxtParmas.get(NODE_ID); String rrinfoId = (String) contenxtParmas.get(RRINFO_ID); long startTime = System.currentTimeMillis(); log.debug("执行自动化操作开始,流程实例ID:{},节点ID:{}", flowInstId, nodeId); try { Map<String, Map<String, String>> handleParams = this .getHandleParams(flowInstId); contenxtParmas.putAll(handleParams); Map<String, Object> extHandleParams = getExtHandleParams(contenxtParmas); if (extHandleParams != null) contenxtParmas.putAll(extHandleParams); deviceIdList = getDeviceIdList("","",rrinfoId,""); this.setDeviceId(deviceIdList.get(0)); IDataObject responseDataObject = null; IDataObject requestDataObject = buildRequestData(contenxtParmas); responseDataObject = getResAdpterInvoker().invoke( requestDataObject, getTimeOut()); handleResonpse(contenxtParmas, responseDataObject); saveParamInsts(flowInstId, nodeId); } catch (Exception e) { String errorMsg = "执行自动化操作失败,流程实例ID:" + flowInstId + ",节点ID:" + nodeId + ".错误信息:" + e.getMessage(); log.error(errorMsg, e); rtn_map.put("checkCode", MesgRetCode.ERR_PROCESS_FAILED); rtn_map.put("exeMsg", e.getMessage()); return JSON.toJSONString(rtn_map); } finally { if (contenxtParmas != null) contenxtParmas.clear(); } log.debug("执行自动化操作结束,流程实例ID:{},节点ID:{},耗时:{}毫秒。", new Object[] { flowInstId, nodeId, new Long((System.currentTimeMillis() - startTime)) }); rtn_map.put("checkCode", MesgRetCode.SUCCESS); rtn_map.put("exeMsg", rtn_sb.toString()); }else{ rtn_map.put("checkCode", MesgRetCode.ERR_PARAMETER_WRONG); rtn_map.put("exeMsg", "ERR_PARAMETER_WRONG;contextParams is null"); } return JSON.toJSONString(rtn_map); } }
package com.invitae.emr.services; import com.invitae.emr.models.LabOrder; import com.invitae.emr.models.Practice; import com.invitae.emr.models.Requisition; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Provides services for processing lab orders. */ public class OrderProcessing { /** * List of test panel codes we offer at our lab */ private static final Set<String> testCatalog = Set.of( "PR60515", "PR60662", "PR61987", "PR72558", "PR74556", "PR81780", "PR82363"); /** * Practices we accept orders from */ private static final Set<Practice> practices = new HashSet<>(); /** * Add practices to the practice list * * @param newPractices The practices to add */ public static void addPractices(List<Practice> newPractices) { practices.addAll(newPractices); } /** * Process a list of orders * * @param orders The orders to process * @return List of requisitions */ public static List<Requisition> processOrders(List<LabOrder> orders) { return new ArrayList<>(); } }
package msip.go.kr.hr.scheduler; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import egovframework.com.cmm.EgovMessageSource; @Controller public class HRController { @Resource(name = "hrScheduling") private HRScheduling hrScheduling; @Resource(name="egovMessageSource") EgovMessageSource egovMessageSource; private static final Logger LOGGER = LoggerFactory.getLogger(HRController.class); /** * 조직/인사 정보 배치 실행 * @param entity * @param model * @return * @throws Exception */ @RequestMapping(value = "/hr/start", method = RequestMethod.GET) @ResponseBody public String regist(ModelMap model) throws Exception { String message = egovMessageSource.getMessage("success.common.insert"); try { hrScheduling.hrExcuter(); message = egovMessageSource.getMessage("success.common.insert"); } catch(Exception e) { LOGGER.error("Request /hr/start exception : ", e.getCause(), e); message = egovMessageSource.getMessage("fail.common.insert"); } return message; } }
package edu.duke.ra.core.result; import java.util.List; import org.json.JSONObject; import edu.duke.ra.core.RAException; public class ErrorResult extends QueryResult { private String query; private List<RAException> errors; public ErrorResult(String query, List<RAException> errors) { this.query = query; this.errors = errors; makeResult(); } @Override protected String makeQuery() { return query; } @Override protected JSONObject makeData() { return new JSONObject(); } @Override protected List<RAException> makeErrors() { return errors; } @Override protected boolean makeQuit() { return false; } }
package cn.test.demo01; import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { ArrayList<Integer> array = new ArrayList<Integer>(); array.add(22); array.add(11); array.add(34); for (int i = 0 ;i<array.size();i++) { System.out.println(array.get(i)); } ArrayList<Person> arr = new ArrayList<Person>(); Person p = new Person("zhangs","44"); arr.add(0,p); arr.add(new Person("lil","22")); arr.add(new Person("liwl","12")); arr.add(new Person("lwril","23")); /* for(int j = 0 ; j<arr.size();j++) { System.out.println(arr.get(j)); } */ System.out.println("======================================"); arr.add(p); for(int m = 0 ; m<arr.size();m++) { System.out.println(arr.get(m)); } } }
package com.koma.component_base.widget; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutCompat; import android.util.AttributeSet; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.LinearLayout; import android.widget.ProgressBar; import com.koma.component_base.R; import org.jetbrains.annotations.NotNull; /** * @author Koma * @date 2018/8/10 下午 04:20 * @des */ public class ProgressBarWebView extends WebView { private ProgressBar progressBar; public ProgressBarWebView(Context context, AttributeSet attrs) { super(context, attrs); progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 8); progressBar.setLayoutParams(params); Drawable drawable = context.getResources().getDrawable(R.drawable.progress_bar); //ContextCompat.getDrawable(context,R.drawable.progress_bar); progressBar.setProgressDrawable(drawable); addView(progressBar); setWebChromeClient(new WebChromeClient()); } private class WebChromeClient extends android.webkit.WebChromeClient { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { progressBar.setVisibility(GONE); } else { if (progressBar.getVisibility() == GONE) { progressBar.setVisibility(VISIBLE); } progressBar.setProgress(newProgress); } super.onProgressChanged(view, newProgress); } } @Override protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { LayoutParams params = (LayoutParams) progressBar.getLayoutParams(); params.x = scrollX; params.y = scrollY; progressBar.setLayoutParams(params); super.onOverScrolled(scrollX, scrollY, clampedX, clampedY); } }
/** * */ /** * @author kahina * */ package fr.imie.ProjetPlateformeWeb.entity;
package com.brainacademy.strategy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public abstract class ValidationContext { private List<Validator> validators; private List<String> errors; public ValidationContext() { validators = new ArrayList<>(); errors = new ArrayList<>(); } public boolean validate() { for (Validator validator : validators) { boolean valid = validator.isValid(); if (! valid) { errors.add("Validation failed " + validator.getClass().getSimpleName()); return false; } } return true; } public List<String> getErrors() { return errors; } public void addValidators(Validator... validator) { validators.addAll(Arrays.asList(validator)); } }
/* * A simple blackjack app. Goal is to get a higher score than the dealer, without going over 21. * Ties go to dealer. Dealer always hits on a score of less than 17, stands otherwise. * Natural blackjack (ace + face card) beats any other 21. Five card charlie beats any score. * Double down on score of 9, 10, or 11 to take 1 more card and double bet. * Surrender ends the game and gives up half your bet if things look hopeless. * Shoe mode allows duplicate cards to show up. * */ package com.jalmond.blackjack; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.Random; public class MainActivity extends AppCompatActivity { private int playerCash; private int playerBet; private boolean playing, playerStands, dealerStands, shoeMode; TextView totalCashTextView, playerBetTextView, playerScoreTextView, dealerScoreTextView, winnerTextView; Button betPlus10Button, betPlus100Button, shoeModeButton, hitButton, standButton, newGameButton, doubleDownButton, surrenderButton; ImageView playerCard1, playerCard2, playerCard3, playerCard4, playerCard5; ImageView dealerCard1, dealerCard2, dealerCard3, dealerCard4, dealerCard5; ImageView playerCardImages[] = {playerCard1, playerCard2, playerCard3, playerCard4, playerCard5}; ImageView dealerCardImages[] = {dealerCard1, dealerCard2, dealerCard3, dealerCard4, dealerCard5}; //"hand" object consists of 5 "card' objects, score, ace count hand playerCards; hand dealerCards; @Override protected void onCreate(Bundle savedInstanceState) { //on initialization of app super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); playing = false; //certain actions only available when "playing" is active shoeMode = true; //shoe mode allows for repeat cards. See method "repeatCard" for details playerStands = false; dealerStands = false; playerCash = 1000; //default starting cash playerBet = 100; //minimum bet totalCashTextView = (TextView) findViewById(R.id.totalCashText); playerBetTextView = (TextView) findViewById(R.id.currentBetText); playerScoreTextView = (TextView) findViewById(R.id.playerScoreText); dealerScoreTextView = (TextView) findViewById(R.id.dealerScoreText); winnerTextView = (TextView) findViewById(R.id.winnerTextView); betPlus10Button = (Button) findViewById(R.id.betPlus10Button); betPlus100Button = (Button) findViewById(R.id.betPlus100Button); shoeModeButton = (Button) findViewById(R.id.shoeModeButton); hitButton = (Button) findViewById(R.id.hitButton); standButton = (Button) findViewById(R.id.standButton); newGameButton = (Button) findViewById(R.id.newGameButton); doubleDownButton = (Button) findViewById(R.id.doubleDownButton); surrenderButton = (Button) findViewById(R.id.surrenderButton); //this could have been done in XML, initial tutorial was based on older android version setButtonOnClickListeners(); playerCardImages[0] = (ImageView) findViewById(R.id.imagePlayerCard1); playerCardImages[1] = (ImageView) findViewById(R.id.imagePlayerCard2); playerCardImages[2] = (ImageView) findViewById(R.id.imagePlayerCard3); playerCardImages[3] = (ImageView) findViewById(R.id.imagePlayerCard4); playerCardImages[4] = (ImageView) findViewById(R.id.imagePlayerCard5); dealerCardImages[0] = (ImageView) findViewById(R.id.imageDealerCard1); dealerCardImages[1] = (ImageView) findViewById(R.id.imageDealerCard2); dealerCardImages[2] = (ImageView) findViewById(R.id.imageDealerCard3); dealerCardImages[3] = (ImageView) findViewById(R.id.imageDealerCard4); dealerCardImages[4] = (ImageView) findViewById(R.id.imageDealerCard5); //player total cash and current bet totalCashTextView.setText(getResources().getString(R.string.total_cash) + " " + playerCash); playerBetTextView.setText(getResources().getString(R.string.current_bet) + " " + playerBet); newGameButton.setVisibility(View.VISIBLE); } private void newGame() { //on new game selected playing = true; playerStands = false; dealerStands = false; //playerBet = 100; //reset to minimum bet playerCards = new hand(); dealerCards = new hand(); winnerTextView.setVisibility(View.INVISIBLE); //hide winner message newGameButton.setVisibility(View.INVISIBLE); //hide New Game button dealerScoreTextView.setVisibility(View.INVISIBLE); //hide dealer score until game over betPlus10Button.setVisibility(View.INVISIBLE); //bet & shoe mode buttons cannot be used during play betPlus100Button.setVisibility(View.INVISIBLE); shoeModeButton.setVisibility(View.INVISIBLE); hitButton.setVisibility(View.VISIBLE); //hit, stand, double down, surrender unavailable outside play standButton.setVisibility(View.VISIBLE); doubleDownButton.setVisibility(View.VISIBLE); surrenderButton.setVisibility(View.VISIBLE); for (ImageView playerCardImage : playerCardImages) { //set all player cards blank playerCardImage.setImageResource(R.drawable.blank); playerCardImage.setVisibility(View.INVISIBLE); } for (ImageView dealerCardImage : dealerCardImages) { //set all dealer cards blank dealerCardImage.setImageResource(R.drawable.blank); dealerCardImage.setVisibility(View.INVISIBLE); } //first dealer card is hidden dealerCardImages[0].setImageResource(R.drawable.card_back); //deal 2 cards to each player dealCard(playerCards); dealCard(dealerCards); dealCard(playerCards); dealCard(dealerCards); //rarely-used code in the event two aces are dealt on the first hand if (playerCards.score > 21){ playerCards.decAces(); playerCards.decScore(); } if (dealerCards.score > 21){ dealerCards.decAces(); dealerCards.decScore(); } updateCards(); } private void updateCards(){ //refresh view of cards, scores, and update messages for (int i = 0; i < playerCards.cards.size(); i++){ //update all player card images //uses bitmapFactory to reduce card image size, as default card image sizes cause memory issues. how long did it take me to figure this out? don't ask. String s = ("card_" + playerCards.cards.get(i).number + "_of_" + playerCards.cards.get(i).suit); int id = getResources().getIdentifier(s, "drawable", getPackageName()); int displayWidth = playerCardImages[i].getWidth(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; //access card image size without loading it into memoru BitmapFactory.decodeResource(getResources(), id, options); int imageWidth = options.outWidth; if (imageWidth > displayWidth){ //reduce size of card image based on size of display, saves memory int widthRatio = Math.round((float) imageWidth / (float) displayWidth); options.inSampleSize = widthRatio; } options.inJustDecodeBounds = false; Bitmap scaledBitmap = BitmapFactory.decodeResource(getResources(), id, options); playerCardImages[i].setVisibility(View.VISIBLE); playerCardImages[i].setImageBitmap(scaledBitmap); } for (int i = 1; i < dealerCards.cards.size(); i++){ //update all dealer card images EXCEPT first card - note starting value of i String s = ("card_" + dealerCards.cards.get(i).number + "_of_" + dealerCards.cards.get(i).suit); int id = getResources().getIdentifier(s, "drawable", getPackageName()); int displayWidth = dealerCardImages[i].getWidth(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), id, options); int imageWidth = options.outWidth; if (imageWidth > displayWidth){ int widthRatio = Math.round((float) imageWidth / (float) displayWidth); options.inSampleSize = widthRatio; } options.inJustDecodeBounds = false; Bitmap scaledBitmap = BitmapFactory.decodeResource(getResources(), id, options); dealerCardImages[i].setVisibility(View.VISIBLE); dealerCardImages[i].setImageBitmap(scaledBitmap); } //first dealer card is hidden dealerCardImages[0].setVisibility(View.VISIBLE); dealerCardImages[0].setImageResource(R.drawable.card_back); winnerTextView.setVisibility(View.INVISIBLE); //hide double down error message. make sure to call updateCards BEFORE setting the message! //update player cash and bet totalCashTextView.setText(getResources().getString(R.string.total_cash) + " " + playerCash); playerBetTextView.setText(getResources().getString(R.string.current_bet) + " " + playerBet); playerScoreTextView.setText(getResources().getString(R.string.player_score) + " " + playerCards.score); dealerScoreTextView.setText(getResources().getString(R.string.dealer_score) + " " + dealerCards.score); if (!playing){ //display hidden dealer card if game is over String s = ("card_" + dealerCards.cards.get(0).number + "_of_" + dealerCards.cards.get(0).suit); int id = getResources().getIdentifier(s, "drawable", getPackageName()); dealerCardImages[0].setVisibility(View.VISIBLE); dealerCardImages[0].setImageResource(id); } } private void setButtonOnClickListeners() { //set button listeners. this was done before I learned it could be done via XML but is being kept for posterity betPlus10Button.setOnClickListener(new View.OnClickListener() { //increase bet by 10, only available while game is active @Override public void onClick(View v) { //increase bet by 10 if game not active. can you increase your bet during the game in blackjack? I don't know. if (!playing && playerBet <= playerCash - 10) { playerBet += 10; playerBetTextView.setText(getResources().getString(R.string.current_bet) + " " + playerBet); } } }); betPlus100Button.setOnClickListener(new View.OnClickListener(){ //increase bet by 100, only available while game is active @Override public void onClick(View v) { //increase bet by 100 if game not active if (!playing && playerBet <= playerCash-100){ playerBet += 100; playerBetTextView.setText(getResources().getString(R.string.current_bet) + " " + playerBet); } } }); shoeModeButton.setOnClickListener(new View.OnClickListener(){ //toggle shoe mode which allos repeat cards, only available while game is inactive @Override public void onClick(View v) { if (!playing){ if (shoeMode){ shoeMode = false; shoeModeButton.setText(R.string.shoe_mode_off); }else{ shoeMode = true; shoeModeButton.setText(R.string.shoe_mode_on); } } } }); hitButton.setOnClickListener(new View.OnClickListener(){ //player hit @Override public void onClick(View v) { if (playing){ dealCard(playerCards); updateCards(); //this code accounts for the variable value of aces. if the player goes over 21, the game checks to see if an ace is present, whose value can be changed from 11 to 1 if (playerCards.score > 21){ if (playerCards.aces > 0){ playerCards.decAces(); playerCards.decScore(); updateCards(); }else{ //no aces to decrement means player busts dealerWins(); } } if (playerCards.cards.size() >= 5 && playerCards.score <= 21){ //five card charlie always wins playerWins(); } dealerTurn(); } } }); standButton.setOnClickListener(new View.OnClickListener(){ //player stands and passes turn to dealer @Override public void onClick(View v) { if (playing){ playerStands = true; if (dealerStands){ scoreCompare(); } dealerTurn(); } } }); newGameButton.setOnClickListener(new View.OnClickListener(){ //begins new game, only available upon win or loss @Override public void onClick(View v) { newGame(); } }); doubleDownButton.setOnClickListener(new View.OnClickListener(){ //double down gives player 1 more card and double bet @Override public void onClick(View v) { if (playing){ if (playerCards.score >= 9 && playerCards.score <=11){ //can only double down on 9, 10, 11 playerStands = true; playerBet *= 2; //double bet dealCard(playerCards); if (playerCards.score > 21){ if (playerCards.aces > 0){ playerCards.decAces(); playerCards.decScore(); updateCards(); }else{ //no aces to decrement means player busts dealerWins(); } } if (playerCards.cards.size() >= 5 && playerCards.score <= 21){ //five card charlie always wins playerWins(); } dealerTurn(); }else{ winnerTextView.setVisibility(View.VISIBLE); //display error message winnerTextView.setText(R.string.doubleDownError); } } } }); surrenderButton.setOnClickListener(new View.OnClickListener(){ //give up and only lose half bet @Override public void onClick(View v) { if(playing){ playerBet /= 2; //decrease bet by half dealerWins(); } } }); } private void scoreCompare() { //check to see whose score is higher if neither player has busted and both elect to stand updateCards(); if (playerCards.score == 21 && dealerCards.score == 21){ //blackjack (21 with 2 cards) beats any other 21 if (dealerCards.cards.size() == 2){ dealerWins(); }else if (playerCards.cards.size() == 2){ playerWins(); } } if (playerCards.score > 21){ //player busts dealerWins(); }else if (dealerCards.score > 21){ //dealer busts playerWins(); }else if (playerCards.score > dealerCards.score){ //ties awarded to dealer playerWins(); }else{ dealerWins(); } } private void dealerWins() { //run when dealer declared winner playerCash -= playerBet; //player loses bet playing = false; updateCards(); winnerTextView.setText(R.string.dealer_wins); //display loss message winnerTextView.setVisibility(View.VISIBLE); newGameButton.setVisibility(View.VISIBLE); //new game now available dealerScoreTextView.setVisibility(View.VISIBLE); //dealer score now visible playerBet = 100; //reset to minimum bet betPlus10Button.setVisibility(View.VISIBLE); //bet & shoe mode buttons can only be used between games betPlus100Button.setVisibility(View.VISIBLE); shoeModeButton.setVisibility(View.VISIBLE); hitButton.setVisibility(View.INVISIBLE); //hit, stand, double, surrender buttons cannot be used between games standButton.setVisibility(View.INVISIBLE); doubleDownButton.setVisibility(View.INVISIBLE); surrenderButton.setVisibility(View.INVISIBLE); } private void playerWins(){ //run when player declared winner playerCash += playerBet; //player wins bet playing = false; updateCards(); winnerTextView.setText(R.string.player_wins); //display win message winnerTextView.setVisibility(View.VISIBLE); newGameButton.setVisibility(View.VISIBLE); //new game now available dealerScoreTextView.setVisibility(View.VISIBLE); //dealer score now visible playerBet = 100; //reset to minimum bet betPlus10Button.setVisibility(View.VISIBLE); //bet & shoe mode buttons can only be used between games betPlus100Button.setVisibility(View.VISIBLE); shoeModeButton.setVisibility(View.VISIBLE); hitButton.setVisibility(View.INVISIBLE); //hit, stand, double, surrender buttons cannot be used between games standButton.setVisibility(View.INVISIBLE); doubleDownButton.setVisibility(View.INVISIBLE); surrenderButton.setVisibility(View.INVISIBLE); } private void dealerTurn(){ //dealer action, method called after player action resolved if (playing){ if (dealerCards.score < 17){ //dealer always hits on 16 or lower dealCard(dealerCards); updateCards(); //this code accounts for the variable value of aces. // if the dealer goes over 21, the game checks to see if an ace is present, whose value can be changed from 11 to 1 if (dealerCards.score > 21){ if (dealerCards.aces > 0){ dealerCards.decAces(); dealerCards.decScore(); updateCards(); }else{ playerWins(); } } //five card charlie always wins if (dealerCards.cards.size() >= 5 && dealerCards.score <= 21){ dealerWins(); } }else{ dealerStands = true; updateCards(); winnerTextView.setText(R.string.dealer_stands); //display dealer stands message winnerTextView.setVisibility(View.VISIBLE); if (playerStands){ scoreCompare(); } } //if the player stands, turn goes to dealer again until dealer stands or busts if (playerStands){ dealerTurn(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.aboutBlackjack) { Intent intent = new Intent(this, InfoScreen.class); startActivity(intent); } return super.onOptionsItemSelected(item); } class card{ //card has a suit and a number private String suit; private String number; public card(){ this.suit = null; this.number = null; } public void setSuit(String newSuit){ //suit setter this.suit = newSuit; } public String getSuit(){ return suit; } //suit getter public void setNumber(String newNumber){ this.number = newNumber; } //number setter public String getNumber(){ return number; } //number getter } class hand{ //hand is an array of cards, keeps track of overall score and how many aces have not been decremented from 11 to 1 private int aces = 0; private int score = 0; private ArrayList<card> cards = new ArrayList<>(); public void incAces(){ this.aces++; } public void decAces(){ this.aces--; } public void incScore(int scorePlus){ this.score += scorePlus; } public void decScore(){ //score can only be decreased if an ace is changes from 11 to 1, thus decreasing score by 10 this.score = this.score - 10; } } public void dealCard(hand hand){ //add card to a hand, adjust score and ace count boolean repeatCheck = true; card nextCard = new card(); //check if selected card is already in either hand, reroll if it is if (!shoeMode){ while (repeatCheck){ generateCard(nextCard); if (!(repeatCard(nextCard.getNumber(), nextCard.getSuit()))){ repeatCheck = false; } } }else { generateCard(nextCard); } //add to aces if ace is dealt if (nextCard.number.equals("ace")){ hand.incAces(); } hand.cards.add(nextCard); hand.incScore(faceValue(nextCard)); updateCards(); } public void generateCard(card nextCard){ //create 1 of 4 suits and 1 of 13 numbers int dealSuit; int dealNumber; String checkSuit; String checkNumber; Random r = new Random(); dealSuit = r.nextInt(4) + 1; switch (dealSuit){ case 1: checkSuit = "hearts"; break; case 2: checkSuit = "clubs"; break; case 3: checkSuit = "diamonds"; break; default: checkSuit = "spades"; break; } dealNumber = r.nextInt(13) + 1; switch (dealNumber){ case 1: checkNumber = "ace"; break; case 11: checkNumber = "jack"; break; case 12: checkNumber = "queen"; break; case 13: checkNumber = "king"; break; default: checkNumber = Integer.toString(dealNumber); break; } nextCard.setSuit(checkSuit); nextCard.setNumber(checkNumber); } public int faceValue(card card){ //determine int value for card number. probably could have saved code for numbers 2-10 somehow but this way works for all cards switch (card.number){ case "2": return 2; case "3": return 3; case "4": return 4; case "5": return 5; case "6": return 6; case "7": return 7; case "8": return 8; case "9": return 9; case "10": return 10; case "jack": return 10; case "queen": return 10; case "king": return 10; case "ace": return 11; //ace is worth 11 until it is decremented default: return 100; //detect errors in card generation } } public boolean repeatCard(String number, String suit){ //check both hands to see if a card already exists //this code is never used if shoe mode is active for (int i = 0; i < playerCards.cards.size(); i++){ if ((suit.equals(playerCards.cards.get(i).suit))&&(number.equals(playerCards.cards.get(i).number))){ return true; } } for (int i = 0; i < dealerCards.cards.size(); i++){ if ((suit.equals(dealerCards.cards.get(i).suit))&&(number.equals(dealerCards.cards.get(i).number))){ return true; } } return false; } }
package com.nexlesoft.tenwordsaday_chiforeng.fragment; import java.text.DecimalFormat; import java.util.ArrayList; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.ImageView; import com.flurry.android.FlurryAdListener; import com.flurry.android.FlurryAdSize; import com.flurry.android.FlurryAdType; import com.flurry.android.FlurryAds; import com.nexlesoft.tenwordsaday_chiforeng.BuyActivity; import com.nexlesoft.tenwordsaday_chiforeng.R; import com.nexlesoft.tenwordsaday_chiforeng.DHConstant; import com.nexlesoft.tenwordsaday_chiforeng.base.BaseFragment; import com.nexlesoft.tenwordsaday_chiforeng.base.SessionManager; import com.nexlesoft.tenwordsaday_chiforeng.constant.CLog; import com.nexlesoft.tenwordsaday_chiforeng.db.DataSourceBilling; import com.nexlesoft.tenwordsaday_chiforeng.db.DatabaseHelperBilling; import com.nexlesoft.tenwordsaday_chiforeng.db.SessionDataSource; import com.nexlesoft.tenwordsaday_chiforeng.db.WordDataSource; import com.nexlesoft.tenwordsaday_chiforeng.model.Session; import com.nexlesoft.tenwordsaday_chiforeng.model.Setting; import com.nexlesoft.tenwordsaday_chiforeng.model.Word; import com.nexlesoft.tenwordsaday_chiforeng.model.Word.WordStatus; import com.nexlesoft.tenwordsaday_chiforeng.utilities.Util; import com.nexlesoft.tenwordsaday_chiforeng.widget.FontableButton; import com.nexlesoft.tenwordsaday_chiforeng.widget.FontableTextView; public class CongratulationFragment extends BaseFragment implements OnClickListener, FlurryAdListener { private static final String TAG = CongratulationFragment.class.getSimpleName(); private FontableTextView mtxtWordLearn, mtxtRemain, mtxtCompleted, mtxtObjective, mtxtSpentLearning, mtxtWordLearnedCount; private FontableButton mBtnNextSession, mBtnQuit; private FrameLayout mFullScreenAdLayout; private boolean mBIsFinished = false; private ImageView imageView; public DataSourceBilling ds; String m_IsPremium = ""; @SuppressWarnings("unchecked") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (View) inflater.inflate(R.layout.fragment_congratulation, container, false); mActivity.setTitle(getString(R.string.str_learning)); mBtnNextSession = (FontableButton) mRootView.findViewById(R.id.btn_next_session); mBtnNextSession.setOnClickListener(this); mBtnQuit = (FontableButton) mRootView.findViewById(R.id.btn_quit); mBtnQuit.setOnClickListener(this); mtxtWordLearn = (FontableTextView) mRootView.findViewById(R.id.txt_word_learn_count); mtxtRemain = (FontableTextView) mRootView.findViewById(R.id.txt_word_remain); mtxtCompleted = (FontableTextView) mRootView.findViewById(R.id.txt_word_complete); mtxtObjective = (FontableTextView) mRootView.findViewById(R.id.txt_total_object); mtxtSpentLearning = (FontableTextView) mRootView.findViewById(R.id.txt_spend_time); mtxtWordLearnedCount = (FontableTextView) mRootView.findViewById(R.id.text_word_learned_count); mFullScreenAdLayout = (FrameLayout) mRootView.findViewById(R.id.full_screen_ad); imageView = (ImageView) mRootView.findViewById(R.id.btn_remove_ads); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult(new Intent(mActivity, BuyActivity.class), 0); } }); WordDataSource wordDS = new WordDataSource(mActivity); wordDS.open(); ArrayList<Word> words = (ArrayList<Word>) (ArrayList<?>) wordDS.getAllData(); wordDS.close(); SessionDataSource sessionDS = new SessionDataSource(mActivity); sessionDS.open(); Session lastSession = sessionDS.getLastSession(); sessionDS.close(); int wordLearnedNum = 0, wordRemainNum = 0; if (words != null && words.size() > 0) { for (Word word : words) { if (word.status == WordStatus.GOT_IT) { wordLearnedNum++; } } Setting setting = SessionManager.getInstance(mActivity).getSetting(); if (setting != null) { setting.overalObjectiveNum = setting.overalObjectiveNum == 0 ? words.size() : setting.overalObjectiveNum; setting.maxObject = words.size(); wordRemainNum = setting.overalObjectiveNum - wordLearnedNum; float completePercent = ((float) wordLearnedNum / (float) setting.overalObjectiveNum) * 100; mtxtRemain.setText(wordRemainNum + ""); mtxtCompleted.setText(new DecimalFormat("#.##").format(completePercent) + "%"); mtxtObjective.setText(setting.overalObjectiveNum + ""); mtxtSpentLearning.setText(Util.convertLongToDateString(lastSession.longTimeSpent, false, true, true)); mtxtWordLearnedCount.setText(SessionManager.getInstance(mActivity).getCorrectAnswerCount() + ""); if (completePercent == 100) { mBtnNextSession.setText(getString(R.string.str_reset_session)); mBIsFinished = true; } } mtxtWordLearn.setText(wordLearnedNum + ""); } ds = DataSourceBilling.getDataSoucre(mActivity); if(ds != null) { m_IsPremium = ds.SelectIsPremium(DatabaseHelperBilling.COLUMN_IS_PREMIUM); CLog.d(TAG, "m_IsPremium ::: " + m_IsPremium); if(m_IsPremium == null || m_IsPremium.equals("")) { FlurryAds.setAdListener(this); FetchAds(); mActivity.ShowLoadingDialog(); } else { imageView.setVisibility(View.GONE); } } return mRootView; } /* Flurry implements */ private void FetchAds() { // if (!DHConstant.DEBUG_MODE) { // mActivity.ShowLoadingDialog(); FlurryAds.fetchAd(mActivity, DHConstant.FLURRY_FULL_BANNER_NAME, mFullScreenAdLayout, FlurryAdSize.FULLSCREEN); // } } private void DisplayAds(boolean isDisplay, String adSpace) { // mActivity.CloseLoadingDialog(); if (isDisplay) { mFullScreenAdLayout.setVisibility(View.VISIBLE); FlurryAds.displayAd(mActivity, adSpace, mFullScreenAdLayout); } else { // mFullScreenAdLayout.setVisibility(View.GONE); mActivity.CloseLoadingDialog(); } } @Override public void ClearInstance() { } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_next_session: if (mBIsFinished) mActivity.resetDBData(); mActivity.pushFragments(new LearningSessionFragment(), true, false); break; case R.id.btn_quit: mActivity.finish(); break; default: break; } } @Override public void onAdClicked(String arg0) { } @Override public void onAdClosed(String arg0) { // if (!mBIsQuit) { // mActivity.pushFragments(new LearningSessionFragment(), true, false); // } else { // mActivity.finish(); // } DisplayAds(false, null); } @Override public void onAdOpened(String arg0) { } @Override public void onApplicationExit(String arg0) { } @Override public void onRenderFailed(String adSpace) { if (adSpace.equals(DHConstant.FLURRY_FULL_BANNER_NAME)) { CLog.d(TAG, "onRenderFailed"); DisplayAds(false, null); } } @Override public void onRendered(String arg0) { } @Override public void onVideoCompleted(String arg0) { } @Override public boolean shouldDisplayAd(String arg0, FlurryAdType arg1) { return true; } @Override public void spaceDidFailToReceiveAd(String adSpace) { if (adSpace.equals(DHConstant.FLURRY_FULL_BANNER_NAME)) { CLog.d(TAG, "spaceDidFailToReceiveAd"); // if (!mBIsQuit) // mActivity.pushFragments(new LearningSessionFragment(), true, // false); // else // // mActivity.pushFragments(new ActivitySummaryFragment(), true, // // false); // mActivity.finish(); // mActivity.CloseLoadingDialog(); DisplayAds(false, adSpace); } } @Override public void spaceDidReceiveAd(String adSpace) { if (adSpace.equals(DHConstant.FLURRY_FULL_BANNER_NAME)) { DisplayAds(true, adSpace); mActivity.CloseLoadingDialog(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { CLog.d(TAG, "onActivityResult ::: " + resultCode); if(resultCode == android.app.Activity.RESULT_OK) { imageView.setVisibility(View.GONE); } } }
package net.acomputerdog.BlazeLoader.util.config; import net.acomputerdog.BlazeLoader.main.BlazeLoader; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Contains a list of ModConfigs. Handles reflection necessary to load/save fields. */ public class ConfigList { private static List<ModConfig> configs = new ArrayList<ModConfig>(); public static void addConfig(ModConfig config) { configs.add(config); } public static void loadConfig(ModConfig config) { try { File loadFile = config.getSaveFile(); if (!loadFile.exists()) { saveConfig(config); } Properties properties = new Properties(); properties.load(new FileInputStream(loadFile)); for (Field f : config.getClass().getDeclaredFields()) { if (!Modifier.isTransient(f.getModifiers())) { f.setAccessible(true); loadField(f, properties, config); } } } catch (Exception e) { BlazeLoader.getLogger().logError("Could not load config for mod " + config.getOwner().getModName()); e.printStackTrace(); } } public static void saveConfig(ModConfig config) { Properties saveFile = new Properties(); for (Field f : config.getClass().getDeclaredFields()) { if (!Modifier.isTransient(f.getModifiers())) { f.setAccessible(true); saveField(f, saveFile, config); } } try { saveFile.store(new BufferedOutputStream(new FileOutputStream(config.configFile)), config.getOwner().getModName()); } catch (IOException e) { BlazeLoader.getLogger().logError("Could not save config for mod: " + config.getOwner().getModName()); e.printStackTrace(); } } private static void saveField(Field field, Properties properties, ModConfig config) { try { if (int.class.isAssignableFrom(field.getType()) || byte.class.isAssignableFrom(field.getType()) || boolean.class.isAssignableFrom(field.getType()) || long.class.isAssignableFrom(field.getType()) || double.class.isAssignableFrom(field.getType()) || float.class.isAssignableFrom(field.getType()) || float.class.isAssignableFrom(field.getType()) || char.class.isAssignableFrom(field.getType()) || short.class.isAssignableFrom(field.getType()) || String.class.isAssignableFrom(field.getType())) { Object value = field.get(config); if (value != null) { properties.setProperty(field.getName(), value.toString()); } else { BlazeLoader.getLogger().logWarning("Skipping null field " + field.getName()); } } else { BlazeLoader.getLogger().logWarning("Skipping invalid config field " + field.getName() + " from mod " + config.getOwner().getModName()); } } catch (Exception e) { BlazeLoader.getLogger().logError("Error saving config field " + field.getName() + " from mod " + config.getOwner().getModName()); e.printStackTrace(); } } private static void loadField(Field field, Properties properties, ModConfig config) { try { Object value = field.get(config); if (value != null) { if (int.class.isAssignableFrom(field.getType())) { field.set(config, Integer.parseInt(properties.getProperty(field.getName(), value.toString()))); } else if (byte.class.isAssignableFrom(field.getType())) { field.set(config, Byte.parseByte(properties.getProperty(field.getName(), value.toString()))); } else if (boolean.class.isAssignableFrom(field.getType())) { field.set(config, Boolean.parseBoolean(properties.getProperty(field.getName(), value.toString()))); } else if (long.class.isAssignableFrom(field.getType())) { field.set(config, Long.parseLong(properties.getProperty(field.getName(), value.toString()))); } else if (double.class.isAssignableFrom(field.getType())) { field.set(config, Double.parseDouble(properties.getProperty(field.getName(), value.toString()))); } else if (float.class.isAssignableFrom(field.getType())) { field.set(config, Float.parseFloat(properties.getProperty(field.getName(), value.toString()))); } else if (char.class.isAssignableFrom(field.getType())) { field.set(config, (properties.getProperty(field.getName(), value.toString())).toCharArray()[0]); } else if (short.class.isAssignableFrom(field.getType())) { field.set(config, Short.parseShort(properties.getProperty(field.getName(), value.toString()))); } else if (String.class.isAssignableFrom(field.getType())) { field.set(config, properties.getProperty(field.getName(), value.toString())); } else { BlazeLoader.getLogger().logWarning("Skipping invalid config field " + field.getName() + " from mod " + config.getOwner().getModName()); } } else { BlazeLoader.getLogger().logWarning("Skipping null field " + field.getName()); } } catch (Exception e) { BlazeLoader.getLogger().logError("Error loading config field " + field.getName() + " from mod " + config.getOwner().getModName()); e.printStackTrace(); } } public static void saveAllConfigs() { for (ModConfig config : configs) { try { config.saveConfig(); } catch (Exception e) { BlazeLoader.getLogger().logError("Unknown error saving config for mod " + config.getOwner().getModName()); e.printStackTrace(); } } } }
package com.example.android.finalproject_yaocmengqid.MainContent; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.android.finalproject_yaocmengqid.Expense; import com.example.android.finalproject_yaocmengqid.People; import com.example.android.finalproject_yaocmengqid.R; import com.example.android.finalproject_yaocmengqid.SideMenu.ProfileActivity; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.math.BigDecimal; import java.util.ArrayList; import static com.example.android.finalproject_yaocmengqid.R.id.help; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private DatabaseReference mExpensesRef; private String TAG = "LoginActivity"; private RecyclerView mRecyclerView; private RecyclerView.LayoutManager mLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, RecordActivity.class); startActivity(intent); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); mRecyclerView = (RecyclerView) findViewById(R.id.my_mainrecycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mRecyclerView.setHasFixedSize(true); // use a linear layout manager mLayoutManager = new LinearLayoutManager(MainActivity.this); mRecyclerView.setLayoutManager(mLayoutManager); mExpensesRef = FirebaseDatabase.getInstance().getReference("expenses").child(user.getUid()); FirebaseRecyclerAdapter<Expense, ExpenseViewHolder> mAdapter = new FirebaseRecyclerAdapter<Expense, ExpenseViewHolder>( Expense.class, R.layout.main_item, ExpenseViewHolder.class, mExpensesRef ) { @Override protected void populateViewHolder(ExpenseViewHolder holder, Expense model, int position) { holder.mName.setText(model.getExpenseType()); holder.mDate.setText(model.getDateString()); holder.mMoney.setText(model.getAmount()); ArrayList<People> payers = model.getPayers(); String payerString = ""; for (People people : payers) { payerString += people.getName() + " "; } holder.mReceiver.setText("Paid by: " + payerString); if(model.getExpenseType().equals("food")){ holder.mIcon.setImageResource(R.drawable.food_icon); }else if(model.getExpenseType().equals("transportation")){ holder.mIcon.setImageResource(R.drawable.trans_icon); }else if(model.getExpenseType().equals("entertainment")){ holder.mIcon.setImageResource(R.drawable.ticket_icon); }else if(model.getExpenseType().equals("shelter")){ holder.mIcon.setImageResource(R.drawable.house_icon); }else if(model.getExpenseType().equals("others")){ holder.mIcon.setImageResource(R.drawable.other_icon); } } }; mRecyclerView.setAdapter(mAdapter); DatabaseReference mDatabaseRef = FirebaseDatabase.getInstance().getReference("users").child(user.getUid()); mDatabaseRef.child("name").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String name = dataSnapshot.getValue(String.class); if (name != null) { ((TextView)findViewById(R.id.nav_text1)).setText(name); } } @Override public void onCancelled(DatabaseError databaseError) { } }); mDatabaseRef.child("email").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String email = dataSnapshot.getValue(String.class); if (email != null) { ((TextView)findViewById(R.id.nav_text2)).setText(email); } } @Override public void onCancelled(DatabaseError databaseError) { } }); mDatabaseRef.child("profilePhoto").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String url = dataSnapshot.getValue(String.class); if (url != null) { ImageView imageView = (ImageView) findViewById(R.id.nav_image); Picasso.with(MainActivity.this).load(Uri.parse(url)) .resize(imageView.getWidth(), imageView.getHeight()) .centerInside() .into(imageView); ImageView avatar = (ImageView) findViewById(R.id.avatar); Picasso.with(MainActivity.this).load(Uri.parse(url)) .resize(avatar.getWidth(), avatar.getHeight()) .centerInside() .into(avatar); } } @Override public void onCancelled(DatabaseError databaseError) { } }); FirebaseDatabase.getInstance().getReference("people").child(user.getUid()) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { ArrayList<People> members = new ArrayList<People>(); //People people = dataSnapshot.getValue(People.class); for (DataSnapshot child : dataSnapshot.getChildren()) members.add(child.getValue(People.class)); BigDecimal pay = new BigDecimal(members.get(0).getPay()); BigDecimal expense = new BigDecimal(members.get(0).getExpense()); BigDecimal delta = pay.subtract(expense); int mark = delta.compareTo(BigDecimal.ZERO); if (mark == 1) { ((TextView) findViewById(R.id.money_string_main)).setText("You still need to receive"); ((TextView) findViewById(R.id.money_main)).setText("$ " + delta.setScale(2).toString()); } else if (mark == -1) { ((TextView) findViewById(R.id.money_string_main)).setText("You still need to pay"); ((TextView) findViewById(R.id.money_main)).setText("$ " + delta.negate().setScale(2).toString()); } ((TextView) findViewById(R.id.my_expense)).setText(expense.toString()); for (int i = 1; i < members.size(); ++ i) expense = expense.add(new BigDecimal(members.get(i).getExpense())); ((TextView) findViewById(R.id.total_expense)).setText(expense.toString()); ((TextView) findViewById(R.id.group_number)).setText("" + members.size()); } @Override public void onCancelled(DatabaseError databaseError) { } }); } else { // User is signed out Log.d(TAG, "onAuthStateChanged:signed_out"); Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); } // ... } }; } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } @Override public void onStop() { if (mAuthListener != null) { mAuth.removeAuthStateListener(mAuthListener); } super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement /*if (id == R.id.action_settings) { return true; }*/ return super.onOptionsItemSelected(item); } public void manageGroup(View view) { startActivity(new Intent(this, ManageGroupActivity.class)); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); String [] emailList = {"dz2276@tc.columbia.edu"}; if (id == R.id.setting) { startActivity(new Intent(this, ProfileActivity.class)); } else if (id == R.id.manage_group) { startActivity(new Intent(this, ManageGroupActivity.class)); } else if (id == R.id.summary) { startActivity(new Intent(this, SummaryActivity.class)); } else if (id == help) { Intent help = new Intent(Intent.ACTION_SENDTO); help.setData(Uri.parse("mailto:")); help.putExtra(Intent.EXTRA_EMAIL, emailList ); help.putExtra(Intent.EXTRA_SUBJECT, "Question"); if (help.resolveActivity(getPackageManager())!=null) { startActivity(help); } } else if (id == R.id.log_out) { logout(item); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public void logout(MenuItem item) { mAuth.signOut(); } public void groupSummary(MenuItem item) { startActivity(new Intent(this, SummaryActivity.class)); } public void calculate(View view) { startActivity(new Intent(this, CalculateActivity.class)); } private static class ExpenseViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public ImageView mIcon; public TextView mName; public TextView mDate; public TextView mMoney; public TextView mReceiver; public View myView; public ExpenseViewHolder(View v) { super(v); mIcon = (ImageView) v.findViewById(R.id.icon); mName = (TextView) v.findViewById(R.id.item_name); mDate = (TextView) v.findViewById(R.id.date); mMoney = (TextView) v.findViewById(R.id.money); mReceiver = (TextView) v.findViewById(R.id.receiver_name); myView = v; } } }
package pack1; import java.util.Arrays; import java.util.Scanner; public class Positive { void check(){ Scanner scan=new Scanner(System.in); String name=scan.next(); char[] ch = name.toCharArray(); int[] num=new int[ch.length]; int[] fin=new int[ch.length]; for(int i=0;i<ch.length;i++){ fin[i]=(int)(ch[i]); } for(int i=0;i<ch.length;i++){ num[i]=(int)(ch[i]); } Arrays.sort(num); if(Arrays.equals(fin,num)){ System.out.println("yes"); } else System.out.println("no"); } public static void main(String[] args) { // TODO Auto-generated method stub Positive obj1=new Positive(); obj1.check(); } }
package com.company.iba.ialeditor.model.impl; import com.company.iba.ialeditor.model.Dictionary; import com.company.iba.ialeditor.service.DictionaryLocalServiceUtil; import com.liferay.portal.kernel.exception.SystemException; /** * The extended model base implementation for the Dictionary service. Represents a row in the &quot;IALEditor_Dictionary&quot; database table, with each column mapped to a property of this class. * * <p> * This class exists only as a container for the default extended model level methods generated by ServiceBuilder. Helper methods and all application logic should be put in {@link DictionaryImpl}. * </p> * * @author Brian Wing Shun Chan * @see DictionaryImpl * @see com.company.iba.ialeditor.model.Dictionary * @generated */ public abstract class DictionaryBaseImpl extends DictionaryModelImpl implements Dictionary { /* * NOTE FOR DEVELOPERS: * * Never modify or reference this class directly. All methods that expect a dictionary model instance should use the {@link Dictionary} interface instead. */ @Override public void persist() throws SystemException { if (this.isNew()) { DictionaryLocalServiceUtil.addDictionary(this); } else { DictionaryLocalServiceUtil.updateDictionary(this); } } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.testfixture.servlet; import java.io.IOException; import java.io.InputStream; import jakarta.servlet.ReadListener; import jakarta.servlet.ServletInputStream; import org.springframework.util.Assert; /** * Delegating implementation of {@link jakarta.servlet.ServletInputStream}. * * <p>Used by {@link MockHttpServletRequest}; typically not directly * used for testing application controllers. * * @author Juergen Hoeller * @since 1.0.2 * @see MockHttpServletRequest */ public class DelegatingServletInputStream extends ServletInputStream { private final InputStream sourceStream; private boolean finished = false; /** * Create a DelegatingServletInputStream for the given source stream. * @param sourceStream the source stream (never {@code null}) */ public DelegatingServletInputStream(InputStream sourceStream) { Assert.notNull(sourceStream, "Source InputStream must not be null"); this.sourceStream = sourceStream; } /** * Return the underlying source stream (never {@code null}). */ public final InputStream getSourceStream() { return this.sourceStream; } @Override public int read() throws IOException { int data = this.sourceStream.read(); if (data == -1) { this.finished = true; } return data; } @Override public int available() throws IOException { return this.sourceStream.available(); } @Override public void close() throws IOException { super.close(); this.sourceStream.close(); } @Override public boolean isFinished() { return this.finished; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener readListener) { throw new UnsupportedOperationException(); } }
package walke.base.tool; import android.Manifest; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.text.TextUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.List; public class Util { public static boolean checkPermission(Context context, String permission) { boolean result = false; if (Build.VERSION.SDK_INT >= 23) { try { Class<?> clazz = Class.forName("android.content.Context"); Method method = clazz.getMethod("checkSelfPermission", String.class); int rest = (Integer) method.invoke(context, permission); if (rest == PackageManager.PERMISSION_GRANTED) { result = true; } else { result = false; } } catch (Exception e) { result = false; } } else { PackageManager pm = context.getPackageManager(); if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) { result = true; } } return result; } public static String getDeviceInfo(Context context) { try { org.json.JSONObject json = new org.json.JSONObject(); android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); String device_id = null; if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) { device_id = tm.getDeviceId(); } String mac = null; FileReader fstream = null; try { fstream = new FileReader("/sys/class/net/wlan0/address"); } catch (FileNotFoundException e) { fstream = new FileReader("/sys/class/net/eth0/address"); } BufferedReader in = null; if (fstream != null) { try { in = new BufferedReader(fstream, 1024); mac = in.readLine(); } catch (IOException e) { } finally { if (fstream != null) { try { fstream.close(); } catch (IOException e) { e.printStackTrace(); } } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } json.put("mac", mac); if (TextUtils.isEmpty(device_id)) { device_id = mac; } if (TextUtils.isEmpty(device_id)) { device_id = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); } json.put("device_id", device_id); return json.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * @return 当前版本名 */ public static String getVersionName(Context context) { PackageManager packageManager = context.getPackageManager(); String version = ""; try { // getPackageName()是你当前类的包名,0代表是获取版本信息 PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0); version = packInfo.versionName; } catch (Exception e) { } return version; } /** * 判断某个界面是否在前台 * * @param context * @param className 某个界面名称 */ public static boolean isForeground(Context context, String className) { if (context == null || TextUtils.isEmpty(className)) { return false; } ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1); if (list != null && list.size() > 0) { ComponentName cpn = list.get(0).topActivity; if (className.equals(cpn.getClassName())) { return true; } } return false; } /** * 验证手机格式 */ public static boolean isMobile(String number) { /* 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188 +147 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通) 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9 [1][7358]\d{9}--原来 [1][47358]\d{9}--2017.4.25 改 */ String num = "[1][47358]\\d{9}";//"[1]"代表第1位为数字1,"[7358]"代表第二位可以为7、3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。 if (TextUtils.isEmpty(number)) { return false; } else { //matches():字符串是否在给定的正则表达式匹配 return number.matches(num); } } public interface OnInstallListener { void onInstallFuncation(Context context, File file); } }
package br.edu.infnet.appSistemaEspecialistaEmFreios.model.repository; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import br.edu.infnet.appSistemaEspecialistaEmFreios.model.domain.Empresa; @Repository public interface EmpresaRepository extends CrudRepository<Empresa, Integer>{ @Query("from Empresa e where e.usuario.id = :userId") public List<Empresa> obterLista(Integer userId); }
package com.esum.comp.sftp.outbound; import java.io.File; import java.util.Hashtable; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.comp.sftp.SftpCode; import com.esum.comp.sftp.SftpConfig; import com.esum.comp.sftp.SftpException; import com.esum.comp.sftp.client.SftpClientConnInfo; import com.esum.comp.sftp.client.SftpSession; import com.esum.comp.sftp.client.SftpSessionFactory; import com.esum.comp.sftp.server.SFTPServer; import com.esum.comp.sftp.table.SftpInfoRecord; import com.esum.comp.sftp.table.SftpInfoTable; import com.esum.framework.common.util.DateUtil; import com.esum.framework.common.util.FileUtil; import com.esum.framework.common.util.StringUtil; import com.esum.framework.common.util.UserVariableUtil; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.component.config.ComponentConfigFactory; import com.esum.framework.core.component.table.InfoTableManager; import com.esum.framework.core.event.RoutingStatus; import com.esum.framework.core.event.log.ErrorInfo; import com.esum.framework.core.event.log.LoggingEvent; import com.esum.framework.core.event.message.EventHeader; import com.esum.framework.core.event.message.MessageEvent; import com.esum.framework.core.event.message.Payload; import com.esum.framework.core.event.util.LoggingEventUtil; import com.esum.framework.core.exception.SystemException; import com.esum.framework.security.ssh.SSHAuthInfo; import com.esum.framework.security.ssh.SSHAuthInfoManager; import com.esum.router.RouterUtil; import com.esum.router.handler.OutboundHandlerAdapter; import com.esum.router.table.document.DocInfoRecord; import com.esum.router.table.partner.PartnerInfoRecord; /** * Copyright(c) eSum Technologies, Inc. All rights reserved. */ public class SftpOutboundHandler extends OutboundHandlerAdapter { private Logger logger = LoggerFactory.getLogger(getClass()); private SftpInfoTable infoTable = null; private String channelName; protected SftpOutboundHandler(String componentId, String channelName) { super(componentId); this.setLog(logger); this.channelName = channelName; } protected LoggingEvent onPostProcess(MessageEvent messageEvent, Object[] params, String status) throws SystemException { LoggingEvent logEvent = LoggingEventUtil.makeLoggingEvent(messageEvent.getEventHeader().getType(), messageEvent.getMessageControlId(), getComponentId(), messageEvent, status); if(status.equals(RoutingStatus.QRSP_STATUS)) logEvent.getLoggingInfo().getMessageLog().setPullSendFlag("Y"); // set fileName to outMessageId. if(params!=null && params.length==1) logEvent.getLoggingInfo().getMessageLog().setOutMessageId(params[0].toString()); return logEvent; } public void onProcess(MessageEvent messageEvent) { this.traceId = "[" + messageEvent.getMessageControlId() + "] "; SftpInfoRecord infoRecord = null; try { String fromSvcId = messageEvent.getMessage().getHeader().getFromParty().getUserId(); String toSvcId = messageEvent.getMessage().getHeader().getToParty().getUserId(); String inMsgId = messageEvent.getMessage().getHeader().getInMessageId(); String msgName = messageEvent.getMessage().getHeader().getMessageName(); String targetIfId = messageEvent.getRoutingInfo().getTargetInterfaceId(); if (StringUtils.isEmpty(targetIfId)) targetIfId = RouterUtil.getTargetInterfaceId(fromSvcId, toSvcId, msgName); this.setInterfaceId(targetIfId); if(infoTable==null) infoTable = (SftpInfoTable)InfoTableManager.getInstance().getInfoTable(SftpConfig.SFTP_INFO_TABLE_ID); infoRecord = (SftpInfoRecord)infoTable.getInfoRecord(new String[]{ getInterfaceId() }); traceId = traceId + "[" + infoRecord.getInterfaceId() + "]"; Payload payload = messageEvent.getMessage().getPayload(); byte[] data = payload.getData(); if (infoRecord.isUseOutboundPull()) { if (!SFTPServer.isVirtual()) { String status = RoutingStatus.QRSP_STATUS; boolean isError = messageEvent.getMessage().getPayload().hasError(); if(messageEvent.getEventHeader().getType()==EventHeader.TYPE_ACKNOWLEDGE) status = isError?RoutingStatus.ACK_FAIL_STATUS:RoutingStatus.DONE_STATUS; String fileName = messageEvent.getMessageControlId()+"_"+messageEvent.getEventHeader().getType()+"_"+status; saveOutbound(fileName, payload.getDataInfo().getReceiver(), data, infoRecord.getOutboundFileEncoding()); logger.info(traceId + "Save Data to OUTBOX. (" + payload.getDataInfo().getReceiver() + ")"); } processSucess(messageEvent, new Object[]{messageEvent.getMessageControlId()}, RoutingStatus.QRSP_STATUS, RoutingStatus.QRSP_STATUS); logger.info(traceId+"Outbound Routing Completed. Status : "+RoutingStatus.QRSP_STATUS); return; } /** send file */ logger.debug(traceId + "Creating SFTP Client Information..."); SftpClientConnInfo sftpConnInfo = getOutboundClient(infoRecord); logger.debug(traceId + "Created SFTP Client Information: " + sftpConnInfo); logger.debug(traceId + "Sending data to " + sftpConnInfo.getHost() + " on " + sftpConnInfo.getPort() + "..."); // Directory Naming pattern Hashtable<String, String> dirParams = new Hashtable<String, String>(); PartnerInfoRecord senderInfo = RouterUtil.getPartnerInfo(messageEvent.getMessage().getPayload().getDataInfo().getSender()); PartnerInfoRecord receiverInfo = RouterUtil.getPartnerInfo(messageEvent.getMessage().getPayload().getDataInfo().getReceiver()); String docName = messageEvent.getMessage().getPayload().getDataInfo().getDocumentName(); String secondDocName = docName; if (RouterUtil.isExistDocInfoRecord(docName, senderInfo.getTpId(), receiverInfo.getTpId())) { DocInfoRecord docInfo = RouterUtil.getDocInfoRecord(docName, senderInfo.getTpId(), receiverInfo.getTpId()); secondDocName = docInfo.getBizSvcName(); } dirParams.put("sendUser", fromSvcId); dirParams.put("recvUser", toSvcId); dirParams.put("docName", docName); dirParams.put("bizSvcName", secondDocName); String dirName = StringUtil.replacePropertyToValue(sftpConnInfo.getDirectory().trim(), dirParams); // File Naming pattern Map<String, String> userVariables = UserVariableUtil.generateUserVariables(messageEvent.getMessageControlId(), fromSvcId, toSvcId, inMsgId, payload); String fileName = StringUtil.replacePropertyToValue(sftpConnInfo.getRename().trim(), userVariables); // Unique channelSftp ID String channelSftpId = infoRecord.getInterfaceId() + "_" + channelName; if (logger.isDebugEnabled()) logger.debug(traceId + "Transferring data to " + sftpConnInfo.getAuthInfoId() + "@" + sftpConnInfo.getHost() + " on " + sftpConnInfo.getPort() + "..."); transfer(traceId, channelSftpId, sftpConnInfo, data, dirName, fileName); if (logger.isDebugEnabled()) logger.debug(traceId + "Transfered data successfully to host. " + sftpConnInfo.getHost() + " on " + sftpConnInfo.getPort() + "."); SftpConfig sftpConfig = (SftpConfig)ComponentConfigFactory.getInstance(getComponentId()); String outputStatus = sftpConfig.getReqMsgOutputStatus(msgName); if(messageEvent.getEventHeader().getType()==EventHeader.TYPE_ACKNOWLEDGE) { logger.debug(traceId+"acknowledge event. sending status is DONE."); outputStatus = RoutingStatus.DONE_STATUS; } setSentTime(DateUtil.getCYMDHMSS()); processSucess(messageEvent, new Object[] {fileName}, outputStatus, sftpConfig.getSyncOutputStatus(), true); } catch (ComponentException e) { logger.error(traceId + "SFTP Info Handling Error!!", e); processError(messageEvent, e); messageEvent.getMessage().getHeader().setErrorInfo(new ErrorInfo(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage())); } catch (SftpException e) { logger.error(traceId + "SFTP Transfer Error!!", e); processError(messageEvent, e); messageEvent.getMessage().getHeader().setErrorInfo(new ErrorInfo(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage())); } catch (Exception e) { logger.error(traceId + "Undefined Error!!", e); SftpException se = new SftpException(SftpCode.ERROR_UNDEFINED, "process()", e.getMessage(), e); processError(messageEvent, se); messageEvent.getMessage().getHeader().setErrorInfo(new ErrorInfo(se.getErrorCode(), se.getErrorLocation(), se.getErrorMessage())); } } private void saveOutbound(String fileName, String authInfoId, byte[] data, String inboundFileEncoding) throws Exception { SSHAuthInfo authInfo = SSHAuthInfoManager.getInstance().getAuthInfo(authInfoId); if (authInfo != null) { File tempFile = new File(SftpConfig.SERVER_HOME, fileName); File dstDir = new File(SftpConfig.USER_HOME, authInfo.getUserId() + File.separator + SftpConfig.SERVER_OUTBOUND_DIR); if (!dstDir.exists()) { dstDir.mkdirs(); } File dstFile = new File(dstDir, fileName); if (dstFile.exists()) { dstFile.delete(); } FileUtil.writeToFile(tempFile, data, inboundFileEncoding); FileUtil.moveFile(tempFile, dstFile); } else throw new SftpException(SftpCode.ERROR_NOT_FOUND_SSH_AUTH_INFO, "saveOutbound()", "Could not get the SSH Auth Info. (id : "+authInfoId + ")"); } /** * Data transfer */ private void transfer(String traceId, String sessionId, SftpClientConnInfo connInfo, byte[] data, String remoteDirName, String remoteFileName) throws SftpException { int maxRetryCnt = SftpConfig.RETRY; int retryCnt = 0; if (logger.isDebugEnabled()) logger.debug(traceId + "Sending file(" + remoteFileName + ") to "+connInfo.getHost()); SftpSession sessionSftp = null; try { while(retryCnt <= maxRetryCnt) { retryCnt++; try { sessionSftp = SftpSessionFactory.getInstance().getSession(sessionId, connInfo); } catch (Exception e) { log.warn(traceId + "SFTP Channel open failed: " + e.toString()); SftpSessionFactory.getInstance().destroy(sessionSftp); /** connection 오류가 나면 retry 하도록 한다. */ if (retryCnt > maxRetryCnt) { throw new SftpException(SftpCode.ERROR_CLIENT_TRANSFER, "transfer()", "SFTP Data Transfer Error! " + e.toString()); } try { log.info(traceId+"Transfer retry... ("+retryCnt+"/"+maxRetryCnt+")"); Thread.sleep(1000); } catch (InterruptedException ex) { log.error(traceId+"Sftp sending interruped by user."); break; } continue; } try { log.info(traceId + "Connected to '" + sessionSftp + "'."); if(remoteDirName!=null && remoteDirName.equals("/INBOX")) { sessionSftp.cd(remoteDirName); logger.debug(traceId + "Sending dir("+remoteDirName+") file(" + remoteFileName + ") to " + connInfo.getHost() + "..."); sessionSftp.write(data, remoteFileName); } else { String remoteTempFileName = remoteFileName+".saving"; sessionSftp.write(data, "/"+SftpConfig.SERVER_TEMP_DIR+"/"+remoteTempFileName); if(logger.isDebugEnabled()) logger.debug(traceId + "Sending dir("+SftpConfig.SERVER_TEMP_DIR+") file(" + remoteTempFileName + ") to " + connInfo.getHost() + "..."); if (StringUtils.isEmpty(remoteDirName) || remoteDirName.equals(".")) { sessionSftp.rename("/"+SftpConfig.SERVER_TEMP_DIR+"/"+remoteTempFileName, remoteFileName); logger.info(traceId + "Sent dir("+remoteDirName+") file(" + remoteFileName + ") to " + connInfo.getHost()); } else { sessionSftp.cd(remoteDirName); sessionSftp.rename("/"+SftpConfig.SERVER_TEMP_DIR+"/"+remoteTempFileName, remoteFileName); logger.info(traceId + "Sent dir("+remoteDirName+") file(" + remoteFileName + ") to " + connInfo.getHost()); } } SftpSessionFactory.getInstance().destroy(sessionSftp); logger.info(traceId + "Disconnected to " + connInfo.getHost() + " on " + connInfo.getPort()); break; } catch (Exception e) { log.warn(traceId + e.getMessage(), e); if (retryCnt > maxRetryCnt) { throw new SftpException(SftpCode.ERROR_CLIENT_TRANSFER, "transfer()", "SFTP Data Transfer Error! " + e.toString()); } logger.error(traceId + "Transfer retries: " + retryCnt, e); } finally { if(sessionSftp!=null) SftpSessionFactory.getInstance().destroy(sessionSftp); } try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error(traceId + e.getMessage(), e); throw new SftpException(SftpCode.ERROR_CLIENT_TRANSFER, "transfer()", "Could not send to data."); } } } finally { if(sessionSftp!=null) SftpSessionFactory.getInstance().destroy(sessionSftp); } } private SftpClientConnInfo getOutboundClient(SftpInfoRecord sftpInfo) throws SftpException { // create SFTP Client Details SftpClientConnInfo clientConnInfo = new SftpClientConnInfo(); clientConnInfo.setHost(sftpInfo.getOutboundHostIp()); clientConnInfo.setPort(sftpInfo.getOutboundHostPort()); clientConnInfo.setAuthInfoId(sftpInfo.getOutboundSshAuthInfoId()); clientConnInfo.setInterfaceId(sftpInfo.getInterfaceId()); clientConnInfo.setDirectory(sftpInfo.getOutboundDirectory()); clientConnInfo.setRename(sftpInfo.getOutboundRename()); return clientConnInfo; } }
package com.openfarmanager.android.googledrive.api; import com.openfarmanager.android.googledrive.model.About; import com.openfarmanager.android.googledrive.model.File; import com.openfarmanager.android.googledrive.model.Token; import com.openfarmanager.android.googledrive.model.exceptions.CreateFolderException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import static com.openfarmanager.android.googledrive.GoogleDriveConstants.LIST_URL; import static com.openfarmanager.android.googledrive.GoogleDriveConstants.UPLOAD_URL; import static com.openfarmanager.android.googledrive.api.Fields.FOLDER_MIME_TYPE; import static com.openfarmanager.android.googledrive.api.Fields.ID; import static com.openfarmanager.android.googledrive.api.Fields.MIME_TYPE; import static com.openfarmanager.android.googledrive.api.Fields.PARENTS; import static com.openfarmanager.android.googledrive.api.Fields.TITLE; /** * author: Vlad Namashko */ public class GoogleDriveWebApi extends Api { private String setupQuery(String path) { switch (path) { case File.SHARED_FOLDER_ID: return "sharedWithMe"; case File.STARRED_FOLDER_ID: return "starred=true"; default: return String.format("'%s'+in+parents+and+trashed=false", path); } } public List<File> listFiles(String path) throws Exception { if (path == null || path.trim().equals("") || path.equals("/")) { path = "root"; } List<File> files = new ArrayList<File>(); list(files, null, setupQuery(path)); return files; } public List<File> search(String title) throws Exception { List<File> files = new ArrayList<File>(); list(files, null, String.format("title+contains+'%s'+and+trashed=false", title)); return files; } public String getDownloadLink(String link) { return link + '&' + getAuth(); } public InputStream download(String downloadLink) throws IOException { URL url = new URL(downloadLink + '&' + getAuth()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int statusCode = connection.getResponseCode(); if (isTokenExpired(statusCode, connection.getResponseMessage())) { setupToken(refreshToken(mToken)); download(downloadLink); } if (statusCode > 200) throw new RuntimeException(); return connection.getInputStream(); } public void upload(String parentId, String title, java.io.File file, UploadListener listener) { try { JSONObject postData = new JSONObject(); setupFileNameData(title, parentId, postData); MultipartUtility multipartUtility = new MultipartUtility(new URL(UPLOAD_URL + '?' + getAuth() + "&uploadType=multipart")); try { multipartUtility.addFormField("meta", postData.toString(), "application/json"); multipartUtility.addFilePart("content", file, listener); int statusCode = multipartUtility.doRequest(); String message = multipartUtility.getResponseMessage(); if (isTokenExpired(statusCode, message)) { setupToken(refreshToken(mToken)); upload(parentId, title, file, listener); } } finally { multipartUtility.close(); } } catch (Exception e) { e.printStackTrace(); } } public boolean delete(String fileId) { try { HttpURLConnection connection = createConnection(new URL(LIST_URL + "/" + fileId + '?' + getAuth())); connection.setRequestMethod(METHOD_DELETE); int responseCode = connection.getResponseCode(); if (responseCode == 403) { return delete(fileId); } return responseCode >= 200 && responseCode <= 204; } catch (Exception e) { e.printStackTrace(); return false; } } public File createDirectory(String title, String parentId) { try { HttpURLConnection connection = createConnection(new URL(LIST_URL + '?' + getAuth())); connection.setRequestMethod(METHOD_POST); JSONObject postData = new JSONObject(); postData.put(MIME_TYPE, FOLDER_MIME_TYPE); setupFileNameData(title, parentId, postData); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(postData.toString()); out.close(); int statusCode = connection.getResponseCode(); if (isTokenExpired(statusCode, connection.getResponseMessage())) { setupToken(refreshToken(mToken)); return createDirectory(title, parentId); } if (statusCode == 201 || statusCode == 200) { return new File(streamToString(connection.getInputStream())); } throw new CreateFolderException(); } catch (Exception e) { e.printStackTrace(); return null; } } public boolean rename(String fileId, String newTitle) { try { JSONObject obj = new JSONObject(); obj.put(TITLE, newTitle); return updateData(fileId, obj.toString()); } catch (Exception e) { e.printStackTrace(); return false; } } public boolean updateData(String fileId, String data) { try { HttpURLConnection connection = createConnection(new URL(LIST_URL + "/" + fileId + '?' + getAuth())); connection.setRequestMethod(METHOD_PUT); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(data); out.close(); int statusCode = connection.getResponseCode(); if (isTokenExpired(statusCode, connection.getResponseMessage())) { setupToken(refreshToken(mToken)); return updateData(fileId, data); } return statusCode == 200; } catch (Exception e) { e.printStackTrace(); return false; } } private void list(List<File> files, String nextPageToken, String query) throws Exception { String url = LIST_URL + '?' + getAuth() + "&maxResults=1000&q=" + query; if (nextPageToken != null) { url += "&pageToken=" + URLEncoder.encode(nextPageToken, "UTF-8"); } URL urlConnection = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlConnection.openConnection(); int statusCode = connection.getResponseCode(); if (isTokenExpired(statusCode, connection.getResponseMessage())) { setupToken(refreshToken(mToken)); list(files, nextPageToken, query); return; } if (statusCode == 201 || statusCode == 200) { String json = streamToString(connection.getInputStream()); JSONObject responseObject = new JSONObject(json); JSONArray items = responseObject.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject object = (JSONObject) items.get(i); try { files.add(new File(object)); } catch (Exception e) { e.printStackTrace(); } } String pageToken = null; try { pageToken = responseObject.getString("nextPageToken"); } catch (Exception ignore) { } if (pageToken != null) { list(files, pageToken, query); } } } public File getFile(String fileId) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(LIST_URL + "/" + fileId + "?" + getAuth()).openConnection(); connection.setRequestProperty("Cache-Control", "no-cache"); int responseCode = connection.getResponseCode(); if (isTokenExpired(responseCode, connection.getResponseMessage())) { setupToken(refreshToken(mToken)); return getFile(fileId); } if (responseCode == 201 || responseCode == 200) { return new File(streamToString(connection.getInputStream())); } return null; } private HttpURLConnection createConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setRequestProperty("Cache-Control", "no-cache"); return connection; } private void setupFileNameData(String title, String parentId, JSONObject postData) throws JSONException { postData.put(TITLE, title); JSONArray parents = new JSONArray(); JSONObject parent = new JSONObject(); parent.put(ID, parentId); postData.put(PARENTS, parents.put(parent)); } public static interface UploadListener { void onProgress(int uploaded, int transferedPortion, int total); } }
package web_study_11.dao; import static org.junit.Assert.fail; import java.sql.Connection; import java.util.Calendar; import java.util.List; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import web_study_11.dao.impl.ProductImpl; import web_study_11.ds.JdbcUtil; import web_study_11.dto.Product; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ProductDaoTest { private static ProductDao dao ; private static Connection con; @BeforeClass public static void setUpBeforeClass() throws Exception{ con = JdbcUtil.getConnection(); dao = ProductImpl.getInstance(); dao.setCon(con); } @Test public void testSelectProductByAll() { System.out.println("testSelectProductByAll()"); List<Product> list = dao.selectProductByAll(); Assert.assertNotNull(list); list.stream().forEach(System.out::println); } @Test public void test01InsertProduct() { System.out.println("testSelectProductByAll()"); Product newProduct = new Product(10, "이현석", 500, "현석이다", "??"); int res = dao.insertProduct(newProduct); Assert.assertEquals(1, res); } @Test public void testSelectProductBycode() { System.out.println("testSelectProductBycode()"); Product pdt = dao.selectProductBycode(1); Assert.assertNotNull(pdt); System.out.println(pdt); } @Test public void test02UpdateProduct() { System.out.println("testUpdateProduct()"); Product modifyPdt = dao.selectProductBycode(10); System.out.println("before : " + modifyPdt); //(NAME, USERID, PWD, EMAIL, PHONE, ADMIN) modifyPdt.setName("최수정"); modifyPdt.setPrice(3333); modifyPdt.setDescription("홍홍홍"); modifyPdt.setPictureUrl("잇음"); int res = dao.updateProduct(modifyPdt); Assert.assertEquals(1, res); System.out.println("after : " + modifyPdt); } @Test public void test03DeleteProduct() { System.out.println("testDeleteProduct()"); int res = dao.deleteProduct(10); Assert.assertEquals(1, res); } @Test public void testSetCon() { System.out.println(con); } }
package com.itheima.day15_cookieDemo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/cookieDemo_01") public class CookieDemo_01 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //创建cookie Cookie cookie = new Cookie("username","zhangsan"); //添加cookie至本地浏览器 response.addCookie(cookie); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
import java.sql.DriverManager; import java.sql.SQLDataException; import java.sql.Statement; import java.util.Collection; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.sql.*; public class MonitoringGUI extends Application{ Stage mainStage; GridPane gpane; Monitoring mon; MenuBar menu; ComboBox<String> whichObs; /** * The start method is the initial method of the GUI to create the first window * @param primaryStage is the intial Stage that is viewed */ @Override public void start(Stage primaryStage) { load(); mainStage=primaryStage; mainStage.setTitle("Galamsey Monitoring Application"); mainStage.setScene(addWindow()); mainStage.show(); } /** * The addWindow method create the menu to be displayed on the stages * @return selectScene is the view of the menu */ public Scene addWindow() { menu = new MenuBar(); Menu view = new Menu("View"); Menu obs = new Menu("Observatory"); obs.setOnAction(event->createObserTable(view)); Menu gal = new Menu("Galamsey"); gal.setOnAction(event->createGalamTable(view,null)); view.getItems().addAll(obs,gal); Menu add = new Menu("Add Data"); Menu adobs = new Menu("Add Observatory"); Menu adgal = new Menu("Add Galamsey"); adobs.setOnAction(event->observatory(add)); adgal.setOnAction(event->galamsey(add)); add.getItems().addAll(adgal,adobs); menu.getMenus().addAll(add,view); gpane = new GridPane(); gpane.add(menu, 0, 0); Scene selectScene = new Scene(gpane,600,300); return selectScene; } public static void main(String[] args) { launch(args); } /** * The galamsey method creates a form-like window to input new galamsey objects into the database * @param clicked Clicked is the menu used to call the method and is passed in order to hide the dropdown on click */ public void galamsey(Menu clicked) { if (clicked!=null){ clicked.hide(); } load(); GridPane grid = new GridPane(); grid.add(menu, 0, 0); Label veg = new Label("Vegetation Colour"); TextField veg1 = new TextField(); grid.add(veg, 0, 2); grid.add(veg1, 2, 2); Label col = new Label("Colour Value"); TextField col1 = new TextField(); grid.add(col, 0, 3); grid.add(col1, 2, 3); Label pos = new Label("Position (Longitude,Latitude)"); TextField pos1 = new TextField(); TextField pos2 = new TextField(); grid.add(pos, 0, 4); grid.add(pos1, 2, 4); grid.add(pos2, 4, 4); Label yr = new Label("Event Year"); TextField yr1 = new TextField(); grid.add(yr, 0, 5); grid.add(yr1, 2, 5); Label ob = new Label("Observation"); ComboBox<String> obs1 = new ComboBox<String>(); obs1.getItems().addAll(mon.observations.keySet()); grid.add(ob, 0, 6); grid.add(obs1, 2, 6); Button submit = new Button("Submit"); grid.add(submit, 2, 7); submit.setOnAction(event-> { try { galam_data(veg1.getText(), Integer.parseInt(col1.getText()), Double.parseDouble(pos1.getText()), Double.parseDouble(pos1.getText()), Integer.parseInt(yr1.getText()), obs1.getValue()); } catch (SQLDataException e) { e.printStackTrace(); } }); mainStage.setScene( new Scene(grid,600,300)); } /** * The observatory method creates a form-like window to input new observatory objects into the database * @param clicked Clicked is the menu used to call the method and is passed in order to hide the dropdown on click */ public void observatory(Menu clicked) { if (clicked!=null){ clicked.hide(); } GridPane grid = new GridPane(); grid.add(menu, 0, 0); Label noObs = new Label("Name of observatory"); TextField noObs1 = new TextField(); grid.add(noObs, 0, 2); grid.add(noObs1, 2, 2); Label nOC = new Label("Name of Country"); TextField nOC1 = new TextField(); grid.add(nOC, 0, 3); grid.add(nOC1, 2, 3); Label yr = new Label("Year of observatory"); TextField yr1 = new TextField(); grid.add(yr, 0, 4); grid.add(yr1, 2, 4); Label area = new Label("Area under observatory"); TextField area1 = new TextField(); grid.add(area, 0, 5); grid.add(area1, 2, 5); Button submit = new Button("Submit"); submit.setOnAction(event-> { try { obser_data(noObs1.getText(),nOC1.getText(),Integer.parseInt(yr1.getText()),Double.parseDouble(area1.getText())); } catch (SQLDataException e) { e.printStackTrace(); } }); grid.add(submit, 2, 6); mainStage.setScene(new Scene(grid,600,300)); } /** * Creates a galamsey object to the appropriate observation hashtable and add the data to the galamsey table in the database * to ensure that both the database and the code have the same data * @param veg_col Vegetation colour of the galamsey * @param col Colour value of the galamsey * @param lon Longitude value of the location of the galamsey occurence * @param lat Latitude value of the location of the galamsey occurence * @param year The year of the galamsey occurence * @param obs The name of the observatory the galamsey occurence is part of * @throws SQLDataException */ public void galam_data(String veg_col,int col,double lon,double lat, int year,String obs) throws SQLDataException { Galamsey galamsey = new Galamsey(veg_col,col,lon,lat,year); galamsey.setObservatory_name(obs); mon.observations.get(obs).add_Galamsey(galamsey); galamsey(null); galamsey.intakeData_Galamsey(); } /** * The load methods loads the data in the database into the hastable */ public void load() { mon = new Monitoring(); Connection conn; ResultSet rs; String query = "select * from galamsey"; conn = null; String sql = "select * from observatory"; try{ Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ICP_Project?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root",""); Statement st = conn.createStatement(); rs = st.executeQuery(sql); // iterate through the java while(rs.next()) { String obser_name = rs.getString("observatory_name"); String country = rs.getString("country_located"); int year_event = rs.getInt("year_obsv"); int area = rs.getInt("area_covered"); mon.observations.put(obser_name.trim(),new Observatory(obser_name,country,year_event,area)); } st = conn.createStatement(); // rs holds all the results of the query rs = st.executeQuery(query); System.out.println("Records from database"); while(rs.next()){ String Vegetation_colour = rs.getString("veg_col"); int Colour_value = rs.getInt("col_value"); double latitude = rs.getDouble("latitude"); double longitude = rs.getDouble("latitude"); int year = rs.getInt("event_year"); String observatory_name = rs.getString("observatory_name"); mon.observations.get(observatory_name.trim()).add_Galamsey(new Galamsey(Vegetation_colour,Colour_value,latitude,longitude,year)); } st.close(); conn.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } /** * The obser_data method adds the observatory data into the observatory table in the database as well as adding observatory * object to the hashtable * @param name The name of the observatory * @param country The country of the observatory * @param year The year of the observatory * @param area The area covered by the observatory */ public void obser_data(String name, String country, int year, double area) throws SQLDataException { Observatory observe = new Observatory(name,country,year,area); mon.observations.put(name, observe); // add to observatory table observatory(null); observe.intake_Data_Observatory(); } /** * View the galamsey table of a specified observatory * @param clicked Clicked is the menu used to call the method and is passed in order to hide the dropdown on click * @param name The observation name that the user wishes to view */ public void createGalamTable(Menu clicked, String name) { if (clicked!=null) clicked.hide(); ComboBox<String> whichObs = new ComboBox<String>(); whichObs.getItems().addAll(mon.observations.keySet()); whichObs.setOnAction(event->createGalamTable(null,whichObs.getValue())); GridPane b = new GridPane(); Label lCol= new Label("Largest Colour Value: 0"); Label aCol = new Label("Average Colour Value: 0"); ObservableList<Galamsey> galam = FXCollections.observableArrayList(); if (name!= null) { Observatory o =mon.observations.get(name); lCol.setText("Largest Colour Value: "+ o.getLargestValue()); aCol.setText("Average Colour Value: "+ o.getAvgValue()); for (int i = 0; i < o.getObservations().size(); i++) { galam.add(o.getObservations().get(i)); } } TableColumn<Galamsey,String> vegcolColumn= new TableColumn<>("Vegetation Colour"); vegcolColumn.setMinWidth(150); vegcolColumn.setCellValueFactory(new PropertyValueFactory<>("veg_col")); TableColumn<Galamsey,Integer> colColumn= new TableColumn<>("Colour Value"); colColumn.setMinWidth(150); colColumn.setCellValueFactory(new PropertyValueFactory<>("col_value")); TableColumn<Galamsey,Double> lon= new TableColumn<>("longitude"); lon.setMinWidth(100); lon.setCellValueFactory(new PropertyValueFactory<>("longitude")); TableColumn<Galamsey,Double> lat= new TableColumn<>("Latitude"); lat.setMinWidth(100); lat.setCellValueFactory(new PropertyValueFactory<>("latitude")); TableColumn<Galamsey,Integer> year= new TableColumn<>("Year"); year.setMinWidth(100); year.setCellValueFactory(new PropertyValueFactory<>("year")); TableView<Galamsey> galamTable = new TableView<>(); galamTable.setItems(galam); galamTable.getColumns().addAll(vegcolColumn,colColumn,lon,lat,year); VBox vbox = new VBox(); vbox.getChildren().addAll(galamTable); Button limit = new Button("Galamsey at Limit"); limit.setOnAction(event->fromGalamseyAtLimit(name)); b.add(menu, 0, 0); b.add(whichObs,0,1); b.add(vbox,0,2); b.add(aCol, 0, 3); b.add(lCol,0,4); b.add(limit, 0, 5); Scene s = new Scene(b,600,400); mainStage.setScene(s); } /** * View the observatory table * @param clicked Clicked is the menu used to call the method and is passed in order to hide the dropdown on click */ public void createObserTable(Menu clicked) { clicked.hide(); GridPane b = new GridPane(); Label lCol= new Label("Largest Colour Value: 0"); Label aCol = new Label("Average Colour Value: 0"); ObservableList<Observatory> observe = FXCollections.observableArrayList(); lCol.setText("Largest Ever Colour Value: "+mon.getLargestAvgColour()); aCol.setText("Largest Average Colour Value: "+mon.getLargestAvgColour()); System.out.println(mon.getLargestAvgColour() +" "+mon.getLargestColour() ); Collection<Observatory> g =mon.observations.values(); for (Observatory observatory : g) { observe.add(observatory); } TableColumn<Observatory,String> name= new TableColumn<>("Name"); name.setMinWidth(150); name.setCellValueFactory(new PropertyValueFactory<>("name")); TableColumn<Observatory,String> country= new TableColumn<>("Country"); country.setMinWidth(150); country.setCellValueFactory(new PropertyValueFactory<>("country")); TableColumn<Observatory,Integer> year= new TableColumn<>("Year"); year.setMinWidth(100); year.setCellValueFactory(new PropertyValueFactory<>("year")); TableColumn<Observatory,Double> area= new TableColumn<>("Area Covered"); area.setMinWidth(200); area.setCellValueFactory(new PropertyValueFactory<>("areaCovered")); TableView<Observatory> obsTable = new TableView<>(); obsTable.setItems(observe); obsTable.getColumns().addAll(name,country,year,area); VBox vbox = new VBox(); vbox.getChildren().addAll(obsTable); Button limit = new Button("Galamsey at Limit"); limit.setOnAction(event->fromObservatoryAtLimit()); b.add(menu, 0, 0); b.add(obsTable,0,2); b.add(aCol, 0, 3); b.add(lCol,0,4); b.add(limit, 0, 5); Scene s = new Scene(b,600,400); mainStage.setScene(s); } /** * View the Galamsey data in a given observatory that have a colour value greater than a given value * @param name The name of the observatory currently being viewed */ public void fromGalamseyAtLimit(String name) { Stage displayLimit = new Stage(); Label limit = new Label("Enter the colour value range"); TextField text = new TextField(); Button submit = new Button("Submit"); submit.setOnAction(event->galamLimit(name, Integer.parseInt(text.getText()))); VBox vbox= new VBox(); vbox.getChildren().addAll(limit,text,submit); Scene s = new Scene(vbox,300,300); displayLimit.setScene(s); displayLimit.show(); } /** * View the galamsey data with a colour value greater than the limit in the observatory with the given name * @param name The observatory name to be viewed from * @param limit The limit at which the galamsey objects are filtered */ public void galamLimit(String name,int limit) { Stage stage = new Stage(); ObservableList<Galamsey> galam = FXCollections.observableArrayList(); if (name!= null) { Observatory o =mon.observations.get(name); for (int i = 0; i < o.getObservations().size(); i++) { if(o.getObservations().get(i).getCol_value()>limit) { galam.add(o.getObservations().get(i)); } } } TableColumn<Galamsey,String> vegcolColumn= new TableColumn<>("Vegetation Colour"); vegcolColumn.setMinWidth(150); vegcolColumn.setCellValueFactory(new PropertyValueFactory<>("veg_col")); TableColumn<Galamsey,Integer> colColumn= new TableColumn<>("Colour Value"); colColumn.setMinWidth(150); colColumn.setCellValueFactory(new PropertyValueFactory<>("col_value")); TableColumn<Galamsey,Double> lon= new TableColumn<>("Longitude"); lon.setMinWidth(100); lon.setCellValueFactory(new PropertyValueFactory<>("longitude")); TableColumn<Galamsey,Double> lat= new TableColumn<>("Latitude"); lat.setMinWidth(100); lat.setCellValueFactory(new PropertyValueFactory<>("latitude")); TableColumn<Galamsey,Integer> year= new TableColumn<>("Year"); year.setMinWidth(100); year.setCellValueFactory(new PropertyValueFactory<>("year")); TableView<Galamsey> galamTable = new TableView<>(); galamTable.setItems(galam); galamTable.getColumns().addAll(vegcolColumn,colColumn,lon,lat,year); VBox vbox = new VBox(); vbox.getChildren().addAll(galamTable); Scene s = new Scene(vbox,600,400); stage.setScene(s); stage.show(); } /** * View the galamsey data with a colour value greater than the limit in the database * @param limit The limit at which the galamsey objects are filtered */ public void fromObservatoryAtLimit() { Stage displayLimit = new Stage(); Label limit = new Label("Enter the colour value range"); TextField text = new TextField(); Button submit = new Button("Submit"); submit.setOnAction(event->obGalamLimit( Integer.parseInt(text.getText()))); VBox vbox= new VBox(); vbox.getChildren().addAll(limit,text,submit); Scene s = new Scene(vbox,300,300); displayLimit.setScene(s); displayLimit.show(); } /** * View the galamsey data with a colour value greater than the limit in the database * @param limit The limit at which the galamsey objects are filtered */ public void obGalamLimit(int limit) { Stage stage = new Stage(); ObservableList<Galamsey> galam = FXCollections.observableArrayList(); galam.addAll(mon.getObservations(limit)); TableColumn<Galamsey,String> vegcolColumn= new TableColumn<>("Vegetation Colour"); vegcolColumn.setMinWidth(150); vegcolColumn.setCellValueFactory(new PropertyValueFactory<>("veg_col")); TableColumn<Galamsey,Integer> colColumn= new TableColumn<>("Colour Value"); colColumn.setMinWidth(150); colColumn.setCellValueFactory(new PropertyValueFactory<>("col_value")); TableColumn<Galamsey,Double> lon= new TableColumn<>("Longitude"); lon.setMinWidth(100); lon.setCellValueFactory(new PropertyValueFactory<>("longitude")); TableColumn<Galamsey,Double> lat= new TableColumn<>("Latitude"); lat.setMinWidth(100); lat.setCellValueFactory(new PropertyValueFactory<>("latitude")); TableColumn<Galamsey,Integer> year= new TableColumn<>("Year"); year.setMinWidth(100); year.setCellValueFactory(new PropertyValueFactory<>("year")); TableView<Galamsey> galamTable = new TableView<>(); galamTable.setItems(galam); galamTable.getColumns().addAll(vegcolColumn,colColumn,lon,lat,year); VBox vbox = new VBox(); vbox.getChildren().addAll(galamTable); Scene s = new Scene(vbox,600,400); stage.setScene(s); stage.show(); } }
package atividade; import com.sun.management.OperatingSystemMXBean; import java.io.*; import java.lang.management.ManagementFactory; import java.net.ServerSocket; import java.net.Socket; /** * @author André Luiz Dias de Oliveira */ public class Servidor { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8080); Socket socket = serverSocket.accept(); System.out.println(socket.getInetAddress() + " Conectado!"); InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); PrintWriter printWriter = new PrintWriter(socket.getOutputStream()); while (true) { String clientResponse = bufferedReader.readLine(); if (clientResponse == null) break; printWriter.println(doSwitch(clientResponse)); printWriter.flush(); } serverSocket.close(); } public static String doSwitch(String response) { switch (response) { case "1": return getSystemMemoryInfo(1); case "2": return getSystemMemoryInfo(2); case "3": return getSystemMemoryInfo(3); case "4": return String.valueOf(ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors()) + " processadores"; case "5": return convertResponse(new File("/").getTotalSpace()); case "6": return convertResponse(new File("/").getFreeSpace()); default: return "Informe um valor valido!"; } } public static String convertResponse(long response) { double converted = (double) response / 1024 / 1024 / 1024; return converted +" GB"; } public static String getSystemMemoryInfo(int memoryType) { OperatingSystemMXBean os = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); long memory = 0; if (memoryType == 1) memory = os.getTotalPhysicalMemorySize(); else if (memoryType == 2) memory = os.getFreePhysicalMemorySize(); else memory = os.getTotalPhysicalMemorySize() - os.getFreePhysicalMemorySize(); return convertResponse(memory); } }
package io.core9.plugin.widgets.datahandler; import io.core9.plugin.server.request.Request; import java.util.Map; public abstract class ContextualDataHandler<T extends DataHandlerFactoryConfig> implements DataHandler<T> { @Override public Map<String,Object> handle(Request req) { return handle(req, req.getBodyAsMap().toBlocking().last()); } public abstract Map<String,Object> handle(Request req, Map<String,Object> context); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.lynn.dao.impl; import com.lynn.bean.UserBean; import com.lynn.dao.BaseDao; import com.lynn.dao.UserDaoI; import java.util.List; import org.springframework.stereotype.Repository; /** * * @author Administrator */ @Repository public class UserDao extends BaseDao<UserBean, Integer> implements UserDaoI{ @Override public UserBean getById(Integer id) { String hql = "from User where id = ?"; List<UserBean> list = getListByHQL(hql, id); if (list != null) { return list.get(0); } else { return null; } } @Override public UserBean getByName(String name) { String hql = "from User where username = ?"; List<UserBean> list = getListByHQL(hql, name); if (list != null) { return list.get(0); } else { return null; } } }