text
stringlengths 10
2.72M
|
|---|
/*
* Created by Angel Leon (@gubatron), Alden Torres (aldenml)
* Copyright (c) 2011-2014, 2013, FrostWire(R). All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.frostwire.gui.theme;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.CellRendererPane;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.synth.SynthTreeUI;
import javax.swing.tree.TreePath;
/**
*
* @author gubatron
* @author aldenml
*
*/
public final class SkinTreeUI extends SynthTreeUI {
private SkinMouseListener mouseListener;
public static ComponentUI createUI(JComponent comp) {
ThemeMediator.testComponentCreationThreadingViolation();
return new SkinTreeUI();
}
@Override
protected CellRendererPane createCellRendererPane() {
return new SkinCellRendererPane();
}
@Override
protected MouseListener createMouseListener() {
if (mouseListener == null) {
mouseListener = new SkinMouseListener(super.createMouseListener());
}
return mouseListener;
}
private void paintRowBackground(Graphics g, int x, int y, int w, int h) {
try {
TreePath path = getClosestPathForLocation(tree, 0, y);
int row = treeState.getRowForPath(path);
boolean selected = tree.isRowSelected(row);
if (selected) {
g.setColor(SkinColors.TABLE_SELECTED_BACKGROUND_ROW_COLOR);
} else if (row % 2 == 1) {
g.setColor(SkinColors.TABLE_ALTERNATE_ROW_COLOR);
} else if (row % 2 == 0) {
g.setColor(Color.WHITE);
}
g.fillRect(0, y, tree.getWidth(), h);
} catch (Throwable e) {
// just eat, not critical
}
}
private final class SkinCellRendererPane extends CellRendererPane {
// the following code is copied from the parent method
@Override
public void paintComponent(Graphics g, Component c, Container p, int x, int y, int w, int h, boolean shouldValidate) {
if (c == null) {
if (p != null) {
Color oldColor = g.getColor();
g.setColor(p.getBackground());
g.fillRect(x, y, w, h);
g.setColor(oldColor);
}
return;
}
if (c.getParent() != this) {
this.add(c);
}
c.setBounds(x, y, w, h);
if (shouldValidate) {
c.validate();
}
boolean wasDoubleBuffered = false;
if ((c instanceof JComponent) && ((JComponent) c).isDoubleBuffered()) {
wasDoubleBuffered = true;
((JComponent) c).setDoubleBuffered(false);
}
paintRowBackground(g, x, y, w, h);
Graphics cg = g.create(x, y, w, h);
try {
c.paint(cg);
} finally {
cg.dispose();
}
if (wasDoubleBuffered && (c instanceof JComponent)) {
((JComponent) c).setDoubleBuffered(true);
}
c.setBounds(-w, -h, 0, 0);
}
}
private final class SkinMouseListener implements MouseListener {
private final MouseListener delegate;
public SkinMouseListener(MouseListener delegate) {
this.delegate = delegate;
}
@Override
public void mouseClicked(MouseEvent e) {
delegate.mouseClicked(e);
}
@Override
public void mousePressed(MouseEvent e) {
TreePath path = getClosestPathForLocation(tree, e.getX(), e.getY());
if (path != null) {
tree.setSelectionPath(path);
}
delegate.mousePressed(e);
}
@Override
public void mouseReleased(MouseEvent e) {
delegate.mouseReleased(e);
}
@Override
public void mouseEntered(MouseEvent e) {
delegate.mouseEntered(e);
}
@Override
public void mouseExited(MouseEvent e) {
delegate.mouseExited(e);
}
}
}
|
package com.gxtc.huchuan.widget;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gxtc.huchuan.R;
/**
* Created by Gubr on 2017/3/17.
*/
public class RewardItem extends LinearLayout {
private TextView mTextView;
private TextView mTextView1;
public RewardItem(Context context) {
this(context,null);
}
public RewardItem(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public RewardItem(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
this.setOrientation(HORIZONTAL);
this.setGravity(Gravity.CENTER_HORIZONTAL);
this.setBackground(getResources().getDrawable(R.drawable.shape_reward_btn_bg));
LayoutParams layoutParams = (LayoutParams) getLayoutParams();
if (layoutParams == null) {
layoutParams = new LayoutParams(getContext(), null);
}
layoutParams.weight = 1;
setLayoutParams(layoutParams);
int dimension = getResources().getDimensionPixelOffset(R.dimen.margin_tiny);
this.setPadding(dimension, dimension, dimension, dimension);
mTextView = new TextView(getContext());
mTextView.setTextColor(getResources().getColor(R.color.red));
mTextView.setMaxEms(2);
mTextView.setMinEms(2);
mTextView1 = new TextView(getContext());
mTextView1.setTextColor(getResources().getColor(R.color.red));
addView(mTextView);
addView(mTextView1);
}
}
|
package com.itheima.bos.service;
import java.util.List;
import com.itheima.bos.domain.Function;
import com.itheima.bos.domain.User;
import com.itheima.bos.page.PageBean;
public interface IUserService {
public User login(User model);
public void editPassword(String password, String id);
public void save(User model, String[] roleIds);
public void pageQuery(PageBean pageBean);
}
|
/*
* 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 controle;
/**
*
* @author Mayco, Matheus, Henrique
*/
public class Fase {
private int numeroFase; //Numero da fase do jogo - 1, 2 ou 3
private int CIT; //Conjunto Imagens de trabalho (numero do CIT)
private int EST; //Estimulo - 0 = som, 1 = imagem e 2 = som e imagem
/**
* @return the CIT
*/
public int getCIT() {
return CIT;
}
/**
* @param CIT the CIT to set
*/
public void setCIT(int CIT) {
this.CIT = CIT;
}
/**
* @return the EST
*/
public int getEST() {
return EST;
}
/**
* @param EST the EST to set
*/
public void setEST(int EST) {
this.EST = EST;
}
/**
* @return the numeroFase
*/
public int getNumeroFase() {
return numeroFase;
}
/**
* @param numeroFase the numeroFase to set
*/
public void setNumeroFase(int numeroFase) {
this.numeroFase = numeroFase;
}
}
|
package com.tntdjs.mediaplayer;
/**
* MediaPlayerState
* @author tsenausk
*/
public final class MediaPlayerState {
public static final int INIT = 0;
public static final int OPEN = 1;
public static final int PLAY = 2;
public static final int PAUSE = 3;
public static final int STOP = 4;
private MediaPlayerState() {};
}
|
package com.edasaki.rpg.spells;
import com.edasaki.rpg.spells.villager.Firework;
public class VillagerSpellbook extends Spellbook {
public static final Spell FIREWORK = new Spell("Firework", 5, 1, 1, 0, new String[] { "Yay, fireworks! Totally harmless, by the way!",
}, null, new Firework());
// DON'T FORGET TO ADD TO SPELL_LIST
public static final Spellbook INSTANCE = new VillagerSpellbook();
private static final Spell[] SPELL_LIST = { FIREWORK };
@Override
public Spell[] getSpellList() {
return SPELL_LIST;
}
}
|
package com.wacai.springboot_demo;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.fastjson.JSON;
import com.wacai.springboot_demo.mapper.CourseMapper;
import com.wacai.springboot_demo.mapper.StudentCourseMapper;
import com.wacai.springboot_demo.mapper.StudentMapper;
import com.wacai.springboot_demo.model.CourseSelectInfo;
import com.wacai.springboot_demo.model.StudentCourse;
import com.wacai.springboot_demo.model.StudentCourseDetail;
import com.wacai.springboot_demo.service.CourseService;
import com.wacai.springboot_demo.service.StudentCourseService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SprintbootDemoApplicationTests {
@Autowired
StudentMapper studentMapper;
@Autowired
CourseMapper courseMapper;
@Autowired
StudentCourseMapper studentCourseMapper;
@Autowired
CourseService courseService;
@Autowired
StudentCourseService studentCourseService;
@Test
public void contextLoads() {
//Integer studentId = 3;
//Integer courseId = 2;
//studentCourseService.save(courseId,studentId);
//studentCourseService.delete(2);
String url = "/";
System.out.println(url.substring(0,url.indexOf('/')));
}
}
|
/*
* Ara - Capture Species and Specimen Data
*
* Copyright © 2009 INBio (Instituto Nacional de Biodiversidad).
* Heredia, Costa Rica.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.dto.inventory;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import org.inbio.ara.dto.GenericDTO;
/**
* The fields will the comment "read only" will be ignored on persistence tasks
*
* @author jgutierrez
*/
enum CoordType {DECIMAL,LAMBERT};
public class SpecimenDTO extends GenericDTO implements Serializable{
/* null when the specimen is new*/
private Long specimenKey;
/*catalogNumber is read only */
private String catalogNumber;
/*institutionCode is read only*/
private String institutionCode;
/*institutionId is read only*/
private Long institutionId;
/*collectionName is read only */
private String collectionName;
/*collectionId is read only */
private Long collectionId;
/*taxonName is read only */
private String taxonName;
/*taxonId is read only */
private Long taxonId;
/*localityDescription is read only */
private String localityDescription;
/*coordinates is read only */
private String coordinates;
/*countryName is read only */
private String countryName;
/*countryId is read only */
private Long countryId;
/*provinceName is read only */
private String provinceName;
/*provinceId is read only */
private Long provinceId;
/*responsibleName is read only */
private String responsibleName;
/*responsibleId is read only */
private Long responsibleId;
/*gatheringObsevationId is read only */
private Long gatheringObsevationId;
private Long gatheringObservationDetailId;
/*labelId is read only */
private Long labelId;
/*originalLabelId is read only */
private Long originalLabelId;
/* For Graphical Inteface purposes */
private boolean selected;
/*categoryName is read only */
private String categoryName;
/*persited*/
private Long categoryId;
/* typeName is read only*/
private String typeName;
/*persited*/
private Long typeId;
/* gatheringMethodName is read only*/
private String gatheringMethodName;
/*persited*/
private Long gatheringMethodId;
/* substrateName is read only*/
private String substrateName;
/*persited*/
private Long substrateId;
/*persited*/
private Long numberWhole;
/* extractionTypeName is read only*/
private String extractionTypeName;
/*persited*/
private Long extractionTypeId;
/* originName is read only*/
private String originName;
/*persited*/
private Long originId;
/* preservationMediumName is read only*/
private String preservationMediumName;
/*persited*/
private Long preservationMediumId;
/* storageTypeName is read only*/
private String storageTypeName;
/*persited*/
private Long storageTypeId;
/*persited*/
private Long numberFragments;
/*persited*/
private boolean discarded;
//Added to generate specimens
private Long certaintyLevel;
private Date dateTime;
/*persited ignoring the valueName of the SelectionListDTO's*/
private List<LifeStageSexDTO> lifeStageSexList;
private String gathObsDetailNumber;
private Long collectorGathObsDetail;
private String collectorNameGathObsDetail;
/** For Quering purposes **/
private Integer radio;
private Double latitude;
private Double longitude;
public SpecimenDTO() {
}
@Override
public String toString() {
String lssToString="";
if(getLifeStageSexList() != null)
{
for(LifeStageSexDTO lssDTO :getLifeStageSexList() )
lssToString = lssToString + lssDTO.toString();
}
return "SpecimenDTO" +
"\n\tSpecimen id = " + specimenKey +
"\n\tCatalog number = " + getCatalogNumber() +
"\n\tInstitution code = " + institutionCode +
"\n\tInstitution id = " + institutionId +
"\n\tCollection name = " + collectionName +
"\n\tCollection id = " + collectionId +
"\n\tspecimen Type Id = " + this.getTypeId() +
"\n\tspecimen Type Name = " + this.getTypeName() +
"\n\tspecimen Category Id = " + this.getCategoryId() +
"\n\tspecimen Category Name = " + this.getCategoryName() +
"\n\tTaxon name = " + taxonName +
"\n\tLocality = " + localityDescription +
"\n\tCoordinates = " + coordinates +
"\n\tCountry name = " + countryName +
"\n\tCountry id = " + countryId +
"\n\tProvince name = " + provinceName +
"\n\tProvince id = " + provinceId +
"\n\tResponsible = " + responsibleName+
"\n\tLongitude = " + getLongitude()+
"\n\tLatitude = " + getLatitude()+
"\n\tRadio = " + getRadio()+
"\n\tDiscarted = " + isDiscarded()+
"\n\tDateTime = " +dateTime+
"\n\tLifeStafeSexDTO = \n" + lssToString +
"\n\tlabelID = " + labelId +
"\n\tOriginalLabelID = " +originalLabelId
;
}
/**
* @return the collectionName
*/
public String getCollectionName() {
return collectionName;
}
/**
* @param collectionName the collectionName to set
*/
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
public String getCoordinates() {
return coordinates;
}
public void setCoordinates(String coordinates) {
this.coordinates = coordinates;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getInstitutionCode() {
return institutionCode;
}
public void setInstitutionCode(String institutionCode) {
this.institutionCode = institutionCode;
}
public String getLocalityDescription() {
return localityDescription;
}
public void setLocalityDescription(String localityDescription) {
this.localityDescription = localityDescription;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public Long getSpecimenKey() {
return specimenKey;
}
public void setSpecimenKey(Long specimenKey) {
this.specimenKey = specimenKey;
}
public String getTaxonName() {
return taxonName;
}
public void setTaxonName(String taxonName) {
this.taxonName = taxonName;
}
/**
* @return the selected
*/
public boolean isSelected() {
return selected;
}
/**
* @param selected the selected to set
*/
public void setSelected(boolean selected) {
this.selected = selected;
}
/**
* @return the catalogNumber
*/
public String getCatalogNumber() {
return catalogNumber;
}
/**
* @param catalogNumber the catalogNumber to set
*/
public void setCatalogNumber(String catalogNumber) {
this.catalogNumber = catalogNumber;
}
/**
* @return the institutionId
*/
public Long getInstitutionId() {
return institutionId;
}
/**
* @param institutionId the institutionId to set
*/
public void setInstitutionId(Long institutionId) {
this.institutionId = institutionId;
}
/**
* @return the collectionId
*/
public Long getCollectionId() {
return collectionId;
}
/**
* @param collectionId the collectionId to set
*/
public void setCollectionId(Long collectionId) {
this.collectionId = collectionId;
}
/**
* @return the taxonId
*/
public Long getTaxonId() {
return taxonId;
}
/**
* @param taxonId the taxonId to set
*/
public void setTaxonId(Long taxonId) {
this.taxonId = taxonId;
}
/**
* @return the responsibleId
*/
public Long getResponsibleId() {
return responsibleId;
}
/**
* @param responsibleId the responsibleId to set
*/
public void setResponsibleId(Long responsibleId) {
this.responsibleId = responsibleId;
}
/**
* @return the countryId
*/
public Long getCountryId() {
return countryId;
}
/**
* @param countryId the countryId to set
*/
public void setCountryId(Long countryId) {
this.countryId = countryId;
}
/**
* @return the provinceId
*/
public Long getProvinceId() {
return provinceId;
}
/**
* @param provinceId the provinceId to set
*/
public void setProvinceId(Long provinceId) {
this.provinceId = provinceId;
}
/**
* @return the responsibleName
*/
public String getResponsibleName() {
return responsibleName;
}
/**
* @param responsibleName the responsibleName to set
*/
public void setResponsibleName(String responsibleName) {
this.responsibleName = responsibleName;
}
/**
* @return the gatheringObsevationId
*/
public Long getGatheringObsevationId() {
return gatheringObsevationId;
}
/**
* @param gatheringObsevationId the gatheringObsevationId to set
*/
public void setGatheringObsevationId(Long gatheringObsevationId) {
this.gatheringObsevationId = gatheringObsevationId;
}
/**
* @return the categoryName
*/
public String getCategoryName() {
return categoryName;
}
/**
* @param categoryName the categoryName to set
*/
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
/**
* @return the categoryId
*/
public Long getCategoryId() {
return categoryId;
}
/**
* @param categoryId the categoryId to set
*/
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
/**
* @return the extractionTypeName
*/
public String getExtractionTypeName() {
return extractionTypeName;
}
/**
* @param extractionTypeName the extractionTypeName to set
*/
public void setExtractionTypeName(String extractionTypeName) {
this.extractionTypeName = extractionTypeName;
}
/**
* @return the extractionTypeId
*/
public Long getExtractionTypeId() {
return extractionTypeId;
}
/**
* @param extractionTypeId the extractionTypeId to set
*/
public void setExtractionTypeId(Long extractionTypeId) {
this.extractionTypeId = extractionTypeId;
}
/**
* @return the typeName
*/
public String getTypeName() {
return typeName;
}
/**
* @param typeName the typeName to set
*/
public void setTypeName(String typeName) {
this.typeName = typeName;
}
/**
* @return the typeId
*/
public Long getTypeId() {
return typeId;
}
/**
* @param typeId the typeId to set
*/
public void setTypeId(Long typeId) {
this.typeId = typeId;
}
/**
* @return the originName
*/
public String getOriginName() {
return originName;
}
/**
* @param originName the originName to set
*/
public void setOriginName(String originName) {
this.originName = originName;
}
/**
* @return the originId
*/
public Long getOriginId() {
return originId;
}
/**
* @param originId the originId to set
*/
public void setOriginId(Long originId) {
this.originId = originId;
}
/**
* @return the preservationMediumName
*/
public String getPreservationMediumName() {
return preservationMediumName;
}
/**
* @param preservationMediumName the preservationMediumName to set
*/
public void setPreservationMediumName(String preservationMediumName) {
this.preservationMediumName = preservationMediumName;
}
/**
* @return the preservationMediumId
*/
public Long getPreservationMediumId() {
return preservationMediumId;
}
/**
* @param preservationMediumId the preservationMediumId to set
*/
public void setPreservationMediumId(Long preservationMediumId) {
this.preservationMediumId = preservationMediumId;
}
/**
* @return the storageTypeName
*/
public String getStorageTypeName() {
return storageTypeName;
}
/**
* @param storageTypeName the storageTypeName to set
*/
public void setStorageTypeName(String storageTypeName) {
this.storageTypeName = storageTypeName;
}
/**
* @return the storageTypeId
*/
public Long getStorageTypeId() {
return storageTypeId;
}
/**
* @param storageTypeId the storageTypeId to set
*/
public void setStorageTypeId(Long storageTypeId) {
this.storageTypeId = storageTypeId;
}
/**
* @return the numberWhole
*/
public Long getNumberWhole() {
return numberWhole;
}
/**
* @param numberWhole the numberWhole to set
*/
public void setNumberWhole(Long numberWhole) {
this.numberWhole = numberWhole;
}
/**
* @return the gatheringMethodName
*/
public String getGatheringMethodName() {
return gatheringMethodName;
}
/**
* @param gatheringMethodName the gatheringMethodName to set
*/
public void setGatheringMethodName(String gatheringMethodName) {
this.gatheringMethodName = gatheringMethodName;
}
/**
* @return the gatheringMethodId
*/
public Long getGatheringMethodId() {
return gatheringMethodId;
}
/**
* @param gatheringMethodId the gatheringMethodId to set
*/
public void setGatheringMethodId(Long gatheringMethodId) {
this.gatheringMethodId = gatheringMethodId;
}
/**
* @return the numberFragments
*/
public Long getNumberFragments() {
return numberFragments;
}
/**
* @param numberFragments the numberFragments to set
*/
public void setNumberFragments(Long numberFragments) {
this.numberFragments = numberFragments;
}
/**
* @return the discarded
*/
public boolean isDiscarded() {
return discarded;
}
/**
* @param discarded the discarded to set
*/
public void setDiscarded(boolean discarded) {
this.discarded = discarded;
}
/**
* @return the lifeStageSexList
*/
public List<LifeStageSexDTO> getLifeStageSexList() {
return lifeStageSexList;
}
/**
* @param lifeStageSexList the lifeStageSexList to set
*/
public void setLifeStageSexList(List<LifeStageSexDTO> lifeStageSexList) {
this.lifeStageSexList = lifeStageSexList;
}
/**
* @return the radio
*/
public Integer getRadio() {
return radio;
}
/**
* @param radio the radio to set
*/
public void setRadio(Integer radio) {
this.radio = radio;
}
/**
* @return the latitude
*/
public Double getLatitude() {
return latitude;
}
/**
* @param latitude the latitude to set
*/
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/**
* @return the longitude
*/
public Double getLongitude() {
return longitude;
}
/**
* @param longitude the longitude to set
*/
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
/**
* @return the substrateName
*/
public String getSubstrateName() {
return substrateName;
}
/**
* @param substrateName the substrateName to set
*/
public void setSubstrateName(String substrateName) {
this.substrateName = substrateName;
}
/**
* @return the substrateId
*/
public Long getSubstrateId() {
return substrateId;
}
/**
* @param substrateId the substrateId to set
*/
public void setSubstrateId(Long substrateId) {
this.substrateId = substrateId;
}
/**
* @return the gatheringObservationDetailId
*/
public Long getGatheringObservationDetailId() {
return gatheringObservationDetailId;
}
/**
* @param gatheringObservationDetailId the gatheringObservationDetailId to set
*/
public void setGatheringObservationDetailId(Long gatheringObservationDetailId) {
this.gatheringObservationDetailId = gatheringObservationDetailId;
}
/**
* @return the certaintyLevel
*/
public Long getCertaintyLevel() {
return certaintyLevel;
}
/**
* @param certaintyLevel the certaintyLevel to set
*/
public void setCertaintyLevel(Long certaintyLevel) {
this.certaintyLevel = certaintyLevel;
}
/**
* @return the dateTime
*/
public Date getDateTime() {
return dateTime;
}
/**
* @param dateTime the dateTime to set
*/
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
/**
* @return the labelID
*/
public Long getLabelId() {
return labelId;
}
/**
* @param labelID the labelID to set
*/
public void setLabelId(Long labelId) {
this.labelId = labelId;
}
/**
* @return the originalLabelId
*/
public Long getOriginalLabelId() {
return originalLabelId;
}
/**
* @param originalLabelId the originalLabelId to set
*/
public void setOriginalLabelId(Long originalLabelId) {
this.originalLabelId = originalLabelId;
}
/**
* @return the gathObsDetailNumber
*/
public String getGathObsDetailNumber() {
return gathObsDetailNumber;
}
/**
* @param gathObsDetailNumber the gathObsDetailNumber to set
*/
public void setGathObsDetailNumber(String gathObsDetailNumber) {
this.gathObsDetailNumber = gathObsDetailNumber;
}
/**
* @return the collectorGathObsDetail
*/
public Long getCollectorGathObsDetail() {
return collectorGathObsDetail;
}
/**
* @param collectorGathObsDetail the collectorGathObsDetail to set
*/
public void setCollectorGathObsDetail(Long collectorGathObsDetail) {
this.collectorGathObsDetail = collectorGathObsDetail;
}
/**
* @return the collectorNameGathObsDetail
*/
public String getCollectorNameGathObsDetail() {
return collectorNameGathObsDetail;
}
/**
* @param collectorNameGathObsDetail the collectorNameGathObsDetail to set
*/
public void setCollectorNameGathObsDetail(String collectorNameGathObsDetail) {
this.collectorNameGathObsDetail = collectorNameGathObsDetail;
}
}
|
package slimeknights.tconstruct.smeltery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMap;
import net.minecraft.item.Item;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import slimeknights.tconstruct.common.ClientProxy;
import slimeknights.tconstruct.common.config.Config;
import slimeknights.tconstruct.library.client.CustomTextureCreator;
import slimeknights.tconstruct.smeltery.block.BlockSearedGlass;
import slimeknights.tconstruct.smeltery.block.BlockSmelteryIO;
import slimeknights.tconstruct.smeltery.block.BlockTank;
import slimeknights.tconstruct.smeltery.client.CastingRenderer;
import slimeknights.tconstruct.smeltery.client.ChannelRenderer;
import slimeknights.tconstruct.smeltery.client.FaucetRenderer;
import slimeknights.tconstruct.smeltery.client.SmelteryRenderer;
import slimeknights.tconstruct.smeltery.client.TankRenderer;
import slimeknights.tconstruct.smeltery.client.TinkerTankRenderer;
import slimeknights.tconstruct.smeltery.tileentity.TileCastingBasin;
import slimeknights.tconstruct.smeltery.tileentity.TileCastingTable;
import slimeknights.tconstruct.smeltery.tileentity.TileChannel;
import slimeknights.tconstruct.smeltery.tileentity.TileFaucet;
import slimeknights.tconstruct.smeltery.tileentity.TileSmeltery;
import slimeknights.tconstruct.smeltery.tileentity.TileTank;
import slimeknights.tconstruct.smeltery.tileentity.TileTinkerTank;
import static slimeknights.tconstruct.common.ModelRegisterUtil.registerItemBlockMeta;
import static slimeknights.tconstruct.common.ModelRegisterUtil.registerItemModel;
public class SmelteryClientProxy extends ClientProxy {
@Override
public void preInit() {
super.preInit();
MinecraftForge.EVENT_BUS.register(new SmelteryClientEvents());
}
@Override
public void registerModels() {
// ignore color state for the clear stained glass, it is handled by tinting
ModelLoader.setCustomStateMapper(TinkerSmeltery.searedGlass, (new StateMap.Builder()).ignore(BlockSearedGlass.TYPE).build());
// Blocks
registerItemModel(TinkerSmeltery.smelteryController);
registerItemModel(TinkerSmeltery.faucet);
registerItemModel(TinkerSmeltery.channel);
registerItemModel(TinkerSmeltery.searedGlass);
registerItemModel(TinkerSmeltery.searedFurnaceController);
registerItemModel(TinkerSmeltery.tinkerTankController);
registerItemBlockMeta(TinkerSmeltery.searedBlock);
registerItemBlockMeta(TinkerSmeltery.castingBlock);
// slabs
registerItemBlockMeta(TinkerSmeltery.searedSlab);
registerItemBlockMeta(TinkerSmeltery.searedSlab2);
// stairs
registerItemModel(TinkerSmeltery.searedStairsStone);
registerItemModel(TinkerSmeltery.searedStairsCobble);
registerItemModel(TinkerSmeltery.searedStairsPaver);
registerItemModel(TinkerSmeltery.searedStairsBrick);
registerItemModel(TinkerSmeltery.searedStairsBrickCracked);
registerItemModel(TinkerSmeltery.searedStairsBrickFancy);
registerItemModel(TinkerSmeltery.searedStairsBrickSquare);
registerItemModel(TinkerSmeltery.searedStairsBrickTriangle);
registerItemModel(TinkerSmeltery.searedStairsBrickSmall);
registerItemModel(TinkerSmeltery.searedStairsRoad);
registerItemModel(TinkerSmeltery.searedStairsTile);
registerItemModel(TinkerSmeltery.searedStairsCreeper);
// drains
Item drain = Item.getItemFromBlock(TinkerSmeltery.smelteryIO);
for(BlockSmelteryIO.IOType type : BlockSmelteryIO.IOType.values()) {
String variant = String.format("%s=%s,%s=%s",
BlockSmelteryIO.FACING.getName(),
BlockSmelteryIO.FACING.getName(EnumFacing.SOUTH),
BlockSmelteryIO.TYPE.getName(),
BlockSmelteryIO.TYPE.getName(type)
);
ModelLoader.setCustomModelResourceLocation(drain, type.meta, new ModelResourceLocation(drain.getRegistryName(), variant));
}
// seared tank items
Item tank = Item.getItemFromBlock(TinkerSmeltery.searedTank);
for(BlockTank.TankType type : BlockTank.TankType.values()) {
String variant = String.format("%s=%s,%s=%s",
BlockTank.KNOB.getName(),
BlockTank.KNOB.getName(type == BlockTank.TankType.TANK),
BlockTank.TYPE.getName(),
BlockTank.TYPE.getName(type)
);
ModelLoader.setCustomModelResourceLocation(tank, type.meta, new ModelResourceLocation(tank.getRegistryName(), variant));
}
// TEs
ClientRegistry.bindTileEntitySpecialRenderer(TileTank.class, new TankRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileSmeltery.class, new SmelteryRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileTinkerTank.class, new TinkerTankRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileFaucet.class, new FaucetRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileChannel.class, new ChannelRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileCastingTable.class, new CastingRenderer.Table());
ClientRegistry.bindTileEntitySpecialRenderer(TileCastingBasin.class, new CastingRenderer.Basin());
// Items
final ResourceLocation castLoc = SmelteryClientEvents.locBlankCast;
CustomTextureCreator.castModelLocation = new ResourceLocation(castLoc.getResourceDomain(), "item/" + castLoc.getResourcePath());
ModelLoader.setCustomMeshDefinition(TinkerSmeltery.cast, new PatternMeshDefinition(castLoc));
if(Config.claycasts) {
final ResourceLocation clayCastLoc = SmelteryClientEvents.locClayCast;
CustomTextureCreator.castModelLocation = new ResourceLocation(clayCastLoc.getResourceDomain(),
"item/" + clayCastLoc.getResourcePath());
ModelLoader.setCustomMeshDefinition(TinkerSmeltery.clayCast, new PatternMeshDefinition(clayCastLoc));
}
TinkerSmeltery.castCustom.registerItemModels();
}
}
|
package com.example.agenda.ui.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.example.agenda.R;
import com.example.agenda.model.dao.AlunoDAO;
import com.example.agenda.model.entity.Aluno;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class ListaAlunosActivity extends AppCompatActivity {
public static final String titulo_appbar = "Lista de alunos";
private final AlunoDAO alunoDao = new AlunoDAO();
private ArrayAdapter<Aluno> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
setTitle(titulo_appbar);
configuraBotaoSalvarAluno();
configuraListaDeAlunos();
alunoDao.salva(new Aluno("william", "122312", "william@email.com"));
alunoDao.salva(new Aluno("giovana", "122312", "gi@email.com"));
}
@Override
protected void onResume() {
super.onResume();
adapter.clear();
adapter.addAll(alunoDao.getAlunos());
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.activity_lista_alunos_menu, menu);
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.activity_lista_alunos_menu_remover) {
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Aluno alunoEscolhido = adapter.getItem(menuInfo.position);
deletarCaixaDeDialogo(alunoEscolhido.getId(), alunoEscolhido);
}
return super.onContextItemSelected(item);
}
private void configuraBotaoSalvarAluno() {
FloatingActionButton botaoSalvarNovoAluno = findViewById(R.id.activity_lista_alunos_fab_novo_aluno);
botaoSalvarNovoAluno.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
abreFormNovoAluno();
}
});
}
private void abreFormNovoAluno() {
startActivity(new Intent(ListaAlunosActivity.this,
FormAlunoActivity.class));
}
private void configuraListaDeAlunos() {
ListView listaDeALunos = findViewById(R.id.activity_lista_de_alunos_list_view);
final List<Aluno> alunos = alunoDao.getAlunos();
configuraAdapterList(listaDeALunos, alunos);
configuraListenerDeCliquePorItem(listaDeALunos, alunos);
registerForContextMenu(listaDeALunos);
}
private void configuraListenerDeCliquePorItem(ListView listaDeALunos, final List<Aluno> alunos) {
listaDeALunos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Aluno alunoEscolhido = alunos.get(position);
Intent vaiParaFormNovoAluno = new Intent(ListaAlunosActivity.this,
FormAlunoActivity.class);
vaiParaFormNovoAluno.putExtra("aluno", alunoEscolhido);
startActivity(vaiParaFormNovoAluno);
}
});
}
private void configuraAdapterList(ListView listaDeALunos, List<Aluno> alunos) {
adapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
alunos);
listaDeALunos.setAdapter(adapter);
}
private void deletarCaixaDeDialogo(final int position, final Aluno aluno) {
new AlertDialog.Builder(this)
.setTitle("Deletando aluno")
.setMessage("Tem certeza que deseja deletar o aluno")
.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alunoDao.remove(aluno);
adapter.remove(aluno);
}
})
.setNegativeButton("Não", null)
.show();
}
}
|
package com.company.model;
/**
* Created by abalamanova on May, 2019
*/
public enum Fee {
PREMIUM("Premium fee", 40),
REGULAR("Regular fee", 30);
private final String type;
private final int cost;
Fee(final String type, int cost) {
this.type = type;
this.cost = cost;
}
public int getCost() {
return cost;
}
public String getType() {
return type;
}
}
|
package com.poi.test;
import com.deepoove.poi.XWPFTemplate;
import java.io.*;
import java.util.HashMap;
public class poimain {
public static void main(String[] args) throws IOException {
//创建输入流
// FileInputStream in = new FileInputStream(new File("a.docx"));
XWPFTemplate template = XWPFTemplate.compile("a.docx").render(new HashMap<String, Object>(){{
put("title", "Pil-tl 模板引擎AccLM");
}});
FileOutputStream out = new FileOutputStream("b.docx");
template.write(out);
out.flush();
out.close();
template.close();
// in.close(); //关闭输入流
}
}
|
package com.sirma.itt.javacourse.threads.task7.producerconsumer;
import org.apache.log4j.Logger;
/**
* Thread class that produces a resource and supplies it to a warehouse. The thread produces a
* specified quantity of the product at regular intervals if the product has reached maximum supply
* it waits for some of it to be consumed.
*
* @author Simeon Iliev
*/
public class Producer extends Thread {
private static final Logger LOGGER = Logger.getLogger(Producer.class);
private static int numThreads = 0;
private final Product product;
private final long productionTime;
private final int supply;
private final int threadNumber;
/**
* Constructor for the thread.
*
* @param product
* the product this thread produces.
* @param productionTime
* the time it takes the thread to produce the supply.
* @param supply
* the supply that this thread can provide.
*/
public Producer(Product product, long productionTime, int supply) {
this.product = product;
this.productionTime = productionTime;
this.supply = supply;
threadNumber = numThreads++;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(productionTime);
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
LOGGER.info(Producer.class.getName() + " : " + threadNumber);
product.deliverProduct(supply);
synchronized (product) {
product.notify();
try {
product.wait();
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
}
|
package com.blog.bean;
public class ContentManageBean {
private int contentId; //博客标识
private String contentTitle; //博客标题
private String ContentMessage; //博客内容
private int contentNum; //浏览次数
private String contentDate;//发布日期
private String contentType; //文章类别
public int getContentId() {
return contentId;
}
public void setContentId(int contentId) {
this.contentId = contentId;
}
public String getContentTitle() {
return contentTitle;
}
public void setContentTitle(String contentTitle) {
this.contentTitle = contentTitle;
}
public String getContentMessage() {
return ContentMessage;
}
public void setContentMessage(String contentMessage) {
ContentMessage = contentMessage;
}
public int getContentNum() {
return contentNum;
}
public void setContentNum(int contentNum) {
this.contentNum = contentNum;
}
public String getContentDate() {
return contentDate;
}
public void setContentDate(String countDate) {
this.contentDate = countDate;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
|
/*
* 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 com.forgerock.sapi.gateway.ob.uk.common.datamodel.converter.common;
import com.forgerock.sapi.gateway.ob.uk.common.datamodel.common.FRExternalPaymentContextCode;
import uk.org.openbanking.datamodel.common.OBExternalPaymentContext1Code;
public class FROBExternalPaymentContext1CodeConverter {
public static FRExternalPaymentContextCode toFRExternalPaymentContextCode(OBExternalPaymentContext1Code obExternalPaymentContext1Code) {
return obExternalPaymentContext1Code == null ? null : FRExternalPaymentContextCode.valueOf(obExternalPaymentContext1Code.name());
}
public static OBExternalPaymentContext1Code toOBExternalPaymentContext1Code(FRExternalPaymentContextCode frExternalPaymentContextCode) {
return frExternalPaymentContextCode == null ? null : OBExternalPaymentContext1Code.valueOf(frExternalPaymentContextCode.name());
}
}
|
package com.gsccs.sme.plat.site.dao;
import com.gsccs.sme.plat.site.model.ContentAttachT;
import com.gsccs.sme.plat.site.model.ContentAttachTExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ContentAttachTMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
int countByExample(ContentAttachTExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
int deleteByExample(ContentAttachTExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
int insert(ContentAttachT record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
int insertSelective(ContentAttachT record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
List<ContentAttachT> selectByExample(ContentAttachTExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
ContentAttachT selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
int updateByExampleSelective(@Param("record") ContentAttachT record, @Param("example") ContentAttachTExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
int updateByExample(@Param("record") ContentAttachT record, @Param("example") ContentAttachTExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
int updateByPrimaryKeySelective(ContentAttachT record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sme_info_attach
*
* @mbggenerated Thu Mar 10 17:51:32 CST 2016
*/
int updateByPrimaryKey(ContentAttachT record);
}
|
/**
*
*/
package com.egame.beans;
/**
* 描述:帮助中心列表的实体bean
*
* @author LiuHan
* @version 1.0 create date 2011-12-29
*/
public class HelpListBean {
/** 主题名称 */
private String helpItemName;
/** 查看的次数 */
private String accessNumber;
public String getHelpItemName() {
return helpItemName;
}
public void setHelpItemName(String helpItemName) {
this.helpItemName = helpItemName;
}
public String getAccessNumber() {
return accessNumber;
}
public void setAccessNumber(String accessNumber) {
this.accessNumber = accessNumber;
}
}
|
package com.szakdolgozat.service;
public interface PostCodeService {
boolean checkPostCodeAndCity(int postCode, String city);
}
|
package p;
public class Type {
public static int count = 0;
}
|
package ${package};
import ${package}.AppApplication;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes= {AppApplication.class})
public abstract class BaseTest {
}
|
package src.com.xebia.tondeuse.object;
import org.apache.commons.lang3.StringUtils;
import src.com.xebia.tondeuse.commun.OrientationEnum;
public class Tondeuse{
private int numero;
private int positionX;
private int positionY;
private OrientationEnum orientationEnum;
private Surface surface;
public Tondeuse() {
}
public Tondeuse(int numero, int positionX, int positionY,
OrientationEnum orientationEnum, Surface surface) {
this.surface = surface;
this.numero = numero;
this.positionX = positionX;
this.positionY = positionY;
this.orientationEnum = orientationEnum;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public int getPositionX() {
return positionX;
}
public void setPositionX(int positionX) {
this.positionX = positionX;
}
public int getPositionY() {
return positionY;
}
public void setPositionY(int positionY) {
this.positionY = positionY;
}
public OrientationEnum getOrientationEnum() {
return orientationEnum;
}
public void setOrientationEnum(OrientationEnum orientationEnum) {
this.orientationEnum = orientationEnum;
}
public Surface getSurface() {
return surface;
}
public void setSurface(Surface surface) {
this.surface = surface;
}
@Override
public String toString() {
StringBuilder sbTondeuse = new StringBuilder(StringUtils.EMPTY);
sbTondeuse.append(this.getPositionX());
sbTondeuse.append(StringUtils.SPACE);
sbTondeuse.append(this.getPositionY());
sbTondeuse.append(StringUtils.SPACE);
if (this.getOrientationEnum() != null) {
sbTondeuse.append(this.getOrientationEnum().getOrientation());
}
//sbTondeuse.append(TondeuseUtils.SAUT_DE_LIGNE);
return sbTondeuse.toString();
}
}
|
package com.atguigu.java;
import static org.junit.Assert.*;
import java.util.List;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ZookeeperWatcherTest {
private String connectString="hadoop101:2181,hadoop102:2181,hadoop103:2181";
private int sessionTimeout=30000;
private ZooKeeper zooKeeper;
@Before
public void init() throws Exception {
//创建zookeeper客户端,需要提供一个默认的观察者,
//当执行设置默认观察者时,如果没有设置,就使用默认的观察者
zooKeeper=new ZooKeeper(connectString, sessionTimeout, new Watcher() {
//当监听的节点发生指定的事件时,自动通知watcher 调用其process()方法
@Override
public void process(WatchedEvent event) {
System.out.println("调用了默认观察者的process()方法");
System.out.println(event.getPath()+"发生了事件:"+ event.getType());
//发生事件后重新读取数据
try {
//持续监听 在回调方法中继续设置观察者
List<String> children = zooKeeper.getChildren("/hi", true);
System.out.println(children);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
}
});
}
@After
public void closeZk() throws Exception {
if (zooKeeper != null) {
zooKeeper.close();
}
}
@Test
public void lsWatch() throws Exception {
List<String> children = zooKeeper.getChildren("/hi", true);
System.out.println(children);
while (true) {
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+"运行中...");
}
}
@Test
public void getWatch() throws Exception {
}
}
|
package filippov.vitaliy.poibms3_8.Base;
public abstract class Constants {
public static String TAG = "MyProjectCar";
public static String[] typeFuel;
public static final String EVENTS = "/data/user/0/filippov.vitaliy.poibms3_8/Events.xml";
public static final String Category_JSON = "/data/user/0/filippov.vitaliy.poibms3_8/Category.json";
}
|
package controllers;
import java.io.File;
import java.util.ArrayList;
import models.Product;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
import util.AppConst;
import util.ParseSpreadsheet;
import views.html.setInventory.*;
public class PushData extends Controller {
public static Result uploadPage() {
return ok(uploadproduct.render());
}
public static Result xlsupload(){
MultipartFormData body = request().body().asMultipartFormData();
FilePart uploaded_file = body.getFile("uploaded_file");
//if (uploaded_file == null || !uploaded_file.getContentType().equals("application/vnd.ms-excel")) {
String fileName="";
if(uploaded_file == null) {
flash("FLASH_ERROR_UPLOAD", "Sorry, there was some problem. Please try again after some time");
return redirect(routes.PushData.uploadPage());
} else {
String filename = uploaded_file.getFilename();
String extension = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
String excel = "xlsx";
if(!extension.equals(excel)){
flash("FLASH_ERROR_UPLOAD", "Sorry, please upload .xlsx file");
return redirect(routes.PushData.uploadPage());
}
File fileXls = uploaded_file.getFile();
String fileNameXls = uploaded_file.getFilename();
String path = AppConst.EXCEL_UPLOAD_DIR + fileNameXls;
ArrayList<ArrayList<String>> spContents = new ParseSpreadsheet().getDataFromSpreadsheet(fileXls);
System.out.println("PARSED EXCEL Total Content: "+spContents.size());
boolean isParsed = false;
if(!spContents.isEmpty())
isParsed = true;
try{
for(ArrayList<String> content:spContents){
Product p = new Product();
p.productName = content.get(0);
p.productCode = content.get(1);
p.productPrice = Float.parseFloat(content.get(2));
p.productQty = Float.parseFloat(content.get(3));
Product pr=Product.getProduct(p);
if(pr!=null){
p.id =pr.id;
Product.update(p);
}else{
Product.create(p);
}
}
}catch(Exception e){
isParsed = false;
}
if(isParsed){
flash("FLASH_SUCCESS_UPLOAD", "Uploaded and saved to Database");
return redirect(routes.PushData.uploadPage());
}else{
flash("FLASH_ERROR_UPLOAD", "EXCEL Format is not right");
return redirect(routes.PushData.uploadPage());
}
}
}
}
|
public class Main {
public static void main(String[] args) {
System.out.println(sumFirstAndLastDigit(5));
}
public static int sumFirstAndLastDigit(int number){
if(number<0){
return -1;
}
int count = 0 ;
int num = number;
int lastDigit = number % 10;
while(number>0){
number = number /10;
count++;
}
while (count>1){
num = num / 10;
count--;
}
return num + lastDigit;
}
}
|
package com.goodformentertainment.canary.r2w;
import net.canarymod.config.Configuration;
import net.visualillusionsent.utils.PropertiesFile;
public class ReturnConfig {
private final PropertiesFile cfg;
public ReturnConfig(final ReturnPlugin plugin) {
cfg = Configuration.getPluginConfig(plugin);
}
// public String getHubWorld() {
// return cfg.getString("hubWorld", "default");
// }
//
// public String getWorldName() {
// return cfg.getString("worldName", "xis");
// }
//
// public int getMaxSize() {
// return cfg.getInt("maxSize", 100);
// }
//
// public int getHeight() {
// return cfg.getInt("islandHeight", 64);
// }
}
|
package com.alibaba.druid.bvt.pool;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.Statement;
import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.filter.FilterAdapter;
import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledStatement;
import com.alibaba.druid.proxy.jdbc.ResultSetProxy;
import com.alibaba.druid.proxy.jdbc.StatementProxy;
public class DruidPooledStatementTest extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setTestOnBorrow(false);
dataSource.getProxyFilters().add(new ErrorFilter());
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_executeQuery_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.executeQuery("select 1");
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_executeUpdate_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.executeUpdate("select 1");
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_executeUpdate_error_1() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.executeUpdate("select 1", Statement.RETURN_GENERATED_KEYS);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_executeUpdate_error_2() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.executeUpdate("select 1", new int[0]);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_executeUpdate_error_3() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.executeUpdate("select 1", new String[0]);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_execute_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.execute("select 1");
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_execute_error_1() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.execute("select 1", Statement.RETURN_GENERATED_KEYS);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_execute_error_2() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.execute("select 1", new int[0]);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_execute_error_3() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.execute("select 1", new String[0]);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getMaxFieldSize_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getMaxFieldSize();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_setMaxFieldSize_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.setMaxFieldSize(0);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getMaxRows_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getMaxRows();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_setMaxRows_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.setMaxRows(0);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_setEscapeProcessing_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.setEscapeProcessing(true);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getQueryTimeout_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getQueryTimeout();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_setQueryTimeout_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.setQueryTimeout(-1);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_cancel_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.cancel();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getWarnings_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getWarnings();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_clearWarnings_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.clearWarnings();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_setCursorName_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.setCursorName(null);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getResultSet_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getResultSet();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getDataSourceStat().getResultSetStat().getOpenCount());
}
public void test_getUpdateCount_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getUpdateCount();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getMoreResults_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getMoreResults();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_setFetchDirection_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.setFetchDirection(0);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getFetchDirection_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getFetchDirection();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_setFetchSize_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.setFetchSize(0);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getFetchSize_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getFetchSize();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getResultSetConcurrency_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getResultSetConcurrency();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getResultSetType_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getResultSetType();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_addBatch_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.addBatch("select 1");
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_clearBatch_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.clearBatch();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_executeBatch_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.executeBatch();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getMoreResults_error_1() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getMoreResults(0);
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getGeneratedKeys_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getGeneratedKeys();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_getResultSetHoldability_error() throws Exception {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.getResultSetHoldability();
} catch (Exception e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(1, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_closeOnCompletion_error() throws Exception {
Connection conn = dataSource.getConnection();
DruidPooledStatement stmt = (DruidPooledStatement) conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.closeOnCompletion();
} catch (SQLFeatureNotSupportedException e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(0, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
public void test_isCloseOnCompletion_error() throws Exception {
Connection conn = dataSource.getConnection();
DruidPooledStatement stmt = (DruidPooledStatement) conn.createStatement();
Assert.assertEquals(0, dataSource.getPoolingCount());
Assert.assertEquals(1, dataSource.getActiveCount());
Assert.assertEquals(0, dataSource.getErrorCount());
Exception error = null;
try {
stmt.isCloseOnCompletion();
} catch (SQLFeatureNotSupportedException e) {
error = e;
}
Assert.assertNotNull(error);
Assert.assertEquals(0, dataSource.getErrorCount());
stmt.close();
conn.close();
Assert.assertEquals(1, dataSource.getPoolingCount());
Assert.assertEquals(0, dataSource.getActiveCount());
}
private final class ErrorFilter extends FilterAdapter {
@Override
public ResultSetProxy statement_executeQuery(FilterChain chain, StatementProxy statement, String sql)
throws SQLException {
throw new SQLException();
}
@Override
public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql) throws SQLException {
throw new SQLException();
}
@Override
public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql,
int autoGeneratedKeys) throws SQLException {
throw new SQLException();
}
@Override
public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql, int[] columnIndexes)
throws SQLException {
throw new SQLException();
}
@Override
public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql,
String[] columnNames) throws SQLException {
throw new SQLException();
}
@Override
public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql) throws SQLException {
throw new SQLException();
}
@Override
public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql, int autoGeneratedKeys)
throws SQLException {
throw new SQLException();
}
@Override
public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql, int[] columnIndexes)
throws SQLException {
throw new SQLException();
}
@Override
public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql, String[] columnNames)
throws SQLException {
throw new SQLException();
}
@Override
public int statement_getMaxFieldSize(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public int statement_getMaxRows(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public void statement_setMaxFieldSize(FilterChain chain, StatementProxy statement, int max) throws SQLException {
throw new SQLException();
}
@Override
public void statement_setMaxRows(FilterChain chain, StatementProxy statement, int max) throws SQLException {
throw new SQLException();
}
@Override
public void statement_setEscapeProcessing(FilterChain chain, StatementProxy statement, boolean enable)
throws SQLException {
throw new SQLException();
}
@Override
public int statement_getQueryTimeout(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public void statement_setQueryTimeout(FilterChain chain, StatementProxy statement, int seconds)
throws SQLException {
throw new SQLException();
}
@Override
public void statement_cancel(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public SQLWarning statement_getWarnings(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public void statement_clearWarnings(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public void statement_setCursorName(FilterChain chain, StatementProxy statement, String name)
throws SQLException {
throw new SQLException();
}
@Override
public ResultSetProxy statement_getResultSet(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public int statement_getUpdateCount(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public boolean statement_getMoreResults(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public void statement_setFetchDirection(FilterChain chain, StatementProxy statement, int value)
throws SQLException {
throw new SQLException();
}
@Override
public int statement_getFetchDirection(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public int statement_getFetchSize(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public void statement_setFetchSize(FilterChain chain, StatementProxy statement, int value) throws SQLException {
throw new SQLException();
}
@Override
public int statement_getResultSetConcurrency(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public int statement_getResultSetType(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public void statement_addBatch(FilterChain chain, StatementProxy statement, String sql) throws SQLException {
throw new SQLException();
}
@Override
public void statement_clearBatch(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public int[] statement_executeBatch(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public boolean statement_getMoreResults(FilterChain chain, StatementProxy statement, int current)
throws SQLException {
throw new SQLException();
}
@Override
public ResultSetProxy statement_getGeneratedKeys(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
@Override
public int statement_getResultSetHoldability(FilterChain chain, StatementProxy statement) throws SQLException {
throw new SQLException();
}
}
}
|
package com.dassa.vo;
public class ShopMemberVO {
private String shopMemberIdx;
private String shopIdx;
private String shopMemberName;
private String shopMemberPhone;
private String shopMemberComment;
private String shopMemberImgName;
private String shopMemberImgPath;
private String shopMemberState;
private String shopMemberRegDate;
private String shopMemberLeaveDate;
public String getShopMemberIdx() {
return shopMemberIdx;
}
public void setShopMemberIdx(String shopMemberIdx) {
this.shopMemberIdx = shopMemberIdx;
}
public String getShopIdx() {
return shopIdx;
}
public void setShopIdx(String shopIdx) {
this.shopIdx = shopIdx;
}
public String getShopMemberName() {
return shopMemberName;
}
public void setShopMemberName(String shopMemberName) {
this.shopMemberName = shopMemberName;
}
public String getShopMemberPhone() {
return shopMemberPhone;
}
public void setShopMemberPhone(String shopMemberPhone) {
this.shopMemberPhone = shopMemberPhone;
}
public String getShopMemberComment() {
return shopMemberComment;
}
public void setShopMemberComment(String shopMemberComment) {
this.shopMemberComment = shopMemberComment;
}
public String getShopMemberImgName() {
return shopMemberImgName;
}
public void setShopMemberImgName(String shopMemberImgName) {
this.shopMemberImgName = shopMemberImgName;
}
public String getShopMemberImgPath() {
return shopMemberImgPath;
}
public void setShopMemberImgPath(String shopMemberImgPath) {
this.shopMemberImgPath = shopMemberImgPath;
}
public String getShopMemberState() {
return shopMemberState;
}
public void setShopMemberState(String shopMemberState) {
this.shopMemberState = shopMemberState;
}
public String getShopMemberRegDate() {
return shopMemberRegDate;
}
public void setShopMemberRegDate(String shopMemberRegDate) {
this.shopMemberRegDate = shopMemberRegDate;
}
public String getShopMemberLeaveDate() {
return shopMemberLeaveDate;
}
public void setShopMemberLeaveDate(String shopMemberLeaveDate) {
this.shopMemberLeaveDate = shopMemberLeaveDate;
}
}
|
package tools;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;
import struct.Node;
public class PrintUtils {
public static void toFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(
Config.out + "." + Config.format));
if (Config.verbose >= 1) {
System.out.println("Generating File : " + Config.out + "."
+ Config.format);
}
switch (Config.format) {
case "dot":
writer.write(ArbresToDot(Config.finalList, Config.out));
writer.close();
break;
case "txt":
writer.write(ArbresToText(Config.finalList));
writer.close();
break;
case "json":
System.out.println("not yet");
writer.close();
break;
case "png":
writer.write(ArbresToDot(Config.finalList, Config.out));
writer.close();
dotGenerator();
break;
default:
System.err
.println("unsupported format will generate the default format instead");
writer.write(ArbresToDot(Config.finalList, Config.out));
writer.close();
dotGenerator();
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String ArbresToDot(ArrayList<Node> list, String graphName) {
String res = "";
ArrayList<Node> tmp = labelNode(list, 0);
res = "graph " + graphName + "{ \n";
res += "node [shape=point] \n";
for (int i = 0; i < tmp.size(); i++) {
res += tmp.get(i).toDot();
}
res += "\n }";
return res;
}
public static String ArbreToDot(Node n, String graphName) {
Node labeled = labelNode(n, 0);
String res = null;
res = "graph " + graphName + "{ \n";
res += labeled.toDot();
res += "\n }";
return res;
}
public static String ArbresToText(ArrayList<Node> n) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n.size(); i++) {
sb.append("Arbre : " + i);
sb.append(ArbreToText(n.get(i)));
sb.append("\n");
}
return sb.toString();
}
public static String ArbreToText(Node n) {
Node labeled = labelNode(n, 0);
StringBuffer sb = new StringBuffer();
sb.append(labeled.getLabel());
sb.append("\n");
for (int i = 0; i < labeled.getFils().size(); i++) {
ArbreToTextTmp(labeled.getFils().get(i), 1, sb);
}
return sb.toString();
}
private static void ArbreToTextTmp(Node n, int nb, StringBuffer sb) {
for (int i = 0; i < nb; i++) {
sb.append(" ");
}
sb.append(n.getLabel());
sb.append("\n");
for (int i = 0; i < n.getFils().size(); i++) {
ArbreToTextTmp(n.getFils().get(i), nb + 1, sb);
}
}
private static Node labelNode(Node n, int start) {
Node label = ToolNode.clone(n);
Stack<Node> stack = new Stack<Node>();
stack.add(label);
int j = start;
while (!stack.isEmpty()) {
Node tmp = stack.pop();
tmp.setLabel(j + "");
for (int i = 0; i < tmp.getFils().size(); i++) {
stack.add(tmp.getFils().get(i));
}
j++;
}
return label;
}
private static ArrayList<Node> labelNode(ArrayList<Node> n, int start) {
ArrayList<Node> list = new ArrayList<Node>();
int j = start;
for (int i = 0; i < n.size(); i++) {
Node label = ToolNode.clone(n.get(i));
Stack<Node> stack = new Stack<Node>();
stack.add(label);
while (!stack.isEmpty()) {
Node tmp = stack.pop();
tmp.setLabel(j + "");
for (int z = 0; z < tmp.getFils().size(); z++) {
stack.add(tmp.getFils().get(z));
}
j++;
}
j++;
list.add(label);
}
return list;
}
private static void dotGenerator() {
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("which dot");
pr.waitFor();
boolean canDo = (pr.exitValue() == 0);
if (!canDo) {
System.err
.println("dot is not installed on this machine will not be able to generate png file");
} else {
if (Config.verbose >= 1) {
System.out.print("Generating Trees in format png......");
}
pr = Runtime.getRuntime().exec(
"dot -Tpng -o " + Config.out + ".png " + Config.out
+ "." + Config.format);
try {
pr.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException();
}
System.out.println("OK");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
/**
* This is a generated file. DO NOT EDIT ANY CODE HERE, YOUR CHANGES WILL BE LOST.
*/
package br.com.senior.furb.basico;
import br.com.senior.messaging.ErrorPayload;
import br.com.senior.messaging.model.CommandDescription;
import br.com.senior.messaging.model.CommandKind;
import br.com.senior.messaging.model.MessageHandler;
/**
* Response method for listGamePlayer
*/
@CommandDescription(name="listGamePlayerResponse", kind=CommandKind.ResponseCommand, requestPrimitive="listGamePlayerResponse")
public interface ListGamePlayerResponse extends MessageHandler {
void listGamePlayerResponse(GamePlayer.PagedResults response);
void listGamePlayerResponseError(ErrorPayload error);
}
|
package Factory;
public class GeraConta {
private ContaFactory conta;
public GeraConta(ContaFactory conta) {
this.conta = conta;
}
public Conta criaConta(String tipo) {
return conta.criaConta(tipo);
}
}
|
package com.baiwang.custom.web.interceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Author: gankunjian
* @Description:
* @Date: Created in 15:56 2018/7/18
* @Modified By:
*/
@Service
public class WSInterceptor {
@Value(value = "#{'${imageCenter.whiteList}'.split(',')}")
private List<String> whiteList;
@Value(value = "#{'${imageCenter.blackList}'.split(',')}")
private List<String> blackList;
/**
* <p>Discription:[允许访问的IP地址]</p>
*
* @return
*/
public List<String> getAllowedIPList() {
List<String> allowedIPList = new ArrayList<String>();
List<String> dealList = dealListMenu(whiteList);
if (dealList != null) {
allowedIPList.addAll(dealList);
}
return allowedIPList;
}
/**
* <p>Discription:[拒绝访问的IP地址]</p>
*
* @return
*/
public List<String> getDeniedIPList() {
List<String> deniedIPList = new ArrayList<String>();
List<String> dealList = dealListMenu(blackList);
if (dealList != null) {
deniedIPList.addAll(dealList);
}
return deniedIPList;
}
private List<String> dealListMenu(List<String> param) {
if (param != null && param.size() > 0) {
if (param.size() == 1 && "".equals(param.get(0))) {
return null;
}
}
return param;
}
}
|
package com.zjf.myself.codebase.fragment;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import com.zjf.myself.codebase.application.AppController;
import java.util.Timer;
import java.util.TimerTask;
public abstract class BaseFragment extends Fragment {
protected ViewGroup content;
protected Handler mMainHandler;
protected LayoutInflater inflater;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inflater = getActivity().getLayoutInflater();
content = (ViewGroup) inflater.inflate(layoutId(), null, false);
mMainHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
BaseFragment.this.handleMessage(msg);
return true;
}
});
if (getArguments() != null) {
initView(getArguments());
}else {
initView();
}
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
ViewGroup p = (ViewGroup) content.getParent();
if (p != null) {
p.removeAllViewsInLayout();
}
return content;
}
/**当fragment可视的时候才加载数据*/
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(getUserVisibleHint()){
loadInitData();
}
}
protected void loadInitData(){}
protected abstract void initView();
protected void initView(Bundle bundle){};
protected abstract int layoutId();
protected View findViewById(int id) {
return content.findViewById(id);
}
protected void handleMessage(Message msg) {
}
@Override
public void onDestroy() {
super.onDestroy();
AppController.cancelAll(this);
}
@Override
public void onResume() {
super.onResume();
// MobclickAgent.onResume(this.getActivity());
}
@Override
public void onPause() {
super.onPause();
// MobclickAgent.onPause(this.getActivity());
}
public Handler getMainHandler(){
return mMainHandler;
}
public Message obtainMessage() {
return mMainHandler.obtainMessage();
}
public Message obtainMessage(int what) {
return mMainHandler.obtainMessage(what);
}
public Message obtainMessage(int what, Object obj) {
return mMainHandler.obtainMessage(what, obj);
}
public Message obtainMessage(int what, int arg1, int arg2) {
return mMainHandler.obtainMessage(what, arg1, arg2);
}
public void post(Runnable r) {
mMainHandler.post(r);
}
public void keyBoardCancle() {
View view = getActivity().getWindow().peekDecorView();
if (view != null) {
InputMethodManager inputmanger = (InputMethodManager) getActivity().getSystemService(Activity
.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public void showKeyboard()
{
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 500);
}
}
|
package com.programapprentice.app;
import java.util.ArrayList;
import java.util.List;
/**
* User: program-apprentice
* Date: 8/21/15
* Time: 10:01 PM
*/
public class Combinations_77 {
public List<List<Integer>> combineWorder(int[] nums, int k, boolean[] rec, int start) {
List<List<Integer>> output = new ArrayList<List<Integer>>();
if(k == 0 || start == nums.length) {
return output;
}
for(int i = start; i < nums.length-k+1; i++) { // wrong for(int i = start; i < nums.length-k; i++) {
if(rec[i]) {
continue;
}
rec[i] = true;
List<List<Integer>> tmp = combineWorder(nums, k - 1, rec, i + 1);
if(tmp.isEmpty()) { // this check is important
List<Integer> e = new ArrayList<Integer>();
e.add(nums[i]);
output.add(e);
} else {
for (List<Integer> e : tmp) {
e.add(0, nums[i]);
output.add(e);
}
}
rec[i] = false;
}
return output;
}
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> output = new ArrayList<List<Integer>>();
if(k == 0 || n == 0) {
return output;
}
boolean[] rec = new boolean[n];
int[] nums = new int[n];
for(int i = 1; i <= n; i++) {
nums[i-1] = i;
}
return combineWorder(nums, k, rec, 0);
}
}
|
package org.reactome.web.nursa.client.details.tabs.dataset.widgets;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.IntegerBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class GseaConfigDisplay extends Composite {
private static final int DEF_NPERMS = 100;
static final Binder uiBinder = GWT.create(Binder.class);
/** The number of permutations. */
@UiField()
VerticalPanel container;
/** The number of permutations. */
@UiField()
IntegerBox nperms;
private GseaConfigSlider slider;
public GseaConfigDisplay() {
initWidget(uiBinder.createAndBindUi(this));
setStyleName(RESOURCES.getCSS().main());
// The config style must be defined in the global style.css
// file since it uses the third-party slider widget styles.
addStyleName("gsea-config");
nperms.setValue(DEF_NPERMS);
// Make the slider.
slider = new GseaConfigSlider();
// Dip into the DOM to add the third-party slider.
container.getElement().appendChild(slider.getElement());
}
public Integer getNperms() {
return nperms.getValue();
}
public int[] getDataSetSizeBounds() {
return slider.getValues();
}
/**
* The UiBinder interface.
*/
interface Binder extends UiBinder<Widget, GseaConfigDisplay> {
}
/** A ClientBundle of resources used by this widget. */
interface Resources extends ClientBundle {
/** The styles used in this widget. */
@Source(Css.CSS)
Css getCSS();
}
private static Resources RESOURCES;
static {
RESOURCES = GWT.create(Resources.class);
RESOURCES.getCSS().ensureInjected();
}
/** Styles used by this widget. */
interface Css extends CssResource {
/** The path to the default CSS styles used by this resource. */
String CSS = "GseaConfigDisplay.css";
String main();
}
}
|
package your_code;
import com.sun.jdi.connect.Connector;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
public class MyPriorityQueue {
// Priority queue implementation.
private ArrayList<Integer> al;
public MyPriorityQueue() {
// Creates new PriorityQueue with ArrayList implementation.
al = new ArrayList<>();
}
public void enqueue(int item) {
// Adds item to the priority queue.
// item : integer to add.
al.add(item);
}
public int dequeueMax() {
// Removes maximum value from the queue.
// returns int value of the maximum.
int max = al.get(0);
int index = 0;
for (int i = 0; i < al.size(); i++) {
if (al.get(i) > max) {
max = al.get(i);
index = i;
}
}
al.remove(index);
return max;
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.engine;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import pl.edu.icm.unity.ldaputils.LDAPAttributeTypesConverter;
import pl.edu.icm.unity.types.basic.AttributeType;
/**
* Tests loading of LDAP attribute types
* @author K. Benedyczak
*/
public class TestLDAPParser extends SecuredDBIntegrationTestBase
{
@Autowired
private LDAPAttributeTypesConverter converter;
@Test
public void test() throws Exception
{
InputStream is = LDAPAttributeTypesConverter.class.getClassLoader().getResourceAsStream(
"pl/edu/icm/unity/server/core/ldapschema/core.schema");
Reader r = new InputStreamReader(is);
List<AttributeType> attribtues = converter.convert(r);
Set<String> withoutDesc = new HashSet<>();
withoutDesc.add("name");
for (AttributeType at: attribtues)
if (!withoutDesc.contains(at.getName()))
assertNotNull(at.toString(), at.getDescription());
assertEquals(46, attribtues.size());
}
}
|
package tarea3_201513677;
import java.util.Scanner;
public final class Menu {
public int Opciones;
public String[] Usuarios;
public String NoUsuario;
public Menu(){
Opciones = 0;
NoUsuario = "";
Usuarios = new String[5];
//Menu principal
do {
System.out.println(" TAREA.3 ");
System.out.println(" -----------> 201513677 <----------- ");
System.out.println(" 1. Usuarios ");
System.out.println(" 2. Palabras Palíndromas ");
System.out.println(" 3. Salir ");
Scanner leer = new Scanner(System.in);
Opciones = leer.nextInt();
switch(Opciones){
case 1:
MenuUs();
break;
case 2:
PalabrasPalindromas();
break;
case 3:
break;
default:
System.out.println("Opcion Invalida");
break;
}
} while (Opciones != 3);
}
//Menu secundario
private void MenuUs(){
System.out.println(" Menu de Usuarios ");
System.out.println(" 1. Ingresar Usuarios ");
System.out.println(" 2. Mostrar todos los Usuarios ");
System.out.println(" 3. Mostrar un Usuario Personalizado ");
System.out.println(" 4. Menú Principal ");
Scanner opcUs = new Scanner(System.in);
Opciones = opcUs.nextInt();
do {
switch(Opciones){
case 1:
IngresarU();
break;
case 2:
MostrarU();
break;
case 3:
UsuarioP();
break;
case 4:
break;
default:
System.out.println("Opcion Invalida");
break;
}
} while (Opciones != 4);
}
public void IngresarU(){
for (int i = 0; i < Usuarios.length; i++) {
System.out.println("Ingrese un usuario: ");
Scanner us = new Scanner(System.in);
NoUsuario = us.nextLine();
Usuarios[i]= NoUsuario;
}
MenuUs();
}
public void MostrarU(){
System.out.println(" Mostrar Usuarios ");
for (int i = 0; i < Usuarios.length; i++) {
System.out.println((i+1)+".------------> "+Usuarios[i]);
}
MenuUs();
}
//Buscar un usuario para el menu personalizado
public String buscar(String us) {
for (int i = 0; i < Usuarios.length; i++) {
if(Usuarios[i].equals(us)){
return "v";
}
}
return "f";
}
//Mostrar el usuario encontrado de la busqueda
public void UsuarioP(){
System.out.println(" Mostrar un Usuario Personalizado ");
System.out.println(" Ingrese un Usuario: ");
Scanner usper = new Scanner(System.in);
NoUsuario = usper.nextLine();
if(!buscar(NoUsuario).equals("f")){
System.out.println(" Usuario: ");
System.out.println(NoUsuario);
} else{
System.err.println(" ERROR!!!! no existe ningun usuario con esa coincidencia ");
}
MenuUs();
}
//Opcion de palabras palindromas busqueda y mostrar las palbras
public void PalabrasPalindromas(){
String palabra;
Scanner sc = new Scanner(System.in);
System.out.println("*************Palabras Palindromas***************");
System.out.println(" Ingrese palabra ");
palabra = sc.nextLine();
if(comparacionpalindroma(palabra)){
System.out.println(" ''''''''' SI ES PALINDROMA ''''''''' ");
}else{
System.out.println(" ''''''''' NO ES PALINDROMA ''''''''' ");
}
}
public static boolean comparacionpalindroma(String palab){
String aux="";
int n = palab.length();
for(int i = 0; i < n; i++){
if(!(palab.substring(i,i + 1).equals(" ")
||palab.substring(i,i + 1).equals(" ,"))){
aux +=palab.substring(i,i + 1);
}
}
n = aux.length();
for(int i = 0; i < n /2; i++){
if(!aux.substring(i, i + 1).equals(aux.substring(n - i - 1,n - i))){
return false;
}
}
return true;
}
}
|
package GameTestArea;
import java.nio.FloatBuffer;
import java.text.DecimalFormat;
import java.util.Random;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.util.vector.Vector3f;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.gluPerspective;
public class PerspectiveDemo
{
/*Quad q = new Quad(-.05f, -.1f, .05f, -.1f, -1, -2);
Quad q2 = new Quad(.1f, -.1f, .2f, 0, -1, -2);
Quad q3 = new Quad(.2f, 0, .2f, .1f, -1, -2);
Quad q4 = new Quad(.2f, .1f, .1f, .2f, -1, -2);
Quad q5 = new Quad(-.05f, .2f, .05f, .2f, -1, -2);
Quad q6 = new Quad(-.2f, .1f, -.1f, .2f, -1, -2);
Quad q7 = new Quad (-.2f, .1f, -.2f, 0f, -1, -2);
Quad q8 = new Quad(-.2f, 0f, -.1f, -.1f, -1, -2);*/
private static UnicodeFont font;
private static DecimalFormat formatter = new DecimalFormat("#.##");
private static FloatBuffer perspectiveProjectionMatrix = reserveData(16);
private static FloatBuffer orthographicProjectionMatrix = reserveData(16);
float lastTime = 0.0f;
float time = 0.0f;
float dx = 0.0f;
float dy = 0.0f;
float dt = 0.0f;
float sensitivity = .2f;
float movementSpeed = 20f;
Cube c = new Cube(0, 0, -0.01f, .002f);
CameraController camera = new CameraController(0, 0, 0);
public void start()
{
try
{
Display.setDisplayMode(new DisplayMode(800, 600));
Display.setTitle("3D Perspective Demo");
Display.setVSyncEnabled(true);
Display.create();
}
catch (LWJGLException e)
{
e.printStackTrace();
System.exit(0);
}
//start OpenGL
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective((float)30, 800f / 600f, 1f, 10);
setUpLighting();
setUpFonts();
Point[] points = new Point[10000];
Random random = new Random();
for (int i = 0; i < points.length; i++) {
float x = random.nextFloat() - .5f;
float y = random.nextFloat() - .5f;
int z = random.nextInt(200) - 200;
points[i] = new Point(x,y,z);
}
Cube[] cubes = new Cube[100];
float pad = .2f;
for (int i = 0; i < cubes.length; i++)
{
float x = random.nextFloat() - 0.5f;
float y = random.nextFloat() - 0.5f;
cubes[i] = new Cube(x,y,-2f - pad, .2f);
pad += .4f;
}
float speed = 0.0f;
float angle = 0.0f;
lastTime = Sys.getTime();
float startZ = -0.01f;
while (!Display.isCloseRequested())
{
glViewport(0, 0, Display.getWidth(), Display.getHeight());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective((float)30, 800f / 600f, 1f, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
time=Sys.getTime();
dt = (time - lastTime);
lastTime = time;
glPushMatrix();
processInput();
camera.updateCameraPosition();
//glBegin(GL_POINTS);
for (Point p: points) {
if (p.z < 0.001f)
p.z += .2f;
else
p.z = -200f;
glColor3f(p.red, p.green, p.blue);
glBegin(GL_POINTS);
glVertex3f(p.x, p.y, p.z);
glEnd();
}
//glEnd();
/*Cube c2 = new Cube(0,0,startZ-=0.01f, .02f);
c2.draw(); */
for (Cube c: cubes) {
System.out.println(Mouse.getX() + ", " + Mouse.getY());
if (Mouse.isButtonDown(0) && c.inBounds(Mouse.getX(), Mouse.getY()))
{
System.out.println("Selected");
}
c.draw();
}
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, Display.getWidth(), 0.0f, Display.getHeight(), -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
//glBegin(GL_QUADS);
//maps the texture to each vertice coordinate 0,0 top left, 1,0 top right,
//1,1 bottom right, 0,1 bottom left (1 is the entire width of the texture)
//glVertex2f(0,0);
//glVertex2f(400, 0);
//glVertex2f(400, 400);
//glVertex2f(0, 400);
//glEnd();
Display.update();
Display.sync(60);
}
Display.destroy();
}
public static void setOrthoOn()
{
// prepare to render in 2D
// so 2D stuff stays on top of 3D scene
glMatrixMode(GL_PROJECTION);
glLoadMatrix(orthographicProjectionMatrix); // preserve perspective view
// clear the perspective matr
glMatrixMode(GL_MODELVIEW);
glPushMatrix(); // Preserve the Modelview Matrix
glLoadIdentity(); // clear the Modelview Matrix
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
}
public static void setOrthoOff()
{
// restore the original positions and views
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glLoadMatrix(perspectiveProjectionMatrix);
glMatrixMode(GL_MODELVIEW);
// turn Depth Testing back on
}
protected static void make2D() {
//Remove the Z axis
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, Display.getWidth(), 0, Display.getHeight(), -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
protected static void make3D() {
//Restore the Z axis
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
}
public void processInput()
{
if (Mouse.isButtonDown(1)) {
dx = Mouse.getDX();
dy = Mouse.getDY();
camera.yaw(dx * sensitivity);
camera.pitch(dy * sensitivity);
}
if (Keyboard.isKeyDown(Keyboard.KEY_W))
camera.forward(movementSpeed *0.002f);
if (Keyboard.isKeyDown(Keyboard.KEY_S))
camera.backwards(movementSpeed * 0.002f);
if (Keyboard.isKeyDown(Keyboard.KEY_A))
camera.strafeLeft(movementSpeed * 0.002f);
if (Keyboard.isKeyDown(Keyboard.KEY_D))
camera.strafeRight(movementSpeed * 0.002f);
if (Keyboard.isKeyDown(Keyboard.KEY_E))
{
glLight(GL_LIGHT0, GL_POSITION, asFloatBuffer(new float[]{camera.position.x,camera.position.y,camera.position.z,1}));
}
if(Keyboard.isKeyDown(Keyboard.KEY_SPACE))
camera.up();
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT))
camera.down();
}
private static FloatBuffer asFloatBuffer(float[] values) {
FloatBuffer buffer = BufferUtils.createFloatBuffer(values.length);
buffer.put(values);
buffer.flip();
return buffer;
}
private static void setUpFonts()
{
java.awt.Font awtFont = new java.awt.Font("Times New Roman", java.awt.Font.BOLD, 18);
font = new UnicodeFont(awtFont);
font.getEffects().add(new ColorEffect(java.awt.Color.white));
font.addAsciiGlyphs();
try{
font.loadGlyphs();
} catch (SlickException e)
{
e.printStackTrace();
}
}
private static void setUpLighting() {
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_LIGHT0);
glLightModel(GL_LIGHT_MODEL_AMBIENT, asFloatBuffer(new float[]{0.05f, 0.05f, 0.05f, 1f}));
glLight(GL_LIGHT0, GL_POSITION, asFloatBuffer(new float[]{0,0,0,1}));
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_DIFFUSE);
}
private static class Quad {
float x, y, x2, y2, zNear, zFar;
float red, green, blue;
public Quad(float x, float y, float x2, float y2, float zNear, float zFar)
{
this.x = x;
this.y = y;
this.x2 = x2;
this.y2 = y2;
this.zNear = zNear;
this.zFar = zFar;
randomizeColors();
}
public void draw() {
glColor3f(red, green, blue);
glBegin(GL_QUADS);
glVertex3f(x, y, zNear);
glVertex3f(x2, y2, zNear);
glVertex3f(x2, y2, zFar);
glVertex3f(x, y, zFar);
glEnd();
}
public void randomizeColors()
{
Random randomGenerator = new Random();
red = randomGenerator.nextFloat();
blue = randomGenerator.nextFloat();
green = randomGenerator.nextFloat();
}
}
private static class Point {
float x, y, z;
float red, green, blue;
public Point(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
randomizeColors();
}
public void randomizeColors()
{
Random randomGenerator = new Random();
red = randomGenerator.nextFloat();
blue = randomGenerator.nextFloat();
green = randomGenerator.nextFloat();
}
}
private static class Cube {
float x, y, z, width;
float red, green, blue;
boolean selected = false;
public Cube(float x, float y, float z, float width)
{
this.x = x;
this.y = y;
this.z = z;
this.width = width;
randomizeColors();
}
public void randomizeColors()
{
Random randomGenerator = new Random();
red = randomGenerator.nextFloat();
blue = randomGenerator.nextFloat();
green = randomGenerator.nextFloat();
}
boolean inBounds(int mousex, int mousey)
{
if(mousex > x && mousex < x + width && mousey > y && mousey < y + width)
return true;
else
return false;
}
public void draw()
{
//Front Face
glColor3f(red, green, blue);
glBegin(GL_QUADS);
glVertex3f(x, y, z);
glVertex3f(x + width, y, z);
glVertex3f(x + width, y + width, z);
glVertex3f(x, y + width, z);
glEnd();
//Rear Face
glColor3f(green, red, blue);
glBegin(GL_QUADS);
glVertex3f(x, y, z + width);
glVertex3f(x + width, y, z + width);
glVertex3f(x + width, y + width, z + width);
glVertex3f(x, y + width, z + width);
glEnd();
//top
glColor3f(green, blue, red);
glBegin(GL_QUADS);
glVertex3f(x, y+width, z);
glVertex3f(x+width, y+width, z);
glVertex3f(x+width, y+width, z+width);
glVertex3f(x, y+width, z+width);
glEnd();
//bottom
glColor3f(blue, red, green);
glBegin(GL_QUADS);
glVertex3f(x, y, z);
glVertex3f(x+width, y, z);
glVertex3f(x+width, y, z+width);
glVertex3f(x, y, z+width);
glEnd();
//leftside
glColor3f(blue, green, red);
glBegin(GL_QUADS);
glVertex3f(x,y,z);
glVertex3f(x, y, z+width);
glVertex3f(x, y+width, z+width);
glVertex3f(x, y+width, z);
glEnd();
//rightside
glColor3f(red, blue, blue);
glBegin(GL_QUADS);
glVertex3f(x+width, y, z);
glVertex3f(x+width, y+width, z);
glVertex3f(x+width, y+width, z+width);
glVertex3f(x+width, y, z+width);
glEnd();
}
public void setX(float x)
{
this.x = x;
}
public void setY(float y)
{
this.y = y;
}
public float getX()
{
return x;
}
public float getY()
{
return y;
}
public float getWidth()
{
return width;
}
public void select()
{
selected = true;
}
}
public class CameraController
{
private Vector3f position = null;
private float yaw = 0.0f;
private float pitch = 0.0f;
public CameraController(float x, float y, float z)
{
position = new Vector3f(x,y,z);
}
public void yaw(float amount)
{
yaw += amount;
}
public void pitch(float amount)
{
pitch -= amount;
}
public void forward(float distance)
{
position.x -= distance * (float)Math.sin(Math.toRadians(yaw));
position.y += distance * (float) Math.tan(Math.toRadians(pitch));
position.z += distance * (float)Math.cos(Math.toRadians(yaw));
}
public void backwards(float distance)
{
position.x += distance * (float)Math.sin(Math.toRadians(yaw));
position.y -= distance * (float) Math.tan(Math.toRadians(pitch));
position.z -= distance * (float)Math.cos(Math.toRadians(yaw));
}
public void strafeLeft(float distance)
{
position.x -= distance * (float)Math.sin(Math.toRadians(yaw-90));
position.z += distance * (float)Math.cos(Math.toRadians(yaw-90));
}
public void strafeRight(float distance)
{
position.x -= distance * (float)Math.sin(Math.toRadians(yaw+90));
position.z += distance * (float)Math.cos(Math.toRadians(yaw+90));
}
public void down()
{
position.y += movementSpeed * 0.002;
}
public void up()
{
position.y -= movementSpeed * 0.002;
}
public void updateCameraPosition()
{
glRotatef(pitch, 1.0f, 0f, 0f);
glRotatef(yaw, 0f, 1.0f, 0f);
glTranslatef(position.x, position.y, position.z);
}
}
public static FloatBuffer reserveData(int amountOfElements) {
return BufferUtils.createFloatBuffer(amountOfElements);
}
public static void main(String[] args)
{
PerspectiveDemo q = new PerspectiveDemo();
q.start();
// TODO Auto-generated method stub
}
}
|
package com.hwj.tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.hwj.entity.student;
import com.hwj.service.IStudentService;
@Component
public class TryCatchStudentService {
@Autowired
private IStudentService iStudentService;
public boolean saveStudent(student student){
try {
this.iStudentService.save(student);
} catch (Exception e) {
// TODO: handle exception
return false;
}
return true;
}
public student findByName(String propertyName,Object value){
student student=new student();
try {
student=this.iStudentService.get(propertyName, value);
} catch (Exception e) {
// TODO: handle exception
return null;
}
return student;
}
public boolean delete(student student){
try {
this.iStudentService.delete(student);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return false;
}
return true;
}
public boolean update(student student){
try {
this.iStudentService.update(student);
} catch (Exception e) {
// TODO: handle exception
return false;
}
return true;
}
}
|
package com.socialmeeting;
import android.app.Activity;
import android.os.Bundle;
public class MeetingActivity extends Activity {
/**
* @see android.app.Activity#onCreate(Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.meeting);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Unit tests for {@link AntPathMatcher}.
*
* @author Alef Arendsen
* @author Seth Ladd
* @author Juergen Hoeller
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
class AntPathMatcherTests {
private final AntPathMatcher pathMatcher = new AntPathMatcher();
@Test
void match() {
// test exact matching
assertThat(pathMatcher.match("test", "test")).isTrue();
assertThat(pathMatcher.match("/test", "/test")).isTrue();
// SPR-14141
assertThat(pathMatcher.match("https://example.org", "https://example.org")).isTrue();
assertThat(pathMatcher.match("/test.jpg", "test.jpg")).isFalse();
assertThat(pathMatcher.match("test", "/test")).isFalse();
assertThat(pathMatcher.match("/test", "test")).isFalse();
// test matching with ?'s
assertThat(pathMatcher.match("t?st", "test")).isTrue();
assertThat(pathMatcher.match("??st", "test")).isTrue();
assertThat(pathMatcher.match("tes?", "test")).isTrue();
assertThat(pathMatcher.match("te??", "test")).isTrue();
assertThat(pathMatcher.match("?es?", "test")).isTrue();
assertThat(pathMatcher.match("tes?", "tes")).isFalse();
assertThat(pathMatcher.match("tes?", "testt")).isFalse();
assertThat(pathMatcher.match("tes?", "tsst")).isFalse();
// test matching with *'s
assertThat(pathMatcher.match("*", "test")).isTrue();
assertThat(pathMatcher.match("test*", "test")).isTrue();
assertThat(pathMatcher.match("test*", "testTest")).isTrue();
assertThat(pathMatcher.match("test/*", "test/Test")).isTrue();
assertThat(pathMatcher.match("test/*", "test/t")).isTrue();
assertThat(pathMatcher.match("test/*", "test/")).isTrue();
assertThat(pathMatcher.match("*test*", "AnothertestTest")).isTrue();
assertThat(pathMatcher.match("*test", "Anothertest")).isTrue();
assertThat(pathMatcher.match("*.*", "test.")).isTrue();
assertThat(pathMatcher.match("*.*", "test.test")).isTrue();
assertThat(pathMatcher.match("*.*", "test.test.test")).isTrue();
assertThat(pathMatcher.match("test*aaa", "testblaaaa")).isTrue();
assertThat(pathMatcher.match("test*", "tst")).isFalse();
assertThat(pathMatcher.match("test*", "tsttest")).isFalse();
assertThat(pathMatcher.match("test*", "test/")).isFalse();
assertThat(pathMatcher.match("test*", "test/t")).isFalse();
assertThat(pathMatcher.match("test/*", "test")).isFalse();
assertThat(pathMatcher.match("*test*", "tsttst")).isFalse();
assertThat(pathMatcher.match("*test", "tsttst")).isFalse();
assertThat(pathMatcher.match("*.*", "tsttst")).isFalse();
assertThat(pathMatcher.match("test*aaa", "test")).isFalse();
assertThat(pathMatcher.match("test*aaa", "testblaaab")).isFalse();
// test matching with ?'s and /'s
assertThat(pathMatcher.match("/?", "/a")).isTrue();
assertThat(pathMatcher.match("/?/a", "/a/a")).isTrue();
assertThat(pathMatcher.match("/a/?", "/a/b")).isTrue();
assertThat(pathMatcher.match("/??/a", "/aa/a")).isTrue();
assertThat(pathMatcher.match("/a/??", "/a/bb")).isTrue();
assertThat(pathMatcher.match("/?", "/a")).isTrue();
// test matching with **'s
assertThat(pathMatcher.match("/**", "/testing/testing")).isTrue();
assertThat(pathMatcher.match("/*/**", "/testing/testing")).isTrue();
assertThat(pathMatcher.match("/**/*", "/testing/testing")).isTrue();
assertThat(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla")).isTrue();
assertThat(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla/bla")).isTrue();
assertThat(pathMatcher.match("/**/test", "/bla/bla/test")).isTrue();
assertThat(pathMatcher.match("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla")).isTrue();
assertThat(pathMatcher.match("/bla*bla/test", "/blaXXXbla/test")).isTrue();
assertThat(pathMatcher.match("/*bla/test", "/XXXbla/test")).isTrue();
assertThat(pathMatcher.match("/bla*bla/test", "/blaXXXbl/test")).isFalse();
assertThat(pathMatcher.match("/*bla/test", "XXXblab/test")).isFalse();
assertThat(pathMatcher.match("/*bla/test", "XXXbl/test")).isFalse();
assertThat(pathMatcher.match("/????", "/bala/bla")).isFalse();
assertThat(pathMatcher.match("/**/*bla", "/bla/bla/bla/bbb")).isFalse();
assertThat(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue();
assertThat(pathMatcher.match("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing")).isTrue();
assertThat(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertThat(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg")).isTrue();
assertThat(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue();
assertThat(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing")).isTrue();
assertThat(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertThat(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing")).isFalse();
assertThat(pathMatcher.match("/x/x/**/bla", "/x/x/x/")).isFalse();
assertThat(pathMatcher.match("/foo/bar/**", "/foo/bar")).isTrue();
assertThat(pathMatcher.match("", "")).isTrue();
assertThat(pathMatcher.match("/{bla}.*", "/testing.html")).isTrue();
assertThat(pathMatcher.match("/{bla}", "//x\ny")).isTrue();
assertThat(pathMatcher.match("/{var:.*}", "/x\ny")).isTrue();
}
@Test
void matchWithNullPath() {
assertThat(pathMatcher.match("/test", null)).isFalse();
assertThat(pathMatcher.match("/", null)).isFalse();
assertThat(pathMatcher.match(null, null)).isFalse();
}
// SPR-14247
@Test
void matchWithTrimTokensEnabled() throws Exception {
pathMatcher.setTrimTokens(true);
assertThat(pathMatcher.match("/foo/bar", "/foo /bar")).isTrue();
}
@Test
void matchStart() {
// test exact matching
assertThat(pathMatcher.matchStart("test", "test")).isTrue();
assertThat(pathMatcher.matchStart("/test", "/test")).isTrue();
assertThat(pathMatcher.matchStart("/test.jpg", "test.jpg")).isFalse();
assertThat(pathMatcher.matchStart("test", "/test")).isFalse();
assertThat(pathMatcher.matchStart("/test", "test")).isFalse();
// test matching with ?'s
assertThat(pathMatcher.matchStart("t?st", "test")).isTrue();
assertThat(pathMatcher.matchStart("??st", "test")).isTrue();
assertThat(pathMatcher.matchStart("tes?", "test")).isTrue();
assertThat(pathMatcher.matchStart("te??", "test")).isTrue();
assertThat(pathMatcher.matchStart("?es?", "test")).isTrue();
assertThat(pathMatcher.matchStart("tes?", "tes")).isFalse();
assertThat(pathMatcher.matchStart("tes?", "testt")).isFalse();
assertThat(pathMatcher.matchStart("tes?", "tsst")).isFalse();
// test matching with *'s
assertThat(pathMatcher.matchStart("*", "test")).isTrue();
assertThat(pathMatcher.matchStart("test*", "test")).isTrue();
assertThat(pathMatcher.matchStart("test*", "testTest")).isTrue();
assertThat(pathMatcher.matchStart("test/*", "test/Test")).isTrue();
assertThat(pathMatcher.matchStart("test/*", "test/t")).isTrue();
assertThat(pathMatcher.matchStart("test/*", "test/")).isTrue();
assertThat(pathMatcher.matchStart("*test*", "AnothertestTest")).isTrue();
assertThat(pathMatcher.matchStart("*test", "Anothertest")).isTrue();
assertThat(pathMatcher.matchStart("*.*", "test.")).isTrue();
assertThat(pathMatcher.matchStart("*.*", "test.test")).isTrue();
assertThat(pathMatcher.matchStart("*.*", "test.test.test")).isTrue();
assertThat(pathMatcher.matchStart("test*aaa", "testblaaaa")).isTrue();
assertThat(pathMatcher.matchStart("test*", "tst")).isFalse();
assertThat(pathMatcher.matchStart("test*", "test/")).isFalse();
assertThat(pathMatcher.matchStart("test*", "tsttest")).isFalse();
assertThat(pathMatcher.matchStart("test*", "test/")).isFalse();
assertThat(pathMatcher.matchStart("test*", "test/t")).isFalse();
assertThat(pathMatcher.matchStart("test/*", "test")).isTrue();
assertThat(pathMatcher.matchStart("test/t*.txt", "test")).isTrue();
assertThat(pathMatcher.matchStart("*test*", "tsttst")).isFalse();
assertThat(pathMatcher.matchStart("*test", "tsttst")).isFalse();
assertThat(pathMatcher.matchStart("*.*", "tsttst")).isFalse();
assertThat(pathMatcher.matchStart("test*aaa", "test")).isFalse();
assertThat(pathMatcher.matchStart("test*aaa", "testblaaab")).isFalse();
// test matching with ?'s and /'s
assertThat(pathMatcher.matchStart("/?", "/a")).isTrue();
assertThat(pathMatcher.matchStart("/?/a", "/a/a")).isTrue();
assertThat(pathMatcher.matchStart("/a/?", "/a/b")).isTrue();
assertThat(pathMatcher.matchStart("/??/a", "/aa/a")).isTrue();
assertThat(pathMatcher.matchStart("/a/??", "/a/bb")).isTrue();
assertThat(pathMatcher.matchStart("/?", "/a")).isTrue();
// test matching with **'s
assertThat(pathMatcher.matchStart("/**", "/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("/*/**", "/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("/**/*", "/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("test*/**", "test/")).isTrue();
assertThat(pathMatcher.matchStart("test*/**", "test/t")).isTrue();
assertThat(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla")).isTrue();
assertThat(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla/bla")).isTrue();
assertThat(pathMatcher.matchStart("/**/test", "/bla/bla/test")).isTrue();
assertThat(pathMatcher.matchStart("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla")).isTrue();
assertThat(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbla/test")).isTrue();
assertThat(pathMatcher.matchStart("/*bla/test", "/XXXbla/test")).isTrue();
assertThat(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbl/test")).isFalse();
assertThat(pathMatcher.matchStart("/*bla/test", "XXXblab/test")).isFalse();
assertThat(pathMatcher.matchStart("/*bla/test", "XXXbl/test")).isFalse();
assertThat(pathMatcher.matchStart("/????", "/bala/bla")).isFalse();
assertThat(pathMatcher.matchStart("/**/*bla", "/bla/bla/bla/bbb")).isTrue();
assertThat(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue();
assertThat(pathMatcher.matchStart("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing")).isTrue();
assertThat(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg")).isTrue();
assertThat(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue();
assertThat(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing")).isTrue();
assertThat(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("/x/x/**/bla", "/x/x/x/")).isTrue();
assertThat(pathMatcher.matchStart("", "")).isTrue();
}
@Test
void uniqueDeliminator() {
pathMatcher.setPathSeparator(".");
// test exact matching
assertThat(pathMatcher.match("test", "test")).isTrue();
assertThat(pathMatcher.match(".test", ".test")).isTrue();
assertThat(pathMatcher.match(".test/jpg", "test/jpg")).isFalse();
assertThat(pathMatcher.match("test", ".test")).isFalse();
assertThat(pathMatcher.match(".test", "test")).isFalse();
// test matching with ?'s
assertThat(pathMatcher.match("t?st", "test")).isTrue();
assertThat(pathMatcher.match("??st", "test")).isTrue();
assertThat(pathMatcher.match("tes?", "test")).isTrue();
assertThat(pathMatcher.match("te??", "test")).isTrue();
assertThat(pathMatcher.match("?es?", "test")).isTrue();
assertThat(pathMatcher.match("tes?", "tes")).isFalse();
assertThat(pathMatcher.match("tes?", "testt")).isFalse();
assertThat(pathMatcher.match("tes?", "tsst")).isFalse();
// test matching with *'s
assertThat(pathMatcher.match("*", "test")).isTrue();
assertThat(pathMatcher.match("test*", "test")).isTrue();
assertThat(pathMatcher.match("test*", "testTest")).isTrue();
assertThat(pathMatcher.match("*test*", "AnothertestTest")).isTrue();
assertThat(pathMatcher.match("*test", "Anothertest")).isTrue();
assertThat(pathMatcher.match("*/*", "test/")).isTrue();
assertThat(pathMatcher.match("*/*", "test/test")).isTrue();
assertThat(pathMatcher.match("*/*", "test/test/test")).isTrue();
assertThat(pathMatcher.match("test*aaa", "testblaaaa")).isTrue();
assertThat(pathMatcher.match("test*", "tst")).isFalse();
assertThat(pathMatcher.match("test*", "tsttest")).isFalse();
assertThat(pathMatcher.match("*test*", "tsttst")).isFalse();
assertThat(pathMatcher.match("*test", "tsttst")).isFalse();
assertThat(pathMatcher.match("*/*", "tsttst")).isFalse();
assertThat(pathMatcher.match("test*aaa", "test")).isFalse();
assertThat(pathMatcher.match("test*aaa", "testblaaab")).isFalse();
// test matching with ?'s and .'s
assertThat(pathMatcher.match(".?", ".a")).isTrue();
assertThat(pathMatcher.match(".?.a", ".a.a")).isTrue();
assertThat(pathMatcher.match(".a.?", ".a.b")).isTrue();
assertThat(pathMatcher.match(".??.a", ".aa.a")).isTrue();
assertThat(pathMatcher.match(".a.??", ".a.bb")).isTrue();
assertThat(pathMatcher.match(".?", ".a")).isTrue();
// test matching with **'s
assertThat(pathMatcher.match(".**", ".testing.testing")).isTrue();
assertThat(pathMatcher.match(".*.**", ".testing.testing")).isTrue();
assertThat(pathMatcher.match(".**.*", ".testing.testing")).isTrue();
assertThat(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla")).isTrue();
assertThat(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla.bla")).isTrue();
assertThat(pathMatcher.match(".**.test", ".bla.bla.test")).isTrue();
assertThat(pathMatcher.match(".bla.**.**.bla", ".bla.bla.bla.bla.bla.bla")).isTrue();
assertThat(pathMatcher.match(".bla*bla.test", ".blaXXXbla.test")).isTrue();
assertThat(pathMatcher.match(".*bla.test", ".XXXbla.test")).isTrue();
assertThat(pathMatcher.match(".bla*bla.test", ".blaXXXbl.test")).isFalse();
assertThat(pathMatcher.match(".*bla.test", "XXXblab.test")).isFalse();
assertThat(pathMatcher.match(".*bla.test", "XXXbl.test")).isFalse();
}
@Test
void extractPathWithinPattern() throws Exception {
assertThat(pathMatcher.extractPathWithinPattern("/docs/commit.html", "/docs/commit.html")).isEmpty();
assertThat(pathMatcher.extractPathWithinPattern("/docs/*", "/docs/cvs/commit")).isEqualTo("cvs/commit");
assertThat(pathMatcher.extractPathWithinPattern("/docs/cvs/*.html", "/docs/cvs/commit.html")).isEqualTo("commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**", "/docs/cvs/commit")).isEqualTo("cvs/commit");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/cvs/commit.html")).isEqualTo("cvs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/commit.html")).isEqualTo("commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/*.html", "/commit.html")).isEqualTo("commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/*.html", "/docs/commit.html")).isEqualTo("docs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("*.html", "/commit.html")).isEqualTo("/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("*.html", "/docs/commit.html")).isEqualTo("/docs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("**/*.*", "/docs/commit.html")).isEqualTo("/docs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("*", "/docs/commit.html")).isEqualTo("/docs/commit.html");
// SPR-10515
assertThat(pathMatcher.extractPathWithinPattern("**/commit.html", "/docs/cvs/other/commit.html")).isEqualTo("/docs/cvs/other/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**/commit.html", "/docs/cvs/other/commit.html")).isEqualTo("cvs/other/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**/**/**/**", "/docs/cvs/other/commit.html")).isEqualTo("cvs/other/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/d?cs/*", "/docs/cvs/commit")).isEqualTo("docs/cvs/commit");
assertThat(pathMatcher.extractPathWithinPattern("/docs/c?s/*.html", "/docs/cvs/commit.html")).isEqualTo("cvs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/d?cs/**", "/docs/cvs/commit")).isEqualTo("docs/cvs/commit");
assertThat(pathMatcher.extractPathWithinPattern("/d?cs/**/*.html", "/docs/cvs/commit.html")).isEqualTo("docs/cvs/commit.html");
}
@Test
void extractUriTemplateVariables() throws Exception {
Map<String, String> result = pathMatcher.extractUriTemplateVariables("/hotels/{hotel}", "/hotels/1");
assertThat(result).isEqualTo(Collections.singletonMap("hotel", "1"));
result = pathMatcher.extractUriTemplateVariables("/h?tels/{hotel}", "/hotels/1");
assertThat(result).isEqualTo(Collections.singletonMap("hotel", "1"));
result = pathMatcher.extractUriTemplateVariables("/hotels/{hotel}/bookings/{booking}", "/hotels/1/bookings/2");
Map<String, String> expected = new LinkedHashMap<>();
expected.put("hotel", "1");
expected.put("booking", "2");
assertThat(result).isEqualTo(expected);
result = pathMatcher.extractUriTemplateVariables("/**/hotels/**/{hotel}", "/foo/hotels/bar/1");
assertThat(result).isEqualTo(Collections.singletonMap("hotel", "1"));
result = pathMatcher.extractUriTemplateVariables("/{page}.html", "/42.html");
assertThat(result).isEqualTo(Collections.singletonMap("page", "42"));
result = pathMatcher.extractUriTemplateVariables("/{page}.*", "/42.html");
assertThat(result).isEqualTo(Collections.singletonMap("page", "42"));
result = pathMatcher.extractUriTemplateVariables("/A-{B}-C", "/A-b-C");
assertThat(result).isEqualTo(Collections.singletonMap("B", "b"));
result = pathMatcher.extractUriTemplateVariables("/{name}.{extension}", "/test.html");
expected = new LinkedHashMap<>();
expected.put("name", "test");
expected.put("extension", "html");
assertThat(result).isEqualTo(expected);
}
@Test
void extractUriTemplateVariablesRegex() {
Map<String, String> result = pathMatcher
.extractUriTemplateVariables("{symbolicName:[\\w\\.]+}-{version:[\\w\\.]+}.jar",
"com.example-1.0.0.jar");
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0");
result = pathMatcher.extractUriTemplateVariables("{symbolicName:[\\w\\.]+}-sources-{version:[\\w\\.]+}.jar",
"com.example-sources-1.0.0.jar");
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0");
}
/**
* SPR-7787
*/
@Test
void extractUriTemplateVarsRegexQualifiers() {
Map<String, String> result = pathMatcher.extractUriTemplateVariables(
"{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar",
"com.example-sources-1.0.0.jar");
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0");
result = pathMatcher.extractUriTemplateVariables(
"{symbolicName:[\\w\\.]+}-sources-{version:[\\d\\.]+}-{year:\\d{4}}{month:\\d{2}}{day:\\d{2}}.jar",
"com.example-sources-1.0.0-20100220.jar");
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0");
assertThat(result.get("year")).isEqualTo("2010");
assertThat(result.get("month")).isEqualTo("02");
assertThat(result.get("day")).isEqualTo("20");
result = pathMatcher.extractUriTemplateVariables(
"{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.\\{\\}]+}.jar",
"com.example-sources-1.0.0.{12}.jar");
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0.{12}");
}
/**
* SPR-8455
*/
@Test
void extractUriTemplateVarsRegexCapturingGroups() {
assertThatIllegalArgumentException().isThrownBy(() ->
pathMatcher.extractUriTemplateVariables("/web/{id:foo(bar)?}", "/web/foobar"))
.withMessageContaining("The number of capturing groups in the pattern");
}
@Test
void combine() {
assertThat(pathMatcher.combine(null, null)).isEmpty();
assertThat(pathMatcher.combine("/hotels", null)).isEqualTo("/hotels");
assertThat(pathMatcher.combine(null, "/hotels")).isEqualTo("/hotels");
assertThat(pathMatcher.combine("/hotels/*", "booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels/*", "/booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels/**", "booking")).isEqualTo("/hotels/**/booking");
assertThat(pathMatcher.combine("/hotels/**", "/booking")).isEqualTo("/hotels/**/booking");
assertThat(pathMatcher.combine("/hotels", "/booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels", "booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels/", "booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels/*", "{hotel}")).isEqualTo("/hotels/{hotel}");
assertThat(pathMatcher.combine("/hotels/**", "{hotel}")).isEqualTo("/hotels/**/{hotel}");
assertThat(pathMatcher.combine("/hotels", "{hotel}")).isEqualTo("/hotels/{hotel}");
assertThat(pathMatcher.combine("/hotels", "{hotel}.*")).isEqualTo("/hotels/{hotel}.*");
assertThat(pathMatcher.combine("/hotels/*/booking", "{booking}")).isEqualTo("/hotels/*/booking/{booking}");
assertThat(pathMatcher.combine("/*.html", "/hotel.html")).isEqualTo("/hotel.html");
assertThat(pathMatcher.combine("/*.html", "/hotel")).isEqualTo("/hotel.html");
assertThat(pathMatcher.combine("/*.html", "/hotel.*")).isEqualTo("/hotel.html");
assertThat(pathMatcher.combine("/**", "/*.html")).isEqualTo("/*.html");
assertThat(pathMatcher.combine("/*", "/*.html")).isEqualTo("/*.html");
assertThat(pathMatcher.combine("/*.*", "/*.html")).isEqualTo("/*.html");
// SPR-8858
assertThat(pathMatcher.combine("/{foo}", "/bar")).isEqualTo("/{foo}/bar");
// SPR-7970
assertThat(pathMatcher.combine("/user", "/user")).isEqualTo("/user/user");
// SPR-10062
assertThat(pathMatcher.combine("/{foo:.*[^0-9].*}", "/edit/")).isEqualTo("/{foo:.*[^0-9].*}/edit/");
// SPR-10554
assertThat(pathMatcher.combine("/1.0", "/foo/test")).isEqualTo("/1.0/foo/test");
// SPR-12975
assertThat(pathMatcher.combine("/", "/hotel")).isEqualTo("/hotel");
// SPR-12975
assertThat(pathMatcher.combine("/hotel/", "/booking")).isEqualTo("/hotel/booking");
}
@Test
void combineWithTwoFileExtensionPatterns() {
assertThatIllegalArgumentException().isThrownBy(() ->
pathMatcher.combine("/*.html", "/*.txt"));
}
@Test
void patternComparator() {
Comparator<String> comparator = pathMatcher.getPatternComparator("/hotels/new");
assertThat(comparator.compare(null, null)).isEqualTo(0);
assertThat(comparator.compare(null, "/hotels/new")).isEqualTo(1);
assertThat(comparator.compare("/hotels/new", null)).isEqualTo(-1);
assertThat(comparator.compare("/hotels/new", "/hotels/new")).isEqualTo(0);
assertThat(comparator.compare("/hotels/new", "/hotels/*")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/*", "/hotels/new")).isEqualTo(1);
assertThat(comparator.compare("/hotels/*", "/hotels/*")).isEqualTo(0);
assertThat(comparator.compare("/hotels/new", "/hotels/{hotel}")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/new")).isEqualTo(1);
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/{hotel}")).isEqualTo(0);
assertThat(comparator.compare("/hotels/{hotel}/booking", "/hotels/{hotel}/bookings/{booking}")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/{hotel}/bookings/{booking}", "/hotels/{hotel}/booking")).isEqualTo(1);
// SPR-10550
assertThat(comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/**")).isEqualTo(-1);
assertThat(comparator.compare("/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}")).isEqualTo(1);
assertThat(comparator.compare("/**", "/**")).isEqualTo(0);
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/*")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/*", "/hotels/{hotel}")).isEqualTo(1);
assertThat(comparator.compare("/hotels/*", "/hotels/*/**")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/*/**", "/hotels/*")).isEqualTo(1);
assertThat(comparator.compare("/hotels/new", "/hotels/new.*")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/{hotel}.*")).isEqualTo(2);
// SPR-6741
assertThat(comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/hotels/**")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}")).isEqualTo(1);
assertThat(comparator.compare("/hotels/foo/bar/**", "/hotels/{hotel}")).isEqualTo(1);
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/foo/bar/**")).isEqualTo(-1);
// gh-23125
assertThat(comparator.compare("/hotels/*/bookings/**", "/hotels/**")).isEqualTo(-11);
// SPR-8683
assertThat(comparator.compare("/**", "/hotels/{hotel}")).isEqualTo(1);
// longer is better
assertThat(comparator.compare("/hotels", "/hotels2")).isEqualTo(1);
// SPR-13139
assertThat(comparator.compare("*", "*/**")).isEqualTo(-1);
assertThat(comparator.compare("*/**", "*")).isEqualTo(1);
}
@Test
void patternComparatorSort() {
Comparator<String> comparator = pathMatcher.getPatternComparator("/hotels/new");
List<String> paths = new ArrayList<>(3);
paths.add(null);
paths.add("/hotels/new");
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isNull();
paths.clear();
paths.add("/hotels/new");
paths.add(null);
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isNull();
paths.clear();
paths.add("/hotels/*");
paths.add("/hotels/new");
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/*");
paths.clear();
paths.add("/hotels/new");
paths.add("/hotels/*");
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/*");
paths.clear();
paths.add("/hotels/**");
paths.add("/hotels/*");
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/*");
assertThat(paths.get(1)).isEqualTo("/hotels/**");
paths.clear();
paths.add("/hotels/*");
paths.add("/hotels/**");
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/*");
assertThat(paths.get(1)).isEqualTo("/hotels/**");
paths.clear();
paths.add("/hotels/{hotel}");
paths.add("/hotels/new");
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
paths.clear();
paths.add("/hotels/new");
paths.add("/hotels/{hotel}");
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
paths.clear();
paths.add("/hotels/*");
paths.add("/hotels/{hotel}");
paths.add("/hotels/new");
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
assertThat(paths.get(2)).isEqualTo("/hotels/*");
paths.clear();
paths.add("/hotels/ne*");
paths.add("/hotels/n*");
Collections.shuffle(paths);
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/ne*");
assertThat(paths.get(1)).isEqualTo("/hotels/n*");
paths.clear();
comparator = pathMatcher.getPatternComparator("/hotels/new.html");
paths.add("/hotels/new.*");
paths.add("/hotels/{hotel}");
Collections.shuffle(paths);
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/hotels/new.*");
assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
paths.clear();
comparator = pathMatcher.getPatternComparator("/web/endUser/action/login.html");
paths.add("/**/login.*");
paths.add("/**/endUser/action/login.*");
paths.sort(comparator);
assertThat(paths.get(0)).isEqualTo("/**/endUser/action/login.*");
assertThat(paths.get(1)).isEqualTo("/**/login.*");
paths.clear();
}
@Test // SPR-8687
void trimTokensOff() {
pathMatcher.setTrimTokens(false);
assertThat(pathMatcher.match("/group/{groupName}/members", "/group/sales/members")).isTrue();
assertThat(pathMatcher.match("/group/{groupName}/members", "/group/ sales/members")).isTrue();
assertThat(pathMatcher.match("/group/{groupName}/members", "/Group/ Sales/Members")).isFalse();
}
@Test // SPR-13286
void caseInsensitive() {
pathMatcher.setCaseSensitive(false);
assertThat(pathMatcher.match("/group/{groupName}/members", "/group/sales/members")).isTrue();
assertThat(pathMatcher.match("/group/{groupName}/members", "/Group/Sales/Members")).isTrue();
assertThat(pathMatcher.match("/Group/{groupName}/Members", "/group/Sales/members")).isTrue();
}
@Test
void defaultCacheSetting() {
match();
assertThat(pathMatcher.stringMatcherCache).hasSizeGreaterThan(20);
for (int i = 0; i < 65536; i++) {
pathMatcher.match("test" + i, "test");
}
// Cache turned off because it went beyond the threshold
assertThat(pathMatcher.stringMatcherCache.isEmpty()).isTrue();
}
@Test
void cachePatternsSetToTrue() {
pathMatcher.setCachePatterns(true);
match();
assertThat(pathMatcher.stringMatcherCache).hasSizeGreaterThan(20);
for (int i = 0; i < 65536; i++) {
pathMatcher.match("test" + i, "test" + i);
}
// Cache keeps being alive due to the explicit cache setting
assertThat(pathMatcher.stringMatcherCache).hasSizeGreaterThan(65536);
}
@Test
void preventCreatingStringMatchersIfPathDoesNotStartsWithPatternPrefix() {
pathMatcher.setCachePatterns(true);
assertThat(pathMatcher.stringMatcherCache).isEmpty();
pathMatcher.match("test?", "test");
assertThat(pathMatcher.stringMatcherCache).hasSize(1);
pathMatcher.match("test?", "best");
pathMatcher.match("test/*", "view/test.jpg");
pathMatcher.match("test/**/test.jpg", "view/test.jpg");
pathMatcher.match("test/{name}.jpg", "view/test.jpg");
assertThat(pathMatcher.stringMatcherCache).hasSize(1);
}
@Test
void creatingStringMatchersIfPatternPrefixCannotDetermineIfPathMatch() {
pathMatcher.setCachePatterns(true);
assertThat(pathMatcher.stringMatcherCache).isEmpty();
pathMatcher.match("test", "testian");
pathMatcher.match("test?", "testFf");
pathMatcher.match("test/*", "test/dir/name.jpg");
pathMatcher.match("test/{name}.jpg", "test/lorem.jpg");
pathMatcher.match("bla/**/test.jpg", "bla/test.jpg");
pathMatcher.match("**/{name}.jpg", "test/lorem.jpg");
pathMatcher.match("/**/{name}.jpg", "/test/lorem.jpg");
pathMatcher.match("/*/dir/{name}.jpg", "/*/dir/lorem.jpg");
assertThat(pathMatcher.stringMatcherCache).hasSize(7);
}
@Test
void cachePatternsSetToFalse() {
pathMatcher.setCachePatterns(false);
match();
assertThat(pathMatcher.stringMatcherCache.isEmpty()).isTrue();
}
@Test
void extensionMappingWithDotPathSeparator() {
pathMatcher.setPathSeparator(".");
assertThat(pathMatcher.combine("/*.html", "hotel.*")).as("Extension mapping should be disabled with \".\" as path separator").isEqualTo("/*.html.hotel.*");
}
@Test // gh-22959
void isPattern() {
assertThat(pathMatcher.isPattern("/test/*")).isTrue();
assertThat(pathMatcher.isPattern("/test/**/name")).isTrue();
assertThat(pathMatcher.isPattern("/test?")).isTrue();
assertThat(pathMatcher.isPattern("/test/{name}")).isTrue();
assertThat(pathMatcher.isPattern("/test/name")).isFalse();
assertThat(pathMatcher.isPattern("/test/foo{bar")).isFalse();
}
@Test // gh-23297
void isPatternWithNullPath() {
assertThat(pathMatcher.isPattern(null)).isFalse();
}
@Test // gh-27506
void consistentMatchWithWildcardsAndTrailingSlash() {
assertThat(pathMatcher.match("/*/foo", "/en/foo")).isTrue();
assertThat(pathMatcher.match("/*/foo", "/en/foo/")).isFalse();
assertThat(pathMatcher.match("/**/foo", "/en/foo")).isTrue();
assertThat(pathMatcher.match("/**/foo", "/en/foo/")).isFalse();
}
}
|
package com.tcs.restcontrollers;
import java.sql.SQLException;
import java.util.List;
import javax.ws.rs.QueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.ws.rs.core.Response;
import org.springframework.http.ResponseEntity;
import com.tcs.bean.Course;
import com.tcs.bean.Student;
import com.tcs.exception.UserNotFoundException;
import com.tcs.service.AdminInterFace;
import com.tcs.service.StudentInterFace;
@RestController
@CrossOrigin
public class AdminControllers {
@Autowired
private AdminInterFace admin;
@RequestMapping(value="/admin/login",method=RequestMethod.POST)
public ResponseEntity loginAdmin(@QueryParam("adminuserName") String adminuserName,@QueryParam("adminPassword") String adminPassword) throws UserNotFoundException {
boolean loginStatus = admin.loginAdmin(adminuserName, adminPassword);
if (loginStatus) {
return new ResponseEntity("Login Successful", HttpStatus.OK);
}else {
return new ResponseEntity("User Name or Password is incorrect ", HttpStatus.NOT_FOUND);
}
}
@RequestMapping(value="/admin/addCourse",method=RequestMethod.POST)
public Response addCourese(@RequestBody Course course ) {
List<Course> courseList = admin.viewCourses();
try {
admin.addCourse(course,courseList);
return Response.status(201).entity("Course with courseCode: " + course.getCourseCode() + " added to catalog").build();
} catch (Exception e) {
return Response.status(409).entity(e.getMessage()).build();
}
}
@RequestMapping(method=RequestMethod.GET,value="/admin/courses")
public List getCourses() throws SQLException {
return admin.getAllCourses();
}
@RequestMapping(method=RequestMethod.PUT,value="/admin/assigncourses")
public Response assignCourses(@QueryParam("courseCode") String courseCode, @QueryParam("instructorId") String instructorId) {
try {
admin.assignCourse(courseCode, instructorId);
return Response.status(201).entity("courseCode: " + courseCode + " assigned to professor: " + instructorId).build();
} catch (Exception e) {
return Response.status(409).entity(e.getMessage()).build();
}
}
@RequestMapping(value="/admin/delete/{courseCode}",method=RequestMethod.DELETE)
public ResponseEntity deleteStudent(@PathVariable String courseCode) throws SQLException {
Course course = admin.deleteCourse(courseCode);
if (null == course) {
return new ResponseEntity("No Course found for ID " + courseCode, HttpStatus.NOT_FOUND);
}
return new ResponseEntity(courseCode, HttpStatus.OK);
}
}
|
package com.zs.ui.home.view;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.huaiye.cmf.sdp.SdpMessageBase;
import com.huaiye.sdk.HYClient;
import com.huaiye.sdk.core.SdkCallback;
import com.huaiye.sdk.logger.Logger;
import com.huaiye.sdk.media.capture.Capture;
import com.huaiye.sdk.media.capture.HYCapture;
import com.huaiye.sdk.sdpmsgs.video.CStartMobileCaptureRsp;
import com.huaiye.sdk.sdpmsgs.video.CStopMobileCaptureRsp;
import com.zs.MCApp;
import com.zs.R;
import com.zs.common.AppBaseActivity;
import com.zs.common.AppUtils;
import com.zs.common.SP;
import com.zs.dao.AppDatas;
import com.zs.dao.MediaFileDaoUtils;
import com.zs.dao.auth.AppAuth;
import com.zs.dao.msgs.CaptureMessage;
import com.zs.dao.msgs.ChatUtil;
import com.zs.dao.msgs.StopCaptureMessage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import static com.zs.common.AppUtils.CAPTURE_TYPE;
import static com.zs.common.AppUtils.STRING_KEY_HD1080P;
import static com.zs.common.AppUtils.STRING_KEY_HD720P;
import static com.zs.common.AppUtils.STRING_KEY_VGA;
import static com.zs.common.AppUtils.STRING_KEY_camera;
import static com.zs.common.AppUtils.STRING_KEY_capture;
import static com.zs.common.AppUtils.STRING_KEY_false;
import static com.zs.common.AppUtils.STRING_KEY_mPublishPresetoption;
import static com.zs.common.AppUtils.STRING_KEY_photo;
import static com.zs.common.AppUtils.showToast;
import static com.zs.ui.Capture.CaptureGuanMoOrPushActivity.REQUEST_CODE_CAPTURE;
/**
* author: admin
* date: 2018/05/16
* version: 0
* mail: secret
* desc: ActionBarLayout
*/
public class CaptureViewLayout extends FrameLayout implements View.OnClickListener {
public View iv_camera;//链接相册键
ImageView iv_shanguang;
View iv_change;
View iv_waizhi;
View iv_close;
View iv_suofang;
View tv_quxiao;
ImageView iv_anjian;
ImageView iv_start_stop;//开关键
View iv_take_photo;//拍照键
TextView tv_name;//名称
TextView tv_size;//内存
TextView tv_fenbianlv;//分辨率
View ll_guanlian;//案件信息
TextView tv_anjian;//案件信息
TextView tv_time;//案件信息
View view_cover;
View fl_root;
TextureView ttv_capture;
SurfaceTexture mSurfaceTexture;
private Camera mCamera;
ArrayList<String> userId = new ArrayList<>();
boolean isOfflineMode = true;//是否在线录像
private final int CAPTURE_STATUS_NONE = 0;
private final int CAPTURE_STATUS_STARTING = 1;
private final int CAPTURE_STATUS_CAPTURING = 2;
int captureStatus;
boolean isRecord;
boolean isPaused;
boolean isFromGuanMo;//是否是观摩启动
MediaFileDaoUtils.MediaFile mMediaFile;
/**
* pc 客户端会多次发消息,采集开始的时候缓存起来
*/
ArrayList<CaptureMessage> pendingMsg = new ArrayList<>();
public boolean isCapture() {
return captureStatus > CAPTURE_STATUS_NONE;
}
public CaptureViewLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CaptureViewLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, -1);
View view = LayoutInflater.from(context).inflate(R.layout.main_capture_layout, null);
iv_camera = view.findViewById(R.id.iv_camera);
iv_shanguang = view.findViewById(R.id.iv_shanguang);
iv_change = view.findViewById(R.id.iv_change);
iv_waizhi = view.findViewById(R.id.iv_waizhi);
ttv_capture = view.findViewById(R.id.ttv_capture);
view_cover = view.findViewById(R.id.view_cover);
iv_close = view.findViewById(R.id.iv_close);
fl_root = view.findViewById(R.id.fl_root);
iv_suofang = view.findViewById(R.id.iv_suofang);
tv_name = view.findViewById(R.id.tv_name);
tv_size = view.findViewById(R.id.tv_size);
tv_fenbianlv = view.findViewById(R.id.tv_fenbianlv);
ll_guanlian = view.findViewById(R.id.ll_guanlian);
tv_anjian = view.findViewById(R.id.tv_anjian);
tv_time = view.findViewById(R.id.tv_time);
iv_start_stop = view.findViewById(R.id.iv_start_stop);
iv_take_photo = view.findViewById(R.id.iv_take_photo);
tv_quxiao = view.findViewById(R.id.tv_quxiao);
iv_anjian = view.findViewById(R.id.iv_anjian);
addView(view);
iv_close.setOnClickListener(this);
iv_camera.setOnClickListener(this);
iv_shanguang.setOnClickListener(this);
iv_change.setOnClickListener(this);
iv_waizhi.setOnClickListener(this);
iv_suofang.setOnClickListener(this);
iv_start_stop.setOnClickListener(this);
iv_anjian.setOnClickListener(this);
tv_quxiao.setOnClickListener(this);
iv_camera.setOnClickListener(this);
iv_take_photo.setOnClickListener(this);
tv_name.setText(AppAuth.get().getUserLoginName());
tv_size.setText("剩余内存:" + AppUtils.getAvailableInternalMemorySize(context));
// + "," +
// AppUtils.getAvailableExternalMemorySize(context));
switch (SP.getInteger(STRING_KEY_mPublishPresetoption, 1)) {
case 1:
tv_fenbianlv.setText("640x480");
break;
case 2:
tv_fenbianlv.setText("1280x720");
break;
case 3:
tv_fenbianlv.setText("1920x1080");
break;
}
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
ttv_capture.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
mSurfaceTexture = surface;
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
});
}
//开始预览视屏
private void startPreviewCamera() {
mCamera = Camera.open();
Camera.Parameters paramOld = mCamera.getParameters();
Camera.Parameters param = mCamera.getParameters();
switch (SP.getInteger(STRING_KEY_photo, 3)) {
case 1://640x480
param.setPictureSize(640, 480);
break;
case 2://1280x720
param.setPictureSize(1280, 720);
break;
case 3://1920x1080
param.setPictureSize(1920, 1080);
break;
}
mCamera.setParameters(param);
try {
mCamera.setPreviewTexture(mSurfaceTexture);
} catch (IOException e) {
e.printStackTrace();
}
ttv_capture.setAlpha(1.0f);
ttv_capture.setRotation(90.0f);
mCamera.startPreview();
mCamera.setParameters(paramOld);
}
public void toggleOnlineOffline() {
HYClient.getSdkOptions().Capture().setCaptureOfflineMode(isOfflineMode);
isOfflineMode = !isOfflineMode;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_anjian:
//关联信息
if (ll_guanlian.getVisibility() == VISIBLE) {
ll_guanlian.setVisibility(GONE);
iv_anjian.setImageResource(R.drawable.zs_add);
} else {
ll_guanlian.setVisibility(VISIBLE);
iv_anjian.setImageResource(R.drawable.zs_lianjie);
}
break;
case R.id.tv_quxiao:
//取消关联
break;
case R.id.iv_camera:
break;
case R.id.iv_start_stop:
if (isRecord) {
isRecord = false;
iv_start_stop.setImageResource(R.drawable.zs_start_bg);
AppUtils.isCaptureLayoutShowing = false;
if (mMediaFile != null) {
mMediaFile = null;
}
HYClient.getHYCapture().stopCapture(new SdkCallback<CStopMobileCaptureRsp>() {
@Override
public void onSuccess(CStopMobileCaptureRsp cStopMobileCaptureRsp) {
startPreviewVideo(null, false);
}
@Override
public void onError(ErrorInfo errorInfo) {
}
});
} else {
startPreviewVideo(null, true);
}
break;
case R.id.iv_shanguang:
if (HYClient.getHYCapture().getCurrentCameraIndex() == HYCapture.Camera.Foreground) {
showToast(AppUtils.getString(R.string.cameraindex_notice));
return;
}
HYClient.getHYCapture().setTorchOn(!HYClient.getHYCapture().isTorchOn());
if (HYClient.getHYCapture().isTorchOn()) {
iv_shanguang.setImageResource(R.drawable.btn_shanguangdeng_press);
} else {
iv_shanguang.setImageResource(R.drawable.btn_shanguangdeng);
}
break;
case R.id.iv_change:
HYClient.getHYCapture().toggleInnerCamera();
break;
case R.id.iv_waizhi:
HYClient.getHYCapture().requestUsbCamera();
if (HYClient.getHYCapture().getCurrentCameraIndex() == HYCapture.Camera.USB) {
} else {
showToast(AppUtils.getString(R.string.out_camera));
}
break;
case R.id.iv_close:
stopCapture();
break;
case R.id.iv_suofang:
toggleBigSmall();
break;
case R.id.iv_take_photo:
if(isRecord) {
showToast("正在录制");
}
if (HYClient.getMemoryChecker().checkEnough()) {
HYClient.getHYCapture().stopCapture(null);
//拍照存放路径
mMediaFile = MediaFileDaoUtils.get().getImgRecordFile();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri;
if (Build.VERSION.SDK_INT >= 24) {
uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", new File(mMediaFile.getRecordPath()));
} else {
uri = Uri.fromFile(new File(mMediaFile.getRecordPath()));
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
((Activity)getContext()).startActivityForResult(intent, REQUEST_CODE_CAPTURE);
} else {
if (getVisibility() != GONE) {
((AppBaseActivity) getContext()).showToast(AppUtils.getString(R.string.local_size_max));
}
}
break;
}
}
public void onResume() {
Logger.debug("CaptureiewLayout onResume() " + isCapturing());
isPaused = false;
if (isCapturing())
HYClient.getHYCapture().setPreviewWindow(ttv_capture);
}
public void onPause() {
isPaused = true;
if (isCapturing())
HYClient.getHYCapture().setPreviewWindow(null);
}
public void onDestroy() {
if (MCApp.getInstance().getTopActivity() != null) {
MCApp.getInstance().getTopActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
if (isCapturing() || isCapturStarting()) {
stopCapture();
}
}
public void stopCapture() {
isRecord = false;
iv_start_stop.setImageResource(R.drawable.zs_start_bg);
if (isCapturing() || isCapturStarting()) {
AppUtils.isCaptureLayoutShowing = false;
if (mMediaFile != null) {
mMediaFile = null;
}
HYClient.getHYCapture().stopCapture(null);
HYClient.getSdkOptions().Capture().setCaptureOfflineMode(false);
if (HYClient.getSdkSamples().P2P().isBeingWatched() ||
HYClient.getSdkSamples().P2P().isTalking()) {
HYClient.getSdkSamples().P2P().stopAll();
}
view_cover.setVisibility(VISIBLE);
captureStatus = CAPTURE_STATUS_NONE;
userId.clear();
if (getVisibility() != GONE) {
((AppBaseActivity) getContext()).showToast(AppUtils.getString(R.string.stop_capture_success));
}
isFromGuanMo = false;
if (iCaptureStateChangeListener != null) {
iCaptureStateChangeListener.onClose();
}
}
//不管停止成功不成功,都要gone掉
setVisibility(GONE);
}
/**
* 开启观摩
*
* @param bean
*/
public void startCaptureFromUser(CaptureMessage bean) {
if (bean != null) {
if (!userId.contains(bean.fromUserId)) {
userId.add(bean.fromUserId);
}
if (isCapturStarting()) {
pendingMsg.add(bean);
}
}
if (isCapturing()) {
setVisibility(VISIBLE);
sendPlayerMessage();
} else {
}
}
/**
* 关闭观摩
*
* @param bean
*/
public void stopCaptureFromUser(StopCaptureMessage bean) {
if (userId.contains(bean.fromUserId)) {
userId.remove(bean.fromUserId);
}
if (userId.size() <= 0) {
if (isFromGuanMo) {
stopCapture();
}
}
}
private void sendPlayerMessage() {
if (pendingMsg.size() > 0) {
for (int i = 0; i < pendingMsg.size(); i++) {
CaptureMessage user = pendingMsg.get(i);
ChatUtil.get().rspGuanMo(user.fromUserId, user.fromUserDomain, user.fromUserName, user.sessionID);
}
// pendingMsg.clear();
}
}
public void startPreviewVideo(final CaptureMessage users, boolean localRecord) {
if (users != null) {
pendingMsg.add(users);
}
if (users != null) {
iv_start_stop.performClick();
} else {
mMediaFile = MediaFileDaoUtils.get().getVideoRecordFile();
boolean captureType = Boolean.parseBoolean(SP.getParam(CAPTURE_TYPE, STRING_KEY_false).toString());
if (captureType) {
HYClient.getSdkOptions().Capture().setCaptureOfflineMode(true);
} else {
HYClient.getSdkOptions().Capture().setCaptureOfflineMode(false);
}
final Capture.Params params;
if (localRecord) {
params = Capture.Params.get()
.setEnableServerRecord(false)
.setCaptureOrientation(HYCapture.CaptureOrientation.SCREEN_ORIENTATION_PORTRAIT)
.setRecordPath(mMediaFile.getRecordPath())
.setCameraIndex(SP.getInteger(STRING_KEY_camera, -1) == 1 ? HYCapture.Camera.Foreground : HYCapture.Camera.Background)
.setPreview(ttv_capture);
isRecord = true;
iv_start_stop.setImageResource(R.drawable.zs_start_rec_bg);
} else {
params = Capture.Params.get()
.setEnableServerRecord(false)
.setCaptureOrientation(HYCapture.CaptureOrientation.SCREEN_ORIENTATION_PORTRAIT)
.setCameraIndex(SP.getInteger(STRING_KEY_camera, -1) == 1 ? HYCapture.Camera.Foreground : HYCapture.Camera.Background)
.setPreview(ttv_capture);
}
toggleShuiYin();
((Activity) getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getLayoutParams().height = calcHeightHeight();
setVisibility(VISIBLE);
AppUtils.isCaptureLayoutShowing = true;
captureStatus = CAPTURE_STATUS_STARTING;
if (HYClient.getHYCapture().isCapturing()) {
HYClient.getHYCapture().stopCapture(new SdkCallback<CStopMobileCaptureRsp>() {
@Override
public void onSuccess(CStopMobileCaptureRsp resp) {
// 停止采集成功
startCapture(params);
}
@Override
public void onError(ErrorInfo errorInfo) {
// 停止采集失败
}
});
} else {
startCapture(params);
}
}
}
private void startCapture(Capture.Params params) {
HYClient.getHYCapture().startCapture(params,
new Capture.Callback() {
@Override
public void onRepeatCapture() {
captureStatus = CAPTURE_STATUS_CAPTURING;
view_cover.setVisibility(GONE);
sendPlayerMessage();
}
@Override
public void onSuccess(CStartMobileCaptureRsp resp) {
view_cover.setVisibility(GONE);
captureStatus = CAPTURE_STATUS_CAPTURING;
if (!AppUtils.isVideo && !AppUtils.isMeet && getVisibility() != GONE) {
((AppBaseActivity) getContext()).showToast(AppUtils.getString(R.string.capture_success));
}
sendPlayerMessage();
if (iCaptureStateChangeListener != null) {
iCaptureStateChangeListener.onOpen();
}
}
@Override
public void onError(ErrorInfo error) {
if (!AppUtils.isVideo && !AppUtils.isMeet && getVisibility() != GONE) {
((AppBaseActivity) getContext()).showToast(AppUtils.getString(R.string.capture_false));
onDestroy();
}
}
@Override
public void onCaptureStatusChanged(SdpMessageBase msg) {
}
});
}
public void toggleShowHide() {
if (!isCapturing()) {
return;
}
if (getVisibility() == VISIBLE) {
setVisibility(INVISIBLE);
if (iCaptureStateChangeListener != null) {
iCaptureStateChangeListener.hide();
}
} else {
setVisibility(VISIBLE);
if (iCaptureStateChangeListener != null) {
iCaptureStateChangeListener.show();
}
}
}
public void toggleShuiYin() {
String strOSDCommand = "drawtext=fontfile="
+ HYClient.getSdkOptions().Capture().getOSDFontFile()
+ ":fontcolor=white:x=0:y=0:fontsize=52:box=1:boxcolor=black:alpha=0.8:text=' "
+ AppDatas.Auth().getUserLoginName()
+ "'";
// OSD名称初始化
HYClient.getSdkOptions().Capture().setOSDCustomCommand(strOSDCommand);
}
private boolean isCapturing() {
return captureStatus == CAPTURE_STATUS_CAPTURING;
}
private boolean isCapturStarting() {
return captureStatus == CAPTURE_STATUS_STARTING;
}
public void toggleBigSmall() {
ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (getLayoutParams().width == LayoutParams.MATCH_PARENT) {
layoutParams.width = AppUtils.getSize(250);
layoutParams.height = calcHeightHeight();
FrameLayout.LayoutParams lp = (LayoutParams) fl_root.getLayoutParams();
lp.height = LayoutParams.MATCH_PARENT;
fl_root.setLayoutParams(lp);
} else {
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = LayoutParams.MATCH_PARENT;
if (SP.getParam(STRING_KEY_capture, "").toString().equals(STRING_KEY_VGA)) {
//手机一般都是16:9的,放大后要注意4:3的情况
FrameLayout.LayoutParams lp = (LayoutParams) fl_root.getLayoutParams();
lp.height = (int) (1.3333 * Float.valueOf(AppUtils.getScreenWidth()));
fl_root.setLayoutParams(lp);
}
}
setLayoutParams(layoutParams);
}
private int calcHeightHeight() {
int height = AppUtils.getSize(332);
switch (SP.getParam(STRING_KEY_capture, "").toString()) {
case STRING_KEY_VGA:
height = AppUtils.getSize(332);
break;
case STRING_KEY_HD720P:
height = AppUtils.getSize(415);
break;
case STRING_KEY_HD1080P:
height = AppUtils.getSize(415);
break;
}
return height;
}
ICaptureStateChangeListener iCaptureStateChangeListener;
public void setiCaptureStateChangeListener(ICaptureStateChangeListener iCaptureStateChangeListener) {
this.iCaptureStateChangeListener = iCaptureStateChangeListener;
}
public void toggleCapture() {
}
public interface ICaptureStateChangeListener {
void onOpen();
void onClose();
void hide();
void show();
}
}
|
/**
* project name:saas
* file name:SysUserService
* package name:com.cdkj.system.service.api
* date:2018/2/9 下午2:34
* author:bovine
* Copyright (c) CD Technology Co.,Ltd. All rights reserved.
*/
package com.cdkj.schedule.system.service.api;
import com.cdkj.common.base.service.api.BaseService;
import com.cdkj.model.system.pojo.SysUser;
/**
* description: 用户管理服务 <br>
* date: 2018/2/9 下午2:34
*
* @author bovine
* @version 1.0
* @since JDK 1.8
*/
public interface SysUserService extends BaseService<SysUser, String> {
/**
* 根据用户名获取用户信息
*
* @param username 用户名
* @return 用户信息
*/
SysUser selectByUsername(String username);
/**
* 根据用户名及登录源获取用户信息
*
* @param username 用户名
* @param sourceLogin 登录源:0:APP登录,1:后端登录
* @return 用户信息
*/
SysUser selectByUsernameAndSourceLogin(String username, int sourceLogin);
/**
* 根据用户名及登录源获取用户信息
*
* @param mobile 手机号
* @param sourceLogin 登录源:0:APP登录,1:后端登录
* @return 用户信息
*/
SysUser selectByMobileAndSourceLogin(String mobile, int sourceLogin);
}
|
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* Leetcode做题-最小的k个数 https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/
*/
public class 最小的k个数 {
public static void main(String[] args) {
getLeastNumbers2(new int[]{4,5,1,6,2,7,3,8}, 3);
}
public static int[] getLeastNumbers2(int[] arr, int k) {
if (k == 0 || arr.length == 0) {
return new int[0];
}
// 统计每个数字出现的次数
int[] counter = new int[10001];
for (int num: arr) {
counter[num]++;
}
// 根据counter数组从头找出k个数作为返回结果
int[] res = new int[k];
int idx = 0;
for (int num = 0; num < counter.length; num++) {
while (counter[num]-- > 0 && idx < k) {
res[idx++] = num;
}
if (idx == k) {
break;
}
}
return res;
}
public int[] getLeastNumbers(int[] arr, int k) {
Queue<Integer> queue=new PriorityQueue<>();
for(int i:arr){
queue.add(i);
}
int[] r=new int[k];
while (k>0){
r[k-1]=queue.remove();
k--;
}
return r;
}
}
|
package com.yu.hu.navigationtest;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.yu.hu.navigationtest.databinding.FragmentMainBinding;
/**
* A simple {@link Fragment} subclass.
*/
public class MainFragment extends Fragment {
private FragmentMainBinding mDataBinding;
private View mRootView;
public MainFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mDataBinding = FragmentMainBinding.inflate(inflater, container, false);
mRootView = mDataBinding.getRoot();
return mRootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//通过bundle传递参数
mDataBinding.toBlankBtn.setOnClickListener(v -> {
//通过Bundle传递数据
Bundle bundle = new Bundle();
bundle.putInt("mode", 0);
bundle.putString("text", mDataBinding.editText.getText().toString());
Navigation.findNavController(mRootView)
//.navigate(R.id.to_blank); //不传值
.navigate(R.id.to_blank, bundle);
});
//通过safeArgs传参
mDataBinding.toBlankBtn2.setOnClickListener(v -> {
//如果args中设置了defaultValue,咋不需要必传
//如果没设置,则必须要传 见nav_graph.xml
MainFragmentDirections.ToBlank toBlank =
MainFragmentDirections.toBlank(mDataBinding.editText.getText().toString())
.setMode(1);
Navigation.findNavController(mRootView)
.navigate(toBlank);
});
}
}
|
package wiki.neoul.pado.domain.account;
public class Account {
}
|
package triangulo;
import static org.junit.Assert.*;
import org.junit.Test;
public class TrianguloTest {
@Test
public void testCrearTriangulo() {
Triangulo unTriangulo;
unTriangulo = new Triangulo(10.0, 8.0, 8.0, 12.0);
assertNotNull(unTriangulo);
Triangulo otroTriangulo;
otroTriangulo = new Triangulo(5.0, 4.0, 4.0, 6.0);
assertNotNull(otroTriangulo);
}
@Test
public void testPerimetroTriangulo() {
Triangulo unTriangulo;
unTriangulo = new Triangulo(10.0, 8.0, 8.0, 12.0);
Double esperado = 26.0;
Double actual = unTriangulo.calcularPerimetroTriangulo();
assertEquals(esperado, actual);
}
@Test
public void testAreaTriangulo() {
Triangulo otroTriangulo;
otroTriangulo = new Triangulo(5.0, 4.0, 4.0, 6.0);
Double esperado = 15.0;
Double actual = otroTriangulo.calcularAreaTriangulo();
assertEquals(esperado, actual);
}
}
|
package tp.pr1.lists;
import tp.pr1.objects.Zombie;
public class ZombieList {
private Zombie[] listaZombies;
private int contZombies;
public ZombieList() {
contZombies = 0;
listaZombies = new Zombie[10];
}
public int getContadorZombie() { //Devuelve el contador de la lista
return contZombies;
}
public void crearZombie(Zombie zombie) { //crear un elemento en la lista
listaZombies[contZombies] = zombie;
contZombies++;
}
public void quitarVidaZ(int posXL, int posYL){
boolean encontrado=false;
int i = 0;
while(!encontrado && i < contZombies) {
encontrado = listaZombies[i].coincide(posXL,posYL); //compara las coordenadas del zombie con las del peashooter para saber si hay un zombie delante y quitarle vida
if (encontrado) {
if (listaZombies[i].getResistenciaZombie() == 0)
matarZombies(i); //si la vida del zombie está a cero, se elimina del array => desplazar array hacia la izquierda
}
if (!encontrado)
i++;
}
}
public void matarZombies(int posZombieArray) {
for (int i = posZombieArray + 1; i < contZombies; i++) // desplazar array hacia la izquierda
listaZombies[i - 1] = listaZombies[i];
contZombies--;
}
public boolean coincide(int posXZ, int posYZSiguiente){
boolean libre = false;
int i = 0;
while(!libre && i< contZombies) {
libre = listaZombies[i].coincideZ(posXZ, posYZSiguiente); //Compara las coordenadas del zombie con => las del zombie (casilla siguiente libre)
if(!libre)
i++;
}
return libre;
}
public boolean updateZ(){ //recorre la lista de zombie para que cada zombie ejecute su update
boolean llegaFinal = false;
int i = 0;
while(i < contZombies && !llegaFinal) {
llegaFinal = listaZombies[i].updateZombie(); //Si durante el update de algún zombie, llega al final del tablero, finaliza la partida y ganan los zombies
i++;
}
return llegaFinal;
}
public String detectarElemento(int posX, int posY){ //Si al recorrer las listas para mostrar el tablero, coincide esa coordenada con las de un peashooter, devuelve "Z" y su resistencia
boolean encontrado = false;
String elemento = "";
int i = 0;
while(!encontrado && i < contZombies) {
encontrado = listaZombies[i].coincideZ(posX, posY);
if (encontrado)
elemento = "Z" + " [" + listaZombies[i].getResistenciaZombie() + "]";
else
i++;
}
return elemento;
}
}
|
package com.java8.concurrency.callables;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.Future;
/**
* This program loops through all the files in a directory and prints the sum of total number
* of lines in each files.
*
*/
public class FilesLineCounter {
private Path dir = Paths.get("src" ,"main", "java" , "concurrency");
public long computeTotalNumberOflines(){
long total = 0;
try {
//total = executeCounters().stream().mapToLong(this :: extractValueFromFuture).sum();
} catch (Exception e) {
// TODO: handle exception
}
return 0;
}
private List<Future<Long>> executeCounters() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.culturaloffers.maps.services;
import com.culturaloffers.maps.model.GeoLocation;
import com.culturaloffers.maps.repositories.GeoLocationRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static com.culturaloffers.maps.constants.GeoLocationConstants.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource("classpath:test-user-geo.properties")
public class GeoLocationServiceUnitTest {
@Autowired
private GeoLocationService geoLocationService;
@MockBean
private GeoLocationRepository geoLocationRepository;
@Before
public void setup() {
GeoLocation geoLocation = new GeoLocation(
NEW_GEO_LOCATION_LATITUDE,
NEW_GEO_LOCATION_LONGITUDE,
NEW_GEO_LOCATION_ADDRESS
);
GeoLocation createdGeoLocation = new GeoLocation(
NEW_GEO_LOCATION_LATITUDE,
NEW_GEO_LOCATION_LONGITUDE,
NEW_GEO_LOCATION_ADDRESS
);
createdGeoLocation.setId(NEW_GEO_LOCATION_ID);
given(geoLocationRepository.findById(NEW_GEO_LOCATION_ID)).willReturn(Optional.of(createdGeoLocation));
given(geoLocationRepository.findByLatitudeAndLongitude(
NEW_GEO_LOCATION_LATITUDE, NEW_GEO_LOCATION_LONGITUDE)).willReturn(null);
given(geoLocationRepository.findByAddress(NEW_GEO_LOCATION_ADDRESS)).willReturn(null);
given(geoLocationRepository.save(geoLocation)).willReturn(createdGeoLocation);
given(geoLocationRepository.findById(BAD_GEO_LOCATION_ID)).willReturn(Optional.empty());
GeoLocation found = new GeoLocation(
DB_GEO_LOCATION_LATITUDE,
DB_GEO_LOCATION_LONGITUDE,
DB_GEO_LOCATION_ADDRESS
);
found.setId(DB_GEO_LOCATION_ID);
given(geoLocationRepository.findByLatitudeAndLongitude(
DB_GEO_LOCATION_LATITUDE, DB_GEO_LOCATION_LONGITUDE)).willReturn(found);
given(geoLocationRepository.findByAddress(DB_GEO_LOCATION_ADDRESS)).willReturn(found);
given(geoLocationRepository.findById(DB_GEO_LOCATION_ID)).willReturn(Optional.of(found));
doNothing().when(geoLocationRepository).delete(createdGeoLocation);
}
@Test
public void testDeleteByAddressOk() {
boolean deleted = geoLocationService.delete(DB_GEO_LOCATION_ADDRESS);
verify(geoLocationRepository, times(1)).findByAddress(DB_GEO_LOCATION_ADDRESS);
assertTrue(deleted);
}
@Test
public void testDeleteByLatitudeAndLongitudeOk() {
boolean deleted = geoLocationService.delete(DB_GEO_LOCATION_LATITUDE, DB_GEO_LOCATION_LONGITUDE);
verify(geoLocationRepository, times(1))
.findByLatitudeAndLongitude(DB_GEO_LOCATION_LATITUDE, DB_GEO_LOCATION_LONGITUDE);
assertTrue(deleted);
}
@Test
public void testDeleteByIdOk() {
boolean deleted = geoLocationService.delete(DB_GEO_LOCATION_ID);
verify(geoLocationRepository, times(1)).findById(DB_GEO_LOCATION_ID);
assertTrue(deleted);
}
@Test
public void testDeleteWrongCoords() {
boolean deleted = geoLocationService.delete(NEW_GEO_LOCATION_LATITUDE, NEW_GEO_LOCATION_LONGITUDE);
verify(geoLocationRepository, times(1))
.findByLatitudeAndLongitude(NEW_GEO_LOCATION_LATITUDE, NEW_GEO_LOCATION_LONGITUDE);
assertFalse(deleted);
}
@Test
public void testDeleteWrongAddress() {
boolean deleted = geoLocationService.delete(NEW_GEO_LOCATION_ADDRESS);
verify(geoLocationRepository, times(1)).findByAddress(NEW_GEO_LOCATION_ADDRESS);
assertFalse(deleted);
}
@Test
public void testDeleteBadId() {
boolean deleted = geoLocationService.delete(BAD_GEO_LOCATION_ID);
verify(geoLocationRepository, times(1)).findById(BAD_GEO_LOCATION_ID);
assertFalse(deleted);
}
@Test
public void testInsert() {
GeoLocation geoLocation = new GeoLocation(
NEW_GEO_LOCATION_LATITUDE,
NEW_GEO_LOCATION_LONGITUDE,
NEW_GEO_LOCATION_ADDRESS
);
GeoLocation created = geoLocationService.insert(geoLocation);
verify(geoLocationRepository, times(1)).findByAddress(NEW_GEO_LOCATION_ADDRESS);
verify(geoLocationRepository, times(1)).save(geoLocation);
assertEquals(NEW_GEO_LOCATION_ADDRESS, created.getAddress());
}
@Test
public void testInsertExistAddress() {
GeoLocation geoLocation = new GeoLocation(
NEW_GEO_LOCATION_LATITUDE,
NEW_GEO_LOCATION_LONGITUDE,
DB_GEO_LOCATION_ADDRESS
);
GeoLocation created = geoLocationService.insert(geoLocation);
verify(geoLocationRepository, times(1)).findByAddress(DB_GEO_LOCATION_ADDRESS);
verify(geoLocationRepository, times(0)).save(geoLocation);
assertNull(created);
}
@Test
public void testUpdateOk() {
GeoLocation geoLocation = new GeoLocation(
NEW_GEO_LOCATION_LATITUDE,
NEW_GEO_LOCATION_LONGITUDE,
NEW_GEO_LOCATION_ADDRESS
);
GeoLocation updatedGeoLocation = geoLocationService.update(DB_GEO_LOCATION_ID, geoLocation);
verify(geoLocationRepository, times(1)).findById(DB_GEO_LOCATION_ID);
verify(geoLocationRepository, times(1)).findByAddress(NEW_GEO_LOCATION_ADDRESS);
verify(geoLocationRepository, times(1)).save(geoLocation);
assertEquals(NEW_GEO_LOCATION_ADDRESS, updatedGeoLocation.getAddress());
assertEquals(NEW_GEO_LOCATION_LATITUDE, updatedGeoLocation.getLatitude(), DELTA);
assertEquals(NEW_GEO_LOCATION_LONGITUDE, updatedGeoLocation.getLongitude(), DELTA);
}
@Test
public void testUpdateSameAddress() {
GeoLocation geoLocation = new GeoLocation(
NEW_GEO_LOCATION_LATITUDE,
NEW_GEO_LOCATION_LONGITUDE,
DB_GEO_LOCATION_ADDRESS
);
GeoLocation updatedGeoLocation = geoLocationService.update(NEW_GEO_LOCATION_ID, geoLocation);
verify(geoLocationRepository, times(1)).findById(NEW_GEO_LOCATION_ID);
verify(geoLocationRepository, times(1)).findByAddress(DB_GEO_LOCATION_ADDRESS);
verify(geoLocationRepository, times(0)).save(geoLocation);
assertNull(updatedGeoLocation);
}
}
|
package Model;
import java.awt.*;
/**
* Class that models a cartransport which extends the class Model.Truck
*/
public class CarTransport extends Truck {
/**
* a boolean which determines if ramp of Model.CarTransport is up or down
*/
private boolean rampDown=false;
/**
* The cargo of Model.CarTransport
*/
private Cargo c;
/**
* The amount of space the transport has
*/
private final int space = 5;
/**
* The maximum amount of weight of a car that is to be loaded
*/
private final int maxWeight=2000;
/**Constructor
* @param nrDoors
* @param enginePower
* @param color
* @param modelname
*/
public CarTransport(int nrDoors, double enginePower, Color color, String modelname,int x, int y){
super(2,80,color.BLUE,"Billy",15000,x,y);
c = new Cargo();
}
/**
* Method that checks if ramp is deployed
* @return boolean (true if ramp is deployed)
*/
public boolean isRampDeployed(){
if(rampDown==false){
return false;
}
return true;
}
/**
* Method to deploy ramp of a cartransport
*/
public void deployRamp(){
if (canBedBeResetedOrDeployed())
this.rampDown=true;
}
/**
* Method to reset ramp of a cartransport
*/
public void resetRamp(){
if (canBedBeResetedOrDeployed())
this.rampDown=false;
}
/**
* Method to calculate speedfactor of cartransport which is used to calculate the amount of gas
* @return double speedfactor
*/
public double speedFactor(){
return getEnginePower() * 0.01;
}
/**
* Method to check if a car can be loaded to a cartransport
* @param car Model.Car that wants to loaded
* @return boolean (true if car can be loaded)
*/
private boolean canLoadCar(Car car){
if (isRampDeployed()&&c.isCloseEnoughToLoad(getX(),getY(),car.getX(),car.getY(),space)&&!c.isCargoToBig(maxWeight,car)){
return true;
}
else return false;}
/**
* Method to load a car from cartransport
* @param car Model.Car that is being loaded to cartransport
*/
public void loadTransport(Car car){
if (canLoadCar(car)){
car.stopEngine();
c.loadCargo(car);
}
else throw new IllegalArgumentException("Cant load transport"); }
/**
* Method to unload a car from cartransport
*/
public void unloadTransport(){
if (!c.isEmpty()&&getCurrentSpeed()==0){
Car car = c.unloadCargo(c.getAmountOfCargo()-1);
car.setX(getX()-10);
car.setY(getY()-10);
}
else throw new IllegalArgumentException("Cant unload transport");
}
/**
* Method to make a cartransport and the cars it's carrying move
*/
@Override
public void move(){
super.move();
for (int i=0;i<c.getAmountOfCargo();i++){
Car car = c.getIndividualCargo(i);
car.setX(getX());
car.setY(getY());
}
}
}
|
import de.tum.in.cm.java.dissim.Algorithm;
import de.tum.in.cm.java.dissim.Main;
import de.tum.in.cm.java.dissim.SimEvent;
import de.tum.in.cm.java.dissim.events.CreateLeaderEvent;
import org.junit.Test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.util.Collection;
import static org.junit.Assert.*;
/**
* @author teemuk
*/
public class CreateLeaderEventTests {
//==============================================================================================//
// Setup/cleanup
//==============================================================================================//
@BeforeClass
public static void setUpBeforeClass()
throws Exception {
}
@AfterClass
public static void tearDownAfterClass()
throws Exception {
}
//==============================================================================================//
//==============================================================================================//
// Tests
//==============================================================================================//
@Test
public void testProcess()
throws Exception {
final double eventTime = 10.0;
final double channelCapacity = 5.0;
final int[] clients = getSequence( 20, 1 );
final int[] channels = getSequence( 4, 1 );
final double[] channelCaps = { 1.0, 1.0, 1.0, 1.0 };
final CreateLeaderEvent event = new CreateLeaderEvent( eventTime,
0, 1, channelCapacity, clients, channels, channelCaps, new Main.Args( new String[0] ) );
final Collection <SimEvent> events = event.process();
for ( final SimEvent e : events ) {
System.out.println( e.toString() );
}
}
//==============================================================================================//
//==============================================================================================//
// Private
//==============================================================================================//
private static int[] getSequence( final int count, final int firstVal ) {
final int[] vals = new int[ count ];
for ( int i = 0; i < count; i++ ) {
vals[ i ] = firstVal + i;
}
return vals;
}
//==============================================================================================//
}
|
package jsoup.bean;
public class Rule {
private String url;
private String[] params;
private String[] values;
private String resultTagName;
private int type = ID;
private int requestMoethod = GET;
public static final int GET = 0;
public static final int POST = 1;
public static final int CLASS = 0;
public static final int ID = 1;
public static final int SELECTION = 2;
public static final int TAG = 3;
public Rule(String url, String[] params, String[] values,
String resultTagName, int type, int requestMoethod) {
super();
this.url = url;
this.params = params;
this.values = values;
this.resultTagName = resultTagName;
this.type = type;
this.requestMoethod = requestMoethod;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String[] getParams() {
return params;
}
public void setParams(String[] params) {
this.params = params;
}
public String[] getValues() {
return values;
}
public void setValues(String[] values) {
this.values = values;
}
public String getResultTagName() {
return resultTagName;
}
public void setResultTagName(String resultTagName) {
this.resultTagName = resultTagName;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getRequestMoethod() {
return requestMoethod;
}
public void setRequestMoethod(int requestMoethod) {
this.requestMoethod = requestMoethod;
}
}
|
package Application.Algorithm;
import java.util.*;
public class PSO {
private static Random r = new Random();
public static CurrentState init(Problem problem, Parameters initParams) {
int noOfParameters = problem.parametersDomains.size();
Particle[] particleList = new Particle[initParams.particlesNo];
Double[] globalBestPosition = new Double[noOfParameters];
Arrays.fill(globalBestPosition, Double.MAX_VALUE);
for (int i = 0; i < initParams.particlesNo; ++i) {
Double[] position = new Double[noOfParameters];
Double[] velocity = new Double[noOfParameters];
for (int j = 0; j < noOfParameters; ++j) {
Double min = problem.parametersDomains.get(j)[0];
Double max = problem.parametersDomains.get(j)[1];
position[j] = min + (max - min) * r.nextDouble();
velocity[j] = r.nextDouble() * initParams.maxVelocity;
}
Particle particle = Particle.builder()
.position(position)
.bestPersonalPosition(position)
.velocity(velocity)
.build();
particle.setCost(problem.objectiveFunction.apply(particle.position));
particleList[i] = particle;
}
return CurrentState.builder()
.globalBestCost(Double.MAX_VALUE)
.globalBestPosition(globalBestPosition)
.parameters(initParams)
.particleList(particleList)
.problem(problem)
.currentIteration(0)
.build();
}
public static CurrentState particleSwarmOptimize(CurrentState oldstate) {
Parameters parameters = oldstate.parameters;
Particle[] newParticles = new Particle[parameters.particlesNo];
int noOfParameters = oldstate.problem.parametersDomains.size();
Double newGlobalBestCost = Double.MAX_VALUE;
Double[] newGlobalBestPosition = oldstate.getGlobalBestPosition();
for (int i = 0; i < parameters.particlesNo; ++i) {
Particle p = oldstate.particleList[i];
newParticles[i] = Particle.builder()
.bestPersonalPosition(Arrays.copyOf(p.bestPersonalPosition, p.bestPersonalPosition.length))
.position(Arrays.copyOf(p.position, p.position.length))
.velocity(Arrays.copyOf(p.velocity, p.velocity.length))
.cost(p.cost)
.build();
}
for (int i = 0; i < parameters.particlesNo; ++i) {
Double[] position = new Double[noOfParameters];
for (int j = 0; j < noOfParameters; ++j) {
position[j] = oldstate.problem.parametersDomains.get(j)[0];
}
newParticles[i].position = position;
}
for (int i = 0; i < parameters.particlesNo; ++i) {
Particle p = newParticles[i];
Double potentialCost = oldstate.problem
.objectiveFunction.apply(oldstate
.particleList[i]
.position);
if (potentialCost < oldstate.particleList[i].cost) {
p.setBestPersonalPosition(oldstate.particleList[i].position);
p.setCost(potentialCost);
} else {
p.setBestPersonalPosition(oldstate.particleList[i].bestPersonalPosition);
p.setCost(oldstate.particleList[i].cost);
}
if (p.getCost() < newGlobalBestCost) {
newGlobalBestCost = p.getCost();
newGlobalBestPosition = p.getBestPersonalPosition();
}
newParticles[i] = p;
}
Double W = parameters.inertia;
Double c1 = parameters.c1;
Double c2 = parameters.c2;
for (int i = 0; i < parameters.particlesNo; ++i) {
boolean areNewPositionsInDomain = true;
Particle p = newParticles[i];
Double[] oldPosition = oldstate.particleList[i].getPosition();
Double[] oldVelocity = oldstate.particleList[i].getVelocity();
for (int k = 0; k < noOfParameters; ++k) {
double r1 = r.nextDouble();
double r2 = r.nextDouble();
Double newVelocity = W * oldVelocity[k] +
c1 * r1 * (p.bestPersonalPosition[k] - oldPosition[k]) +
c2 * r2 * (newGlobalBestPosition[k] - oldPosition[k]);
Double newPosition = newVelocity + oldPosition[k];
p.getVelocity()[k] = newVelocity;
p.getPosition()[k] = newPosition;
areNewPositionsInDomain = areNewPositionsInDomain
&& oldstate.problem.parametersDomains.get(k)[0] <= p.getPosition()[k]
&& oldstate.problem.parametersDomains.get(k)[1] >= p.getPosition()[k];
}
if (!areNewPositionsInDomain) {
for (int k = 0; k < noOfParameters; ++k) {
Double min = oldstate.problem.parametersDomains.get(k)[0];
Double max = oldstate.problem.parametersDomains.get(k)[1];
Double newPosition = min + (max - min) * r.nextDouble();
p.getPosition()[k] = newPosition;
}
}
newParticles[i] = p;
}
return CurrentState.builder()
.currentIteration(oldstate.currentIteration + 1)
.globalBestPosition(newGlobalBestPosition)
.globalBestCost(newGlobalBestCost)
.problem(oldstate.problem)
.parameters(oldstate.parameters)
.particleList(newParticles)
.build();
}
public static CurrentState solve(CurrentState initialState) {
CurrentState resultedState = initialState;
int noOfIterations = resultedState.parameters.maxIterations;
double inertiaDecreasingStep = (initialState.parameters.inertia - 0.1) / noOfIterations > 0 ?
(initialState.parameters.inertia - 0.1) / noOfIterations : 0;
for (int i = 0; i < noOfIterations; ++i) {
resultedState = particleSwarmOptimize(resultedState);
resultedState.parameters.inertia -= inertiaDecreasingStep;
}
return resultedState;
}
}
|
package com.example.pmsl.filemanager;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by pmsl on 16-4-8.
*/
public class LocalFragment extends Fragment {
private View view;
static TabFragmentAdapter.CategorySecondFragmentListener listener;
public ArrayList<Map<String, Object>> storage = new ArrayList<>();
private static LocalFragment sLocalFragment;
public static LocalFragment newInstance(TabFragmentAdapter.CategorySecondFragmentListener listener) {
LocalFragment.listener = listener;
sLocalFragment = new LocalFragment();
return sLocalFragment;
}
public static LocalFragment getInstance() {
return sLocalFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_local, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!("".equals(Tools.getPrimaryStoragePath()))) {
String storagePath = Tools.getPrimaryStoragePath();
Map<String, Object> InternalMemory = new HashMap<>();
InternalMemory.put("path", storagePath);
InternalMemory.put("storageImage", R.drawable.internalstorage);
InternalMemory.put("name", "内置存储");
InternalMemory.put("storageInfo", "总共:" + Tools.getTotalInternalMemorySize() + ", 可用:" + Tools.getAvailableInternalMemorySize());
storage.add(InternalMemory);
}
if (!("".equals(Tools.getSecondaryStoragePath()))) {
String storagePath = Tools.getSecondaryStoragePath();
Map<String, Object> ExternalMemory = new HashMap<>();
ExternalMemory.put("path", storagePath);
ExternalMemory.put("name", "SD卡");
ExternalMemory.put("storageImage", R.drawable.sdcard);
ExternalMemory.put("storageInfo", "总共:" + Tools.getTotalExternalMemorySize() + ", 可用:" + Tools.getAvailableExternalMemorySize());
storage.add(ExternalMemory);
}
ListView local = (ListView) view.findViewById(R.id.local);
local.setOnItemClickListener(new LocalItemClickListen());
local.setAdapter(new LocalAdapter(getContext()));
// ((MainActivity)getActivity()).setBelowMenu(MainActivity.LOCALFRAGMENT);
// final LinearLayout belowOperationMenu = (LinearLayout) view.findViewById(R.id.local_below_operation_menu);
// CheckBox mkdir = (CheckBox) view.findViewById(R.id.local_mkdir);
// CheckBox cancelOperation = (CheckBox) view.findViewById(R.id.local_cancel_operation);
// CheckBox paste = (CheckBox) view.findViewById(R.id.local_paste);
// CheckBox move = (CheckBox) view.findViewById(R.id.local_move);
// switch (FilesOperation.operationState) {
// default:
// case MainActivity.COPYING_STATE:
// belowOperationMenu.setVisibility(View.VISIBLE);
// mkdir.setVisibility(View.VISIBLE);
// cancelOperation.setVisibility(View.VISIBLE);
// paste.setVisibility(View.VISIBLE);
// move.setVisibility(View.GONE);
// break;
// case MainActivity.MOVING_STATE:
// belowOperationMenu.setVisibility(View.VISIBLE);
// mkdir.setVisibility(View.VISIBLE);
// cancelOperation.setVisibility(View.VISIBLE);
// paste.setVisibility(View.GONE);
// move.setVisibility(View.VISIBLE);
// break;
// case MainActivity.DEFAULT_STATE:
// belowOperationMenu.setVisibility(View.GONE);
// break;
//
// }
// cancelOperation.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// FilesOperation.operationState=MainActivity.DEFAULT_STATE;
// belowOperationMenu.setVisibility(View.GONE);
// }
// });
}
@Override
public void onDestroy() {
super.onDestroy();
storage.clear();
}
public class LocalAdapter extends BaseAdapter {
LayoutInflater layoutInflater;
public LocalAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return storage.size();
}
@Override
public Object getItem(int position) {
return storage.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.fragment_local_item, null);
viewHolder.storageImage = (ImageView) convertView.findViewById(R.id.storageImage);
viewHolder.storageName = (TextView) convertView.findViewById(R.id.storageName);
viewHolder.storageInfo = (TextView) convertView.findViewById(R.id.storageInfo);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.storageImage.setImageResource((Integer) storage.get(position).get("storageImage"));
viewHolder.storageName.setText(storage.get(position).get("name").toString());
viewHolder.storageInfo.setText(storage.get(position).get("storageInfo").toString());
return convertView;
}
public class ViewHolder {
ImageView storageImage;
TextView storageName;
TextView storageInfo;
}
}
public class LocalItemClickListen implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, Object> map = new HashMap<>();
map.put("storageRootName", storage.get(position).get("name"));
map.put("storageRootPath", storage.get(position).get("path"));
map.put("name", storage.get(position).get("name"));
map.put("path", storage.get(position).get("path"));
((MainActivity) getActivity()).setBelowMenu(MainActivity.LOCALPATHFRAGMENT);
listener.onNextFragment(map);
}
}
public static int backPressed() {
if (listener.isNext) {
if (LocalPathFragment.isShow) {
LocalPathFragment.isShow = false;
LocalPathFragment.isUpdateImage = false;
LocalPathFragment.localPathAdapter.notifyDataSetChanged();
return MainActivity.RESTORE_INIT_STATE;
} else {
HashMap<String, Object> map = new HashMap<>();
String storageName = LocalPathFragment.filePath.substring(LocalPathFragment.filePath.lastIndexOf("/") + 1);
// String storageName = LocalPathFragment.filePath.substring(LocalPathFragment.filePath.lastIndexOf("/")+1);
String storagePath = LocalPathFragment.filePath.substring(0, LocalPathFragment.filePath.lastIndexOf("/"));
// String storagePath = LocalPathFragment.filePath.substring(0, LocalPathFragment.filePath.lastIndexOf("/"));
// Log.i("TAG", storagePath);
if (LocalPathFragment.filePath.equals(LocalPathFragment.rootPath)) {
Log.i("TAG", LocalPathFragment.rootPath);
listener.onPreviousFragment(null);
} else {
map.put("storageRootName", LocalPathFragment.rootName);
map.put("storageRootPath", LocalPathFragment.rootPath);
map.put("name", storageName);
map.put("path", storagePath);
listener.onPreviousFragment(map);
}
return MainActivity.RETURN_PREVIOUS_FRAGMENT;
}
} else {
return MainActivity.EXIT_ACTIVITY;
}
}
}
|
package com.jongewaard.dev.barberbooking.Fragments;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import com.jongewaard.dev.barberbooking.Common.Common;
import com.jongewaard.dev.barberbooking.Model.BookingInformation;
import com.jongewaard.dev.barberbooking.R;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import dmax.dialog.SpotsDialog;
import io.paperdb.Paper;
public class BookingStep4Fragment extends Fragment {
SimpleDateFormat simpleDateFormat;
LocalBroadcastManager localBroadcastManager;
Unbinder unbinder;
AlertDialog dialog;
static BookingStep4Fragment instance;
@BindView(R.id.txt_booking_barber_text)
TextView txt_booking_barber_text;
@BindView(R.id.txt_booking_time_text)
TextView txt_booking_time_text;
@BindView(R.id.txt_salon_address)
TextView txt_salon_address;
@BindView(R.id.txt_salon_name)
TextView txt_salon_name;
@BindView(R.id.txt_salon_open_hours)
TextView txt_salon_open_hours;
@BindView(R.id.txt_salon_phone)
TextView txt_salon_phone;
@BindView(R.id.txt_salon_website)
TextView txt_salon_website;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Aply format for date diplay confirm
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
localBroadcastManager = LocalBroadcastManager.getInstance(getContext());
localBroadcastManager.registerReceiver(confirmBookingReceiver, new IntentFilter(Common.KEY_CONFIRM_BOOKING));
dialog = new SpotsDialog.Builder().setContext(getContext()).setCancelable(false)
.build();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View itemView = inflater.inflate(R.layout.fragment_booking_step_four, container, false);
unbinder = ButterKnife.bind(this, itemView);
return itemView;
}
@OnClick(R.id.btn_confirm)
void confirmBooking(){
dialog.show();
/* Procces Timestamp
* We will use Timestamp to filter all booking with date is greater today
* for only display all future booking
* */
String startTime = Common.convertTimeSlotToString(Common.currentTimeSlot);
String[] convertTime = startTime.split("-"); //Split ex : 9:00 - 10:00
//Get start time : get 9:00
String[] startTimeConvert = convertTime[0].split(":");
int startHourInt = Integer.parseInt(startTimeConvert[0].trim()); // we get 9
int startMinInt = Integer.parseInt(startTimeConvert[1].trim()); //We get 00
Calendar bookingDateWithourHouse = Calendar.getInstance();
bookingDateWithourHouse.setTimeInMillis(Common.bookingDate.getTimeInMillis());
bookingDateWithourHouse.set(Calendar.HOUR_OF_DAY, startHourInt);
bookingDateWithourHouse.set(Calendar.MINUTE, startMinInt);
//Create timestamp object and apply to BookingInformation
Timestamp timestmp = new Timestamp(bookingDateWithourHouse.getTime());
//Create booking information
final BookingInformation bookingInformation = new BookingInformation();
bookingInformation.setCityBook(Common.city);
bookingInformation.setTimestamp(timestmp); //Aqui agrego toda la config. de la hora
bookingInformation.setDone(false); //Always FALSE, because we will use this field
// to filter display on user
bookingInformation.setBarberId(Common.currentBarber.getBarberId());
bookingInformation.setBarberName(Common.currentBarber.getName());
bookingInformation.setCustomerName(Common.currentUser.getName());
bookingInformation.setCustomerPhone(Common.currentUser.getPhoneNumber());
bookingInformation.setSalonId(Common.currentSalon.getSalonId());
bookingInformation.setSalonAddress(Common.currentSalon.getAddress());
bookingInformation.setSalonName(Common.currentSalon.getName());
bookingInformation.setTime(new StringBuilder(Common.convertTimeSlotToString(Common.currentTimeSlot))
.append(" at ")
.append(simpleDateFormat.format(bookingDateWithourHouse.getTime())).toString());
bookingInformation.setSlot(Long.valueOf(Common.currentTimeSlot));
//Submit to Barber document
DocumentReference bookingDate = FirebaseFirestore.getInstance()
.collection("AllSalon")
.document(Common.city)
.collection("Branch")
.document(Common.currentSalon.getSalonId())
.collection("Barbers")
.document(Common.currentBarber.getBarberId())
.collection(Common.simpleFormatDate.format(bookingDateWithourHouse.getTime())) //es el bookDate de este método!
.document(String.valueOf(Common.currentTimeSlot)); //bookDate is date simpleformat with dd_MMM_yyyy
//write data
bookingDate.set(bookingInformation)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//Here we can write an funcion to check if already exist an booking,
// we will prevent new booking
addToUserBooking(bookingInformation);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void addToUserBooking(final BookingInformation bookingInformation) {
resetStaticData();
getActivity().finish(); //close ACTIVITY
//Firs, create new collection
final CollectionReference userBooking = FirebaseFirestore.getInstance()
.collection("User")
.document(Common.currentUser.getPhoneNumber())
.collection("Booking");
//Check if exist document in this collection
//Get current date
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
Timestamp toDayTimeStamp = new Timestamp(calendar.getTime());
userBooking
.whereGreaterThanOrEqualTo("timestamp", toDayTimeStamp)
.whereEqualTo("done", false)
.limit(1) //Only take 1
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.getResult().isEmpty())
{
//Set data
userBooking.document()
.set(bookingInformation)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
if(dialog.isShowing())
dialog.dismiss();
addToCalendar(Common.bookingDate,
Common.convertTimeSlotToString(Common.currentTimeSlot));
resetStaticData();
getActivity().finish(); //close ACTIVITY
Toast.makeText(getContext(), "Success!", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if(dialog.isShowing())
dialog.dismiss();
Toast.makeText(getContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else
{
if(dialog.isShowing() && dialog != null)
dialog.dismiss();
resetStaticData();
getActivity().finish(); //close ACTIVITY
Toast.makeText(getContext(), "Unsuccessfully!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void addToCalendar(Calendar bookingDate, String startDate) {
String startTime = Common.convertTimeSlotToString(Common.currentTimeSlot);
String[] convertTime = startTime.split("-"); //Split ex : 9:00 - 10:00
//Get start time : get 9:00
String[] startTimeConvert = convertTime[0].split(":");
int startHourInt = Integer.parseInt(startTimeConvert[0].trim()); // we get 9
int startMinInt = Integer.parseInt(startTimeConvert[1].trim()); //We get 00
String[] endTimeConvert = convertTime[1].split(":");
int endHourInt = Integer.parseInt(endTimeConvert[0].trim()); // we get 10
int endMinInt = Integer.parseInt(endTimeConvert[1].trim()); //We get 00
Calendar startEvent = Calendar.getInstance();
startEvent.setTimeInMillis(bookingDate.getTimeInMillis());
startEvent.set(Calendar.HOUR_OF_DAY, startHourInt); //Set event start hour
startEvent.set(Calendar.MINUTE, startMinInt); //set event start min
Calendar endEvent = Calendar.getInstance();
endEvent.setTimeInMillis(bookingDate.getTimeInMillis());
endEvent.set(Calendar.HOUR_OF_DAY, endHourInt); //Set event start hour
endEvent.set(Calendar.MINUTE, endMinInt); //set event start min
//After we have strtEvent and endEvent, convert it to format String
SimpleDateFormat calendarDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String startEventTime = calendarDateFormat.format(startEvent.getTime());
String endEventTime = calendarDateFormat.format(endEvent.getTime());
addToDeviceCalendar(startEventTime, endEventTime, "Haircut Booking",
new StringBuilder("Haircut from ")
.append(startTime)
.append(" with ")
.append(Common.currentBarber.getName())
.append(" at ")
.append(Common.currentSalon.getName()).toString(),
new StringBuilder("Address: ").append(Common.currentSalon.getAddress()).toString());
}
private void addToDeviceCalendar(String startEventTime, String endEventTime, String title, String description_, String location) {
SimpleDateFormat calendarDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
try{
Date start = calendarDateFormat.parse(startEventTime);
Date end = calendarDateFormat.parse(endEventTime);
ContentValues event = new ContentValues();
//Put
event.put(CalendarContract.Events.CALENDAR_ID, getCalendar(getContext()));
event.put(CalendarContract.Events.TITLE, title);
event.put(CalendarContract.Events.DESCRIPTION, description_);
event.put(CalendarContract.Events.EVENT_LOCATION, location);
//Time
event.put(CalendarContract.Events.DTSTART, start.getTime());
event.put(CalendarContract.Events.DTEND, end.getTime());
event.put(CalendarContract.Events.ALL_DAY, 0);
event.put(CalendarContract.Events.HAS_ALARM, 1);
String timeZone = TimeZone.getDefault().getID();
event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);
Uri calendars;
if(Build.VERSION.SDK_INT >= 8) {
calendars = Uri.parse("content://com.android.calendar/calendars");
}
else {
calendars = Uri.parse("content://calendar/events");
}
Uri uri_save = getActivity().getContentResolver().insert(calendars, event);
//Save to cache
Paper.init(getActivity());
Paper.book().write(Common.EVENT_URI_CACHE, uri_save.toString());
} catch (ParseException e){
e.printStackTrace();
}
}
private String getCalendar(Context context) {
//Get default calendar ID of calendar of Gmail
String gmailIdCalendar = "";
String projection[]={"_id", "calendar_displayName"};
// Uri calendars = Uri.parse("content://calendar/events");
Uri calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = context.getContentResolver();
//select all calendar
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if(managedCursor.moveToFirst())
{
String calName;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
do {
calName = managedCursor.getString(nameCol);
if (calName.contains("@gmail.com"))
{
gmailIdCalendar = managedCursor.getString(idCol);
break; // Exit as soon as have id
}
}while(managedCursor.moveToNext());
managedCursor.close();
}
return gmailIdCalendar;
}
private void resetStaticData() {
Common.step = 0;
Common.currentTimeSlot = -1;
Common.currentSalon = null;
Common.currentBarber = null;
Common.bookingDate.add(Calendar.DATE, 0); //Current date added
}
BroadcastReceiver confirmBookingReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
setData();
}
};
private void setData() {
txt_booking_barber_text.setText(Common.currentBarber.getName());
txt_booking_time_text.setText(new StringBuilder(Common.convertTimeSlotToString(Common.currentTimeSlot))
.append(" at ")
.append(simpleDateFormat.format(Common.bookingDate.getTime())));
txt_salon_address.setText(Common.currentSalon.getAddress());
txt_salon_website.setText(Common.currentSalon.getWebsite());
txt_salon_name.setText(Common.currentSalon.getName());
txt_salon_open_hours.setText(Common.currentSalon.getOpenHours());
}
public static BookingStep4Fragment getInstance() {
if(instance == null)
instance = new BookingStep4Fragment();
return instance;
}
@Override
public void onDestroy() {
localBroadcastManager.unregisterReceiver(confirmBookingReceiver);
super.onDestroy();
}
}
|
package com.zhku.my21days.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.zhku.my21days.dao.AdviceDAO;
import com.zhku.my21days.util.CurrentUser;
import com.zhku.my21days.vo.Advice;
import com.zhku.my21days.vo.AdviceExample;
import com.zhku.my21days.vo.Analys;
@Controller
@RequestMapping("/advices")
public class AdvicesController {
@Resource
private AdviceDAO adviceDAO;
@RequestMapping("/getAdvices")
public void getAdvices(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
AdviceExample ex=new AdviceExample();
com.zhku.my21days.vo.AdviceExample.Criteria criteria=ex.createCriteria();
List<Advice> anylist= adviceDAO.selectByExample(ex);
out.println("<?xml version='1.0' encoding='UTF-8'?>");
out.println("<adviceslist>");
for (int i = 0; i <anylist.size(); i++) {
Advice ay= (Advice)anylist.get(i);
out.println("<advices>");
out.print("<type>");
out.print(ay.getType());
out.println("</type>");
out.print("<name>");
out.print(ay.getName());
out.println("</name>");
out.print("<part1>");
out.print(ay.getPart1());
out.println("</part1>");
out.print("<part2>");
out.print(ay.getPart2());
out.println("</part2>");
out.print("<part3>");
out.print(ay.getPart3());
out.println("</part3>");
out.println("</advices>");
}
out.println("</adviceslist>");
}
}
|
//package com.example.common;
//
//import com.example.pojo.Employee;
//import lombok.AllArgsConstructor;
//import org.springframework.mail.SimpleMailMessage;
//import org.springframework.mail.javamail.JavaMailSender;
//
//
///**
// * 邮件发送线程类
// */
//@AllArgsConstructor
//public class EmailRunnable implements Runnable{
//
// private Employee employee;
// private JavaMailSender javaMailSender;
// private String fromAddress;
// private String subject;
// private String content;
//
// @Override
// public void run() {
// SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
// simpleMailMessage.setFrom(fromAddress);
// simpleMailMessage.setTo(employee.getEmail());
// simpleMailMessage.setSubject(subject);
// simpleMailMessage.setText(content);
// javaMailSender.send(simpleMailMessage);
//
//// 带附件
//// MimeMessage mimeMessage=javaMailSender.createMimeMessage();
//// MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage,true);
//// mimeMessageHelper.setFrom(from);
//// mimeMessageHelper.setTo(to);
//// mimeMessageHelper.setSubject(subject);
//// mimeMessageHelper.setText(content,true);
//// FileSystemResource fileSystemResource=new FileSystemResource(new File(filePath));
//// String fileName=fileSystemResource.getFilename();
//// mimeMessageHelper.addAttachment(fileName,fileSystemResource);
// }
//}
|
package Classes;
public class Distribuidor extends Sacola {
public String RazaoSocial;
public int Telefone;
public String produtos;
}
|
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class EvenPalindrome {
static String evenlength(String n)
{
String res = n;
for (int j = n.length() - 1; j >= 0; --j)
res += n.charAt(j);
return res;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i = 0; i < t; i++){
String ip=in.next();
int op= getResult(ip);
System.out.println(op);
}
}
private static int getResult(String ip) {
// TODO Auto-generated method stub
int maxCount=0,minValue=0;
String evenVal=evenlength(ip);
Map<Integer,Integer> opMap=new HashMap<Integer,Integer>();
for(int i=0;i<evenVal.length();i++) {
String val=""+evenVal.charAt(i);
if(opMap.get(Integer.valueOf(val))==null)
opMap.put(Integer.valueOf(val), 0);
else {
int count=opMap.get(Integer.valueOf(val));
opMap.put(Integer.valueOf(val), count+1);
}
}
for(int j=0;j<10;j++) {
if(opMap.get(j)!=null) {
int Count=opMap.get(j);
if(maxCount <Count) {
maxCount=Count;
minValue=j;
}
else if(maxCount==Count)
{
if(j<minValue) {
minValue=j;
}
}
}
}
return minValue;
}
}
|
package com.grocery.codenicely.vegworld_new.sub_category.provider;
import android.util.Log;
import com.grocery.codenicely.vegworld_new.helper.Urls;
import com.grocery.codenicely.vegworld_new.sub_category.OnSubCategoryGetRequest;
import com.grocery.codenicely.vegworld_new.sub_category.api.SubCategoryRequestApi;
import com.grocery.codenicely.vegworld_new.sub_category.model.SubCategoryData;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Meghal on 6/19/2016.
*/
public class RetrofitSubCategoryDetailsProvider implements SubCategoryDetailsProvider {
private String TAG="RetrofitSubCategory";
private Call<SubCategoryData> subCategoryDataCall;
@Override
public void requestSubCategoryDetails(String access_token, int category_id, final OnSubCategoryGetRequest onSubCategoryGetRequest) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(2,TimeUnit.MINUTES).readTimeout(2,TimeUnit.MINUTES).addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Urls.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
final SubCategoryRequestApi subCategoryRequestApi = retrofit.create(SubCategoryRequestApi.class);
subCategoryDataCall = subCategoryRequestApi.getSubCategoryData(access_token,category_id);
subCategoryDataCall.enqueue(new Callback<SubCategoryData>() {
@Override
public void onResponse(Call<SubCategoryData> call, Response<SubCategoryData> response) {
Log.i(TAG,"Response Received :"+response.body());
onSubCategoryGetRequest.onSuccess(response.body());
}
@Override
public void onFailure(Call<SubCategoryData> call, Throwable t) {
onSubCategoryGetRequest.onFailure();
t.printStackTrace();
}
});
}
@Override
public void onDestroy() {
if(subCategoryDataCall!=null){
subCategoryDataCall.cancel();
}
}
}
|
package Topic16Static;
public class Student {
public String name;
public String surName;
public int numberIndeks;
private static int numberOfStudents = 0;
public Student(String name, String surName, int numberIndeks) {
this.name = name;
this.surName = surName;
this.numberIndeks = numberIndeks;
numberOfStudents ++;
}
public String getName() {
return name;
}
public String getSurName() {
return surName;
}
public int getNumberIndeks() {
return numberIndeks;
}
public static int getNumberOfStudents() {
return numberOfStudents;
}
}
|
package com.unlimited.scala.rest.exception.handler;
import com.unlimited.scala.rest.exception.ErrorResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
/**
* This is the default exception handler.<br/>
* If there is an uncaught exception, the REST client will get an HTTP 500 (INTERNAL SERVER ERROR) status code,
* with application/json media type as default.
*
* @author Iulian Dumitru
*/
@Component
@Provider
public class DefaultExceptionHandler implements ExceptionMapper<Throwable> {
private static final Logger LOG = LoggerFactory.getLogger(DefaultExceptionHandler.class);
@Override
public Response toResponse(Throwable exception) {
LOG.error("Unknown error:", exception);
Response.Status internalServerError = Response.Status.INTERNAL_SERVER_ERROR;
ErrorResponse errorResponse = new ErrorResponse(internalServerError.getStatusCode(), "Unknown error. Please retry!");
// return application/json media type as default
return Response.status(internalServerError)
.entity(errorResponse)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
|
package com.example.demo.hello;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
/**
* 先声明队列再监听队列
* 默认 持久化的durable=true、非独占、非自动删除 的队列
*/
@RabbitListener(queuesToDeclare = @Queue(value = "hello"))
public class helloCustomer {
@RabbitHandler
public void receive(String msg){
System.out.println("msg : "+msg);
}
}
|
package com.performance.optimization.design.observer;
import java.util.Vector;
/**
* 具体的主题实现 维护了观察者队列,提供了增加和删除观察者的方法并使用inform()通知观察者
* @author qiaolin
*
*/
public class ConcreteSubject implements ISubject{
private Vector<IObserver> observers = new Vector<IObserver>();
public void attach(IObserver observer) {
observers.add(observer);
}
public void detach(IObserver observer) {
observers.remove(observer);
}
public void inform() {
for(IObserver observer:observers){
observer.update();//观察者的更新
}
}
}
|
public class AVLNode {
public AVLNode left = null;
public AVLNode right = null;
public int value = 0;
public AVLNode parent = null;
/**
* adds a new value to the left or right subtree depending on what the value is
* @return AVLNode the balanced tree with the new value added
*/
public AVLNode insert(int newValue) {
// perform binary-search style insertion
if (newValue < this.value) {
// insert the value to the left sub-tree
if (this.left == null) {
AVLNode newNode = new AVLNode();
newNode.value = newValue;
newNode.parent = this;
this.left = newNode;
} else {
this.left.insert(newValue);
}
} else {
// insert the value into the right sub-tree
if (this.right == null) {
AVLNode newNode = new AVLNode();
newNode.value = newValue;
newNode.parent = this;
this.right = newNode;
} else {
this.right.insert(newValue);
}
}
return rebalance();
}
/**
* Rebalances the tree by performing rotations after a balue has been inserted into the tree
* @return returns the new balanced tree
*/
public AVLNode rebalance() {
// make a temp node for rotation and to the new tree
AVLNode temp = null;
// balance the tree (if necessary)
// if the left node is out of balance
if(getBalance() <= (-2)){
// if the new value was inserted into the subtree of inside grandchild
// perform a double right rotation
if(this.left.right.left != null){
temp = this.left.right;
this.left.right = temp.left;
temp.left = this.left;
this.left = temp;
temp = this.left;
this.left = temp.right;
temp.right = this;
}else{ // perform a single right rotation
temp = this.left;
this.left = temp.right;
temp.right = this;
}
}else if(getBalance() >= 2){ // else if the left node is out of balance
// if the new value was inserted into the subtree of inside grandchild
// perform a double left rotation
if(this.right.right.left != null){
temp = this.right.left;
this.right.left = temp.right;
temp.right = this.right;
this.right = temp;
temp = this.right;
this.right = temp.left;
temp.left = this;
}else{// perform a single left rotation
temp = this.right;
this.right = temp.left;
temp.left = this;
}
}
// return the new balanced tree
return temp;
}
/**
* calculates the difference between the height of the right side of the tree and the left side of tree
* @return integer difference between the rightHeight and the leftHeight
*/
public int getBalance() {
int rightHeight = 0;
if (this.right != null) {
rightHeight = this.right.getHeight();
}
int leftHeight = 0;
if (this.left != null) {
leftHeight = this.left.getHeight();
}
return rightHeight - leftHeight;
}
/**
* Prints out the tree sideways
* @param depth the depth of the tree
*/
public void print(int depth) {
if (this.right != null) {
this.right.print(depth + 1);
}
for (int i = 0; i < depth; i++) {
System.out.print("\t");
}
System.out.println(this.value);
if (this.left != null) {
this.left.print(depth + 1);
}
}
/**
* calculates the height of the tree
* @return integer containing height of the tree
*/
public int getHeight() {
int leftHeight = 1;
if (left != null) {
leftHeight = left.getHeight() + 1;
}
int rightHeight = 0;
if (right != null) {
rightHeight = right.getHeight() + 1;
}
// if value of leftHeight is greater then rightHeight then return leftHeight else rightHeight
return (leftHeight > rightHeight) ? leftHeight : rightHeight;
}
}
|
package com.company;
public abstract class Conta {
private int numeroDaConta;
private int agencia;
private String banco;
protected double saldo;
protected double saque;
protected double deposito;
public Conta(int numeroDaConta, int agencia, String banco, double saldo) {
this.numeroDaConta = numeroDaConta;
this.agencia = agencia;
this.banco = banco;
this.saldo = saldo;
}
@Override
public String toString() {
return "Conta{" +
"numeroDaConta=" + numeroDaConta +
", agencia=" + agencia +
", banco='" + banco + '\'' +
", saldo=" + saldo +
'}';
}
public int getNumeroDaConta() {
return numeroDaConta;
}
public void setNumeroDaConta(int numeroDaConta) {
this.numeroDaConta = numeroDaConta;
}
public int getAgencia() {
return agencia;
}
public void setAgencia(int agencia) {
this.agencia = agencia;
}
public String getBanco() {
return banco;
}
public void setBanco(String banco) {
this.banco = banco;
}
public abstract double getSaldo();
public abstract double getSaque() throws Exception;
public abstract double getDeposito() throws Exception;
public void setDeposito(double deposito) {
this.deposito = deposito;
}
public void setSaque(double saque) {
this.saque = saque;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
}
|
package rdfsynopsis.test;
import static org.junit.Assert.assertEquals;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import rdfsynopsis.analyzer.Analyzer;
import rdfsynopsis.analyzer.TripleStreamAnalyzer;
import rdfsynopsis.dataset.InMemoryDataset;
import rdfsynopsis.statistics.PropertyUsagePerSubjectClass;
import rdfsynopsis.util.Namespace;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.sparql.vocabulary.FOAF;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.vocabulary.VCARD;
public class PropertyUsagePerSubjectClassTest {
InMemoryDataset ds;
Logger log = Logger.getLogger(PropertyUsagePerSubjectClassTest.class);
Namespace exampleNs = new Namespace("ex", "http://example.com/");
Resource maxRes;
Resource petraRes;
Resource stefanRes;
Resource thomasRes;
Resource biancaRes;
Resource marcoRes;
Resource nataliaRes;
Resource hamburgRes;
Resource berlinRes;
Resource hammRes;
Resource augsburgRes;
@Before
public void setUpBefore() throws Exception {
ds = new InMemoryDataset();
Model m = ds.getModel();
String maxMusterName = "Maximilian Mustermann";
String petraMusterName = "Petra Mustermann";
String stefanMusterName = "Thomas Mustermann";
String thomasMusterName = "Stefan Mustermann";
String biancaMusterName = "Bianca Mustermann";
String marcoMusterName = "Marco Mustermann";
String nataliaMusterName = "Natalia Mustermann";
String maxUri = "http://example.com/MaxMustermann";
String petraUri = "http://example.com/PetraMustermann";
String stefanUri = "http://example.com/StefanMustermann";
String thomasUri = "http://example.com/ThomasMustermann";
String biancaUri = "http://example.com/BiancaMustermann";
String marcoUri = "http://example.com/MarcoMustermann";
String nataliaUri = "http://example.com/NataliaMustermann";
String hamburgUri = "http://sws.geonames.org/2911298";
String berlinUri = "http://sws.geonames.org/2950159";
String hammUri = "http://sws.geonames.org/2911240";
String augsburgUri = "http://sws.geonames.org/2954172";
maxRes = m.createResource(maxUri).addLiteral(VCARD.FN, maxMusterName);
petraRes = m.createResource(petraUri).addLiteral(VCARD.FN,petraMusterName);
stefanRes = m.createResource(stefanUri).addLiteral(VCARD.FN,stefanMusterName);
thomasRes = m.createResource(thomasUri).addLiteral(VCARD.FN,thomasMusterName);
biancaRes = m.createResource(biancaUri).addLiteral(VCARD.FN,biancaMusterName);
marcoRes = m.createResource(marcoUri).addLiteral(VCARD.FN,marcoMusterName);
nataliaRes = m.createResource(nataliaUri).addLiteral(VCARD.FN,nataliaMusterName);
hamburgRes = m.createResource(hamburgUri);
berlinRes = m.createResource(berlinUri);
hammRes = m.createResource(hammUri);
augsburgRes = m.createResource(augsburgUri);
// output graph for debugging
log.debug(ds.toString());
}
@Test
public void noClasses() {
PropertyUsagePerSubjectClass pupsc = new PropertyUsagePerSubjectClass();
pupsc.processSparqlDataset(ds);
// no classes used
assertEquals(0, pupsc.getClassUris().size());
assertEquals(0, pupsc.getNumClasses());
// 7 occurrences of VCARD:FN for untyped subjects
assertEquals(1, pupsc.getUntypedNumProperties());
assertEquals(7, pupsc.getUntypedPropertyUsage(VCARD.FN));
// no further occurrences for untyped
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.knows));
assertEquals(0, pupsc.getUntypedPropertyUsage(VCARD.BDAY));
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.depiction));
assertEquals(0, pupsc.getUntypedPropertyUsage(RDF.type));
// property usage for any class and any property is zero
assertEquals(0, pupsc.getPropertyUsagePerClass(FOAF.Person, FOAF.knows));
assertEquals(0, pupsc.getPropertyUsagePerClass(FOAF.Person, VCARD.FN));
assertEquals(0, pupsc.getPropertyUsagePerClass(FOAF.Person, FOAF.birthday));
assertEquals(0, pupsc.getPropertyUsagePerClass(VCARD.TELTYPES, VCARD.EMAIL));
assertEquals(0, pupsc.getPropertyUsagePerClass(RDFS.Class, RDFS.subClassOf));
}
@Test
public void typedSubjects() {
PropertyUsagePerSubjectClass pupsc = new PropertyUsagePerSubjectClass();
// person foaf:based_near city
petraRes.addProperty(FOAF.based_near, augsburgRes);
maxRes.addProperty(FOAF.based_near, hamburgRes);
stefanRes.addProperty(FOAF.based_near, augsburgRes);
thomasRes.addProperty(FOAF.based_near, berlinRes);
biancaRes.addProperty(FOAF.based_near, hammRes);
marcoRes.addProperty(FOAF.based_near, berlinRes);
nataliaRes.addProperty(FOAF.based_near, hamburgRes);
// person foaf:knows person
petraRes.addProperty(FOAF.knows, maxRes);
maxRes.addProperty(FOAF.knows, petraRes);
maxRes.addProperty(FOAF.knows, marcoRes);
marcoRes.addProperty(FOAF.knows, maxRes);
maxRes.addProperty(FOAF.knows, thomasRes);
thomasRes.addProperty(FOAF.knows, maxRes);
marcoRes.addProperty(FOAF.knows, thomasRes);
thomasRes.addProperty(FOAF.knows, marcoRes);
marcoRes.addProperty(FOAF.knows, biancaRes);
biancaRes.addProperty(FOAF.knows, marcoRes);
thomasRes.addProperty(FOAF.knows, biancaRes);
biancaRes.addProperty(FOAF.knows, thomasRes);
thomasRes.addProperty(FOAF.knows, stefanRes);
stefanRes.addProperty(FOAF.knows, thomasRes);
thomasRes.addProperty(FOAF.knows, nataliaRes);
nataliaRes.addProperty(FOAF.knows, thomasRes);
biancaRes.addProperty(FOAF.knows, stefanRes);
stefanRes.addProperty(FOAF.knows, biancaRes);
// typing
petraRes.addProperty(RDF.type, FOAF.Person);
maxRes.addProperty(RDF.type, FOAF.Person);
stefanRes.addProperty(RDF.type, FOAF.Person);
thomasRes.addProperty(RDF.type, FOAF.Person);
biancaRes.addProperty(RDF.type, FOAF.Person);
marcoRes.addProperty(RDF.type, FOAF.Person);
nataliaRes.addProperty(RDF.type, FOAF.Person);
pupsc.processSparqlDataset(ds);
// 1 class used
assertEquals(1, pupsc.getClassUris().size());
assertEquals(1, pupsc.getNumClasses());
// no untyped subjects
assertEquals(0, pupsc.getUntypedNumProperties());
assertEquals(0, pupsc.getUntypedPropertyUsage(VCARD.FN));
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.knows));
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.based_near));
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.depiction));
assertEquals(0, pupsc.getUntypedPropertyUsage(RDF.type));
// property usage per subject class
assertEquals(18, pupsc.getPropertyUsagePerClass(FOAF.Person, FOAF.knows));
assertEquals(7, pupsc.getPropertyUsagePerClass(FOAF.Person, VCARD.FN));
assertEquals(7, pupsc.getPropertyUsagePerClass(FOAF.Person, FOAF.based_near));
// we filter out type triples
assertEquals(0, pupsc.getPropertyUsagePerClass(FOAF.Person, RDF.type));
assertEquals(0, pupsc.getPropertyUsagePerClass(VCARD.TELTYPES, VCARD.EMAIL));
assertEquals(0, pupsc.getPropertyUsagePerClass(RDFS.Class, RDFS.subClassOf));
}
@Test
public void noClassesTripleStream() {
PropertyUsagePerSubjectClass pupsc = new PropertyUsagePerSubjectClass();
Analyzer tsa = new TripleStreamAnalyzer(ds)
.addCriterion(pupsc);
tsa.performAnalysis(null);
// no classes used
assertEquals(0, pupsc.getClassUris().size());
assertEquals(0, pupsc.getNumClasses());
// 7 occurrences of VCARD:FN for untyped subjects
assertEquals(1, pupsc.getUntypedNumProperties());
assertEquals(7, pupsc.getUntypedPropertyUsage(VCARD.FN));
// no further occurrences for untyped
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.knows));
assertEquals(0, pupsc.getUntypedPropertyUsage(VCARD.BDAY));
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.depiction));
assertEquals(0, pupsc.getUntypedPropertyUsage(RDF.type));
// property usage for any class and any property is zero
assertEquals(0, pupsc.getPropertyUsagePerClass(FOAF.Person, FOAF.knows));
assertEquals(0, pupsc.getPropertyUsagePerClass(FOAF.Person, VCARD.FN));
assertEquals(0, pupsc.getPropertyUsagePerClass(FOAF.Person, FOAF.birthday));
assertEquals(0, pupsc.getPropertyUsagePerClass(VCARD.TELTYPES, VCARD.EMAIL));
assertEquals(0, pupsc.getPropertyUsagePerClass(RDFS.Class, RDFS.subClassOf));
}
@Test
public void typedSubjectsTripleStream() {
PropertyUsagePerSubjectClass pupsc = new PropertyUsagePerSubjectClass();
// person foaf:based_near city
petraRes.addProperty(FOAF.based_near, augsburgRes);
maxRes.addProperty(FOAF.based_near, hamburgRes);
stefanRes.addProperty(FOAF.based_near, augsburgRes);
thomasRes.addProperty(FOAF.based_near, berlinRes);
biancaRes.addProperty(FOAF.based_near, hammRes);
marcoRes.addProperty(FOAF.based_near, berlinRes);
nataliaRes.addProperty(FOAF.based_near, hamburgRes);
// person foaf:knows person
petraRes.addProperty(FOAF.knows, maxRes);
maxRes.addProperty(FOAF.knows, petraRes);
maxRes.addProperty(FOAF.knows, marcoRes);
marcoRes.addProperty(FOAF.knows, maxRes);
maxRes.addProperty(FOAF.knows, thomasRes);
thomasRes.addProperty(FOAF.knows, maxRes);
marcoRes.addProperty(FOAF.knows, thomasRes);
thomasRes.addProperty(FOAF.knows, marcoRes);
marcoRes.addProperty(FOAF.knows, biancaRes);
biancaRes.addProperty(FOAF.knows, marcoRes);
thomasRes.addProperty(FOAF.knows, biancaRes);
biancaRes.addProperty(FOAF.knows, thomasRes);
thomasRes.addProperty(FOAF.knows, stefanRes);
stefanRes.addProperty(FOAF.knows, thomasRes);
thomasRes.addProperty(FOAF.knows, nataliaRes);
nataliaRes.addProperty(FOAF.knows, thomasRes);
biancaRes.addProperty(FOAF.knows, stefanRes);
stefanRes.addProperty(FOAF.knows, biancaRes);
// typing
petraRes.addProperty(RDF.type, FOAF.Person);
maxRes.addProperty(RDF.type, FOAF.Person);
stefanRes.addProperty(RDF.type, FOAF.Person);
thomasRes.addProperty(RDF.type, FOAF.Person);
biancaRes.addProperty(RDF.type, FOAF.Person);
marcoRes.addProperty(RDF.type, FOAF.Person);
nataliaRes.addProperty(RDF.type, FOAF.Person);
Analyzer tsa = new TripleStreamAnalyzer(ds)
.addCriterion(pupsc);
tsa.performAnalysis(null);
// 1 class used
assertEquals(1, pupsc.getClassUris().size());
assertEquals(1, pupsc.getNumClasses());
// no untyped subjects
assertEquals(0, pupsc.getUntypedNumProperties());
assertEquals(0, pupsc.getUntypedPropertyUsage(VCARD.FN));
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.knows));
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.based_near));
assertEquals(0, pupsc.getUntypedPropertyUsage(FOAF.depiction));
assertEquals(0, pupsc.getUntypedPropertyUsage(RDF.type));
// property usage per subject class
assertEquals(18, pupsc.getPropertyUsagePerClass(FOAF.Person, FOAF.knows));
assertEquals(7, pupsc.getPropertyUsagePerClass(FOAF.Person, VCARD.FN));
assertEquals(7, pupsc.getPropertyUsagePerClass(FOAF.Person, FOAF.based_near));
// we filter out type triples
assertEquals(0, pupsc.getPropertyUsagePerClass(FOAF.Person, RDF.type));
assertEquals(0, pupsc.getPropertyUsagePerClass(VCARD.TELTYPES, VCARD.EMAIL));
assertEquals(0, pupsc.getPropertyUsagePerClass(RDFS.Class, RDFS.subClassOf));
}
}
|
package db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import Models.*;
public class LegalPersonDB implements LegalPersonDBIF {
private LegalPersonDB legalPersonDB;
private static final String FIND_ALL_Q =
"SELECT Legal_Person.id, personType, fname, lname, title, salary, phoneNumber, email, (StreetName + ' ' + StreetNo +' '+ PostCode +' '+ city + ' '+ country) AS address, companyName, CVRno, SSN, supplyType, CustomerId FROM (Legal_Person LEFT OUTER JOIN Person ON Legal_Person.Id = Person.Id LEFT OUTER JOIN Organization ON Legal_Person.Id = Organization.Id LEFT OUTER JOIN Address ON Address.AddressId = Legal_Person.Id LEFT OUTER JOIN POSTCODE ON POSTCODE.PostalCode = ADDRESS.PostCode LEFT OUTER JOIN EMPLOYEE_ROLE ON EMPLOYEE_ROLE.PersonId = LEGAL_PERSON.Id LEFT OUTER JOIN CUSTOMER_ROLE ON CUSTOMER_ROLE.LegalPersonId = LEGAL_PERSON.Id LEFT OUTER JOIN SUPPLIER_ROLE ON SUPPLIER_ROLE.LegalPersonId = LEGAL_PERSON.Id)";
private static final String FIND_BY_ID_Q = FIND_ALL_Q + " WHERE Legal_Person.id = ?";
private static final String FIND_BY_NAME_Q = FIND_ALL_Q + " WHERE fname = ?";
private PreparedStatement findAllPerson;
private PreparedStatement findById;
private PreparedStatement findByName;
//insert part
private static final String INSERT_Q = "insert into Legal_Person (phoneNumber, email, personType, addressId) values (?, ?, ?, ?)";
private PreparedStatement insertPS;
private static final String INSERT_PERSON_Q = "INSERT INTO PERSON (id, fname, lname) VALUES (?,?,?)";
private PreparedStatement insertP;
public LegalPersonDB() throws DataAccessException {
init();
}
private void init() throws DataAccessException {
Connection connection = DBConnection.getInstance().getConnection();
try {
findAllPerson = connection.prepareStatement(FIND_ALL_Q);
findById = connection.prepareStatement(FIND_BY_ID_Q);
findByName = connection.prepareStatement(FIND_BY_NAME_Q);
} catch (SQLException e) {
// e.printStackTrace();
throw new DataAccessException(DBMessages.COULD_NOT_PREPARE_STATEMENT, e);
}
}
@Override
public List<LegalPerson> findAll() throws DataAccessException {
ResultSet rs;
try {
rs = this.findAllPerson.executeQuery();
} catch (SQLException e) {
// e.printStackTrace();
throw new DataAccessException(DBMessages.COULD_NOT_READ_RESULTSET, e);
}
List<LegalPerson> res = buildObjects(rs);
return res;
}
@Override
public LegalPerson findById(String id) throws DataAccessException {
LegalPerson res = null;
try {
findById.setString(1, id);
ResultSet rs = findById.executeQuery();
if (rs.next()) {
res = buildObject(rs);
}
} catch (SQLException e) {
// e.printStackTrace();
throw new DataAccessException(DBMessages.COULD_NOT_BIND_OR_EXECUTE_QUERY, e);
}
return res;
}
@Override
public List<LegalPerson> findByName(String name) throws DataAccessException {
List<LegalPerson> res = null;
try {
findByName.setString(1, "%" + name + "%");
if (name != null && name.length() == 1) {
findByName.setString(2, name);
} else {
findByName.setString(2, "");
}
findByName.setString(3, "%" + name + "%");
ResultSet rs = findByName.executeQuery();
res = buildObjects(rs);
} catch (SQLException e) {
// e.printStackTrace();
throw new DataAccessException(DBMessages.COULD_NOT_BIND_OR_EXECUTE_QUERY, e);
}
return res;
}
private List<LegalPerson> buildObjects(ResultSet rs) throws DataAccessException {
List<LegalPerson> res = new ArrayList<>();
try {
while (rs.next()) {
LegalPerson currLegalPerson = buildObject(rs);
res.add(currLegalPerson);
}
} catch (SQLException e) {
// e.printStackTrace();
throw new DataAccessException(DBMessages.COULD_NOT_READ_RESULTSET, e);
}
return res;
}
private LegalPerson buildObject(ResultSet rs) throws DataAccessException {
try {
if(rs.getString("personType").equals("Person")) {
LegalPerson res = buildPerson(rs);
return res;
}
if (rs.getString("personType").equals("Organization")){
LegalPerson res = buildOrganization(rs);
return res;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private Person buildPerson(ResultSet rs) throws DataAccessException {
Person res = new Person(null, null, null, null ,null, null, null, null);
try {
//String phoneNumber, String email, String address, String fName, String lName,
//EmployeeRole employeeRole, CustomerRole customerRole, SupplierRole supplierRole
res.setPhoneNumber(rs.getString("phoneNumber"));
res.setEmail(rs.getString("email"));
res.setAddress(rs.getString("address"));
//person
res.setId(rs.getInt("id"));
res.setfName(rs.getString("fname"));
res.setlName(rs.getString("lname"));
//String SSN, String title, double salary
EmployeeRole e = new EmployeeRole(rs.getString("ssn"), rs.getString("title"), rs.getDouble("salary"));
res.setEmployeeRole(e);
//customerID
CustomerRole c = new CustomerRole(rs.getString("customerId"));
res.setCustomerRole(c);
//String supplyType
SupplierRole s = new SupplierRole(rs.getString("supplyType"));
res.setSupplierRole(s);
} catch (SQLException e) {
// e.printStackTrace();
throw new DataAccessException(DBMessages.COULD_NOT_READ_RESULTSET, e);
}
return res;
}
private Organization buildOrganization(ResultSet rs) throws DataAccessException {
//String organizationID, String organizationName, String CVR,
//CustomerRole customerRole, SupplierRole supplierRole
Organization res = new Organization(null, null, null, 0, null, null, null, null);
try {
res.setPhoneNumber(rs.getString("phoneNumber"));
res.setEmail(rs.getString("email"));
res.setAddress(rs.getString("address"));
//organization
res.setOrganizationID(rs.getInt("id"));
res.setOrgnizationName(rs.getString("CompanyName"));
res.setCVR(rs.getString("CVRno"));
//customerID
CustomerRole c = new CustomerRole(rs.getString("customerId"));
res.setCustomerRole(c);
//String supplyType
SupplierRole s = new SupplierRole(rs.getString("supplyType"));
} catch (SQLException e) {
// e.printStackTrace();
throw new DataAccessException(DBMessages.COULD_NOT_READ_RESULTSET, e);
}
return res;
}
@Override
public LegalPerson insert(LegalPerson person) throws DataAccessException {
// TODO Auto-generated method stub
return null;
}
}
|
package main;
import exception.LackSufficientBalanceException;
import org.apache.log4j.Logger;
import service.SalaryPaymentServer;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CountDownLatch;
public class Main {
public static final Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) throws Exception {
int fileRowCount = 1000;
BigDecimal deptorDepositAmount = new BigDecimal(1000000000);
try {
Path salaryPaymentFolderPath = Paths.get("..\\..\\SalaryPayment");
Files.createDirectories(salaryPaymentFolderPath);
SalaryPaymentServer salaryPaymentServer = new SalaryPaymentServer();
salaryPaymentServer.createFile(deptorDepositAmount, fileRowCount);
CountDownLatch latch = salaryPaymentServer.salaryPaymentThreadsExecuter(deptorDepositAmount);
System.out.println("************* PROCESSING *************");
latch.await();
System.out.println("********** FINISHED PROCESS **********");
} catch (Exception e) {
logger.error(e.getMessage(), e);
System.err.print(e.getMessage());
throw new Exception();
}
}
}
|
package com.mars.test;
import java.util.HashMap;
import java.util.Map;
import com.mars.model.Position;
import com.mars.model.Sonda;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.junit.Before;
import org.junit.Test;
public class PositionTest {
public static Map<Position, Sonda> surfaceMap;
@Before
public void init(){
surfaceMap = new HashMap<Position, Sonda>();
}
/**
* Tests the equality between two Positions
* the result should validate that the two Positions are equal
*/
@Test
public void compareTwoEqual(){
Position pos1 = new Position(3,3);
Position pos2 = new Position(3,3);
assertEquals(pos1, pos2);
}
/**
* Tests the inequality between two Positions
* the result should validate that the two Positions are different
*/
@Test
public void compareTwoDifferent(){
Position pos1 = new Position(3,3);
Position pos2 = new Position(3,4);
assertFalse(pos1.equals(pos2));
}
/**
* Tests the result when Sondas are inserted at the same position of the sondasMap
* the result should be the sondasMap size equals to 1
*/
@Test
public void testSurfaceMapSize(){
Position pos1 = new Position(3,3);
Sonda sonda1 = new Sonda(pos1, "W", 1);
surfaceMap.put(pos1, sonda1);
Position pos2 = new Position(3,3);
Sonda sonda2 = new Sonda(pos2, "N", 2);
surfaceMap.put(pos2, sonda2);
Position pos3 = new Position(3,3);
Sonda sonda3 = new Sonda(pos2, "E", 3);
surfaceMap.put(pos3, sonda3);
assertEquals(surfaceMap.size(), 1);
}
/**
* Tests what value is retained when multiple Sondas are added
* to the position of the sondasMap
* the result should be the last heading value being equal to the one
* of the last Sonda added
*/
@Test
public void testSurfaceMapLastItem(){
Position pos1 = new Position(3,3);
Sonda sonda1 = new Sonda(pos1, "W", 1);
surfaceMap.put(pos1, sonda1);
Position pos2 = new Position(3,3);
Sonda sonda2 = new Sonda(pos2, "N", 2);
surfaceMap.put(pos2, sonda2);
Position pos3 = new Position(3,3);
Sonda sonda3 = new Sonda(pos2, "E", 3);
surfaceMap.put(pos3, sonda3);
assertEquals(surfaceMap.get(new Position(3,3)).getHeading(), "E");
}
}
|
package com.tu.rocketmq.transactionConfig;
import com.tu.mysql.model.User;
import com.tu.mysql.service.UserService;
import com.tu.rocketmq.action.RocketTransAction;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
/**
* @Auther: tuyongjian
* @Date: 2020/4/20 17:03
* @Description:生产者的事务监听器
*/
@Service
public class MQTransProducerListener implements TransactionListener {
private static final Logger logger = LoggerFactory.getLogger(MQTransProducerListener.class);
@Autowired
private UserService userService;
//执行本地事务
@Override
public LocalTransactionState executeLocalTransaction(Message message, Object o) {
logger.info("开始执行本地事务。。。");
String body = new String(message.getBody());
String key = message.getKeys();
String transactionId = message.getTransactionId();
logger.info("transactionId="+transactionId+", key="+key+", body="+body);
int status = Integer.parseInt(o.toString());
logger.info("state-------------:"+status);
try {
User user = new User();
String msgBody = null;
msgBody = new String(message.getBody(), RemotingHelper.DEFAULT_CHARSET);
user.setUserName(msgBody);
user.setPassword("123");
userService.add(user);
return LocalTransactionState.COMMIT_MESSAGE;
} catch (Exception e) {
logger.info("出现异常"+e.getMessage());
return LocalTransactionState.ROLLBACK_MESSAGE;
}
}
//检查本地事务
/**
* 当本地事务处理返回UNKNOW的时候
* 回执行次方法进行会查,这个时候再进行
* 提交消息或者回滚消息
* @param messageExt
* @return
*/
@Override
public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
logger.info("开始检查本地事务。。。");
return LocalTransactionState.UNKNOW;
}
}
|
package com.social.server.service;
public interface MessageService {
String getMessage(String code, Object... args);
}
|
package net.sf.taverna.t2.component.ui.view;
import static net.sf.taverna.t2.workflowmodel.utils.Tools.getFirstProcessorWithActivityInputPort;
import static net.sf.taverna.t2.workflowmodel.utils.Tools.getFirstProcessorWithActivityOutputPort;
import java.util.Arrays;
import java.util.List;
import net.sf.taverna.t2.component.ComponentActivity;
import net.sf.taverna.t2.workbench.file.FileManager;
import net.sf.taverna.t2.workbench.ui.views.contextualviews.ContextualView;
import net.sf.taverna.t2.workbench.ui.views.contextualviews.activity.ContextualViewFactory;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workflowmodel.Processor;
import net.sf.taverna.t2.workflowmodel.processor.activity.Activity;
import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityInputPort;
import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityOutputPort;
public class ComponentActivitySemanticAnnotationContextViewFactory implements
ContextualViewFactory<Object> {
private static FileManager fm = FileManager.getInstance();
@Override
public boolean canHandle(Object selection) {
return getContainingComponentActivity(selection) != null;
}
public static ComponentActivity getContainingComponentActivity(
Object selection) {
if (selection instanceof ComponentActivity)
return (ComponentActivity) selection;
if (selection instanceof ActivityInputPort) {
Processor p = null;
Dataflow d = fm.getCurrentDataflow();
p = getFirstProcessorWithActivityInputPort(d,
(ActivityInputPort) selection);
Activity<?> a = p.getActivityList().get(0);
return getContainingComponentActivity(a);
}
if (selection instanceof ActivityOutputPort) {
Processor p = null;
Dataflow d = fm.getCurrentDataflow();
p = getFirstProcessorWithActivityOutputPort(d,
(ActivityOutputPort) selection);
Activity<?> a = p.getActivityList().get(0);
return getContainingComponentActivity(a);
}
return null;
}
@Override
public List<ContextualView> getViews(Object selection) {
return Arrays
.<ContextualView> asList(new ComponentActivitySemanticAnnotationContextualView(
selection));
}
}
|
package com.peregudova.multinote.requests;
public class SaveNoteCommand extends GetNoteCommand{
private String text;
public SaveNoteCommand(String token, String user, String id_note, String text) {
super(token, user, id_note);
this.text = text;
this.setCommand("save");
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge;
import com.google.common.collect.Lists;
import org.giddap.dreamfactory.leetcode.onlinejudge.implementations.GrayCodeMathImpl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class GrayCodeTest {
private GrayCode solution = new GrayCodeMathImpl();
@Test
public void small01() {
assertEquals(Lists.newArrayList(0), solution.grayCode(0));
}
@Test
public void small02() {
assertEquals(Lists.newArrayList(0, 1), solution.grayCode(1));
}
@Test
public void small03() {
assertEquals(Lists.newArrayList(0, 1, 3, 2), solution.grayCode(2));
}
}
|
/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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.
*/
import dalvik.system.InMemoryDexClassLoader;
import java.lang.reflect.Method;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws Exception {
System.loadLibrary(args[0]);
// Feature only enabled for target SDK version Q and later.
setTargetSdkVersion(/* Q */ 29);
if (isDebuggable()) {
// Background verification is disabled in debuggable mode. This test makes
// no sense then.
return;
}
if (!hasOatFile()) {
// We only generate vdex files if the oat directories are created.
return;
}
setProcessDataDir(DEX_LOCATION);
final int maxCacheSize = getVdexCacheSize();
final int numDexFiles = DEX_BYTES_CHECKSUMS.length;
if (numDexFiles <= maxCacheSize) {
throw new IllegalStateException("Not enough dex files to test cache eviction");
}
// Simply load each dex file one by one.
check(0, getCurrentCacheSize(), "There should be no vdex files in the beginning");
for (int i = 0; i < numDexFiles; ++i) {
ClassLoader loader = loadDex(i);
waitForVerifier();
check(true, hasVdexFile(loader), "Loading dex file should have produced a vdex");
check(Math.min(i + 1, maxCacheSize), getCurrentCacheSize(),
"Unexpected number of cache entries");
}
// More complicated pattern where some dex files get reused.
for (int s = 1; s < numDexFiles; ++s) {
for (int i = 0; i < maxCacheSize; ++i) {
ClassLoader loader = loadDex(i);
waitForVerifier();
check(true, hasVdexFile(loader), "Loading dex file should have produced a vdex");
check(maxCacheSize, getCurrentCacheSize(), "Unexpected number of cache entries");
}
}
}
private static native boolean isDebuggable();
private static native boolean hasOatFile();
private static native int setTargetSdkVersion(int version);
private static native void setProcessDataDir(String path);
private static native void waitForVerifier();
private static native boolean hasVdexFile(ClassLoader loader);
private static native int getVdexCacheSize();
private static native boolean isAnonymousVdexBasename(String basename);
private static <T> void check(T expected, T actual, String message) {
if (!expected.equals(actual)) {
System.err.println("ERROR: " + message + " (expected=" + expected.toString() +
", actual=" + actual.toString() + ")");
}
}
private static int getCurrentCacheSize() {
int count = 0;
File folder = new File(DEX_LOCATION, "oat");
File[] subfolders = folder.listFiles();
if (subfolders.length != 1) {
throw new IllegalStateException("Expect only one subfolder - isa");
}
folder = subfolders[0];
for (File f : folder.listFiles()) {
if (f.isFile() && isAnonymousVdexBasename(f.getName())) {
count++;
}
}
return count;
}
private static byte[] createDex(int index) {
if (index >= 100) {
throw new IllegalArgumentException("Not more than two decimals");
}
// Clone the base dex file. This is the dex file for index 0 (class ID "01").
byte[] dex = DEX_BYTES_BASE.clone();
// Overwrite the checksum and sha1 signature.
System.arraycopy(DEX_BYTES_CHECKSUMS[index], 0, dex, DEX_BYTES_CHECKSUM_OFFSET,
DEX_BYTES_CHECKSUM_SIZE);
// Check that the class ID offsets match expectations - they should contains "01".
if (dex[DEX_BYTES_CLASS_ID_OFFSET1 + 0] != 0x30 ||
dex[DEX_BYTES_CLASS_ID_OFFSET1 + 1] != 0x31 ||
dex[DEX_BYTES_CLASS_ID_OFFSET2 + 0] != 0x30 ||
dex[DEX_BYTES_CLASS_ID_OFFSET2 + 1] != 0x31) {
throw new IllegalStateException("Wrong class name values");
}
// Overwrite class ID.
byte str_id1 = (byte) (0x30 + ((index + 1) / 10));
byte str_id2 = (byte) (0x30 + ((index + 1) % 10));
dex[DEX_BYTES_CLASS_ID_OFFSET1 + 0] = str_id1;
dex[DEX_BYTES_CLASS_ID_OFFSET1 + 1] = str_id2;
dex[DEX_BYTES_CLASS_ID_OFFSET2 + 0] = str_id1;
dex[DEX_BYTES_CLASS_ID_OFFSET2 + 1] = str_id2;
return dex;
}
private static ClassLoader loadDex(int index) {
return new InMemoryDexClassLoader(ByteBuffer.wrap(createDex(index)), /*parent*/ null);
}
private static final String DEX_LOCATION = System.getenv("DEX_LOCATION");
private static final int DEX_BYTES_CLASS_ID_OFFSET1 = 0xfd;
private static final int DEX_BYTES_CLASS_ID_OFFSET2 = 0x11d;
private static final int DEX_BYTES_CHECKSUM_OFFSET = 8;
private static final int DEX_BYTES_CHECKSUM_SIZE = 24;
// Dex file for: "public class MyClass01 {}".
private static final byte[] DEX_BYTES_BASE = Base64.getDecoder().decode(
"ZGV4CjAzNQBHVjDjQ9WQ2TSezZ0exFH00hvlJrenqvNEAgAAcAAAAHhWNBIAAAAAAAAAALABAAAG" +
"AAAAcAAAAAMAAACIAAAAAQAAAJQAAAAAAAAAAAAAAAIAAACgAAAAAQAAALAAAAB0AQAA0AAAAOwA" +
"AAD0AAAAAQEAABUBAAAlAQAAKAEAAAEAAAACAAAABAAAAAQAAAACAAAAAAAAAAAAAAAAAAAAAQAA" +
"AAAAAAAAAAAAAQAAAAEAAAAAAAAAAwAAAAAAAACfAQAAAAAAAAEAAQABAAAA6AAAAAQAAABwEAEA" +
"AAAOAAEADgAGPGluaXQ+AAtMTXlDbGFzczAxOwASTGphdmEvbGFuZy9PYmplY3Q7AA5NeUNsYXNz" +
"MDEuamF2YQABVgB1fn5EOHsiY29tcGlsYXRpb24tbW9kZSI6ImRlYnVnIiwibWluLWFwaSI6MSwi" +
"c2hhLTEiOiI4ZjI5NTlkMDExNmMyYjdmZTZlMDUxNWQ3MTQxZTRmMGY0ZTczYzBiIiwidmVyc2lv" +
"biI6IjEuNS41LWRldiJ9AAAAAQAAgYAE0AEAAAAAAAAADAAAAAAAAAABAAAAAAAAAAEAAAAGAAAA" +
"cAAAAAIAAAADAAAAiAAAAAMAAAABAAAAlAAAAAUAAAACAAAAoAAAAAYAAAABAAAAsAAAAAEgAAAB" +
"AAAA0AAAAAMgAAABAAAA6AAAAAIgAAAGAAAA7AAAAAAgAAABAAAAnwEAAAMQAAABAAAArAEAAAAQ" +
"AAABAAAAsAEAAA==");
// Checksum/SHA1 signature diff for classes MyClass01 - MyClassXX.
// This is just a convenient way of storing many similar dex files.
private static final byte[][] DEX_BYTES_CHECKSUMS = new byte[][] {
Base64.getDecoder().decode("R1Yw40PVkNk0ns2dHsRR9NIb5Sa3p6rz"),
Base64.getDecoder().decode("i1V1U3C8nexVk4uw185lXZd9kzd82iaA"),
Base64.getDecoder().decode("tFPbVPdpzuoDWqH71Ak5HpltBHg0frMU"),
Base64.getDecoder().decode("eFSc7dENiK8nxviKBmd/O2s7h/NAj+l/"),
Base64.getDecoder().decode("DlUfNQ3cuVrCHRyw/cOFhqEe+0r6wlUP"),
Base64.getDecoder().decode("KVaBmdG8Y8kx8ltEPXWyi9OCdL14yeiW"),
Base64.getDecoder().decode("K1bioDTHtPwmrPXkvZ0XYCiripH6KsC2"),
Base64.getDecoder().decode("oVHctdpHG3YTNeQlVCshTkFKVra9TG4k"),
Base64.getDecoder().decode("eVWMFHRY+w4lpn9Uo9jn+eNAmaRK4HEw"),
Base64.getDecoder().decode("/lW3Q3U4ot5A2qkhiv4Aj+s8zv7984MA"),
Base64.getDecoder().decode("BFRB+4HwRbuD164DB3sVy28dc+Ea5YVQ"),
Base64.getDecoder().decode("klQBLEXyr0cviHDHlqFyWPGKaQQnqMiD"),
Base64.getDecoder().decode("jlTcJAkpnbDI/E4msuvMyWqKxNMTN0YU"),
Base64.getDecoder().decode("vlUOrp4aN0PxcaqQrQmm597P+Ymu5Adt"),
Base64.getDecoder().decode("HlXyT1GoJk1m33O8OMaYxqy3K1Byyf1S"),
Base64.getDecoder().decode("d1O5toIKjTXNZkgP3p9RiiafhuKw4gUH"),
Base64.getDecoder().decode("11RsuG9UrFHPipOj9zjuGU9obctMJbq6"),
Base64.getDecoder().decode("dlSW5egObqheoHSRthlR2c2jVKLGQ3QL"),
Base64.getDecoder().decode("ulMgQEhC0XMhmKxHtgdURY6B6JEqNb3E"),
Base64.getDecoder().decode("YFV08vrcs49xYr1OBhrza5H8Ha86FODz"),
Base64.getDecoder().decode("jFKPxTFd3kn6K0p6n8YEPgm0hiozXW1p"),
Base64.getDecoder().decode("LlUZdlCXwAn4qksYL6Urw+bZC/fYuJ1T"),
Base64.getDecoder().decode("K1SuRt9xZX5lAVtbpMauOWLVXs2KooUA"),
Base64.getDecoder().decode("2FJAWIk0JS9EdvkgHjquLL9qdcLeHaRJ"),
Base64.getDecoder().decode("YVResABr9IvZLV8eeIhM3TXfGC+Y6/x1"),
Base64.getDecoder().decode("UVTrkVGIh8u7FBHgcbS9flI0CY5g2E3m"),
Base64.getDecoder().decode("oVIu6RsrT6HgnbPzNGiYZSpKS0cqNi+a"),
Base64.getDecoder().decode("2FR/slWq9YC6kJRDEw21RVGmJhr3/uKZ"),
Base64.getDecoder().decode("CFbaSi70ZVaumL7zsXWlD/ernHxCZPx6"),
Base64.getDecoder().decode("7FTY+T1/qevWQM6Yoe+OwNcUdgcCUomJ"),
};
}
|
package easyinvest.com.myapplication;
public class State {
private static Portfolio portfolio;
private static Stock stock;
private static Index index;
public static Portfolio getPortfolio() {
return portfolio;
}
public static void setStock(Stock stock) {
State.stock = stock;
}
public static Stock getStock() {
return stock;
}
public static void setIndex(Index index) {
State.index = index;
}
public static Index getIndex() {return index;}
public static void reset() {
stock = null;
portfolio = new Portfolio();
}
}
|
package colis.com.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import colis.com.dao.TrajetDao;
import colis.com.entities.personnes.Personnes;
import colis.com.entities.trajets.Trajet;
@RestController
@CrossOrigin("*") // pour gere les erreu d'ente ex: Orig
public class TrajetRestServices {
@Autowired // injection des depenses
private TrajetDao trajetDao;
@RequestMapping(value="/trajet", method=RequestMethod.POST)// elle nous permet d'avoir le resultat de cette requet par http
public Trajet saveTrajet(@RequestBody Trajet t){
return trajetDao.save(t);
}
@RequestMapping(value="/trajet/list", method=RequestMethod.GET)// elle nous permet d'avoir le resultat de cette requet par http
public Trajet listTrajet(@RequestParam(name="idTrajet", defaultValue="")String idTrajet){
return trajetDao.findOne(Long.parseLong(idTrajet));
}
@RequestMapping(value="/trajet/all", method=RequestMethod.GET)// elle nous permet d'avoir le resultat de cette requet par http
public List<Trajet> getPersonnes(){
return trajetDao.findAll();
}
}
|
package eecs.ai.p1.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import eecs.ai.p1.Board;
import eecs.ai.p1.BoardState;
import eecs.ai.p1.Directions;
public class RandomizeState extends Command {
private final int numberMoves;
private RandomizeState(int numberMoves) {
initLegalMoves();
this.numberMoves = numberMoves;
}
/**
* Builds a new instance of the randomize state command
* @param numberMoves The number of random moves you want to make
* @return The new instance of the command to randomize the state
*/
public static final RandomizeState of(int numberMoves) {
return new RandomizeState(numberMoves);
}
/**
* Executes the randomization of the board based on the number of moves, and a passed in board.
*/
@Override
public final void execute(Board gameBoard) {
//Removes previous visited states, treat as a new starting point
gameBoard.getVisited().clear();
Random numberGenerator;
if (gameBoard.toPrint()){
System.out.println("RandomizeState: " + numberMoves);
//Generate based off a seed (print evaluation)
numberGenerator = new Random(391);
}
else {
//Else, generate a completely random random (statistical analysis).
numberGenerator = new Random();
}
for (int i = 0; i < numberMoves; i++) {
BoardState boardState = gameBoard.getState();
ArrayList<Directions> legalMoves = getLegalMoves(boardState.getPosition());
gameBoard.addVisited(boardState.hashCode());
List<Directions> possibleMoves = legalMoves.stream()
.filter(move -> !gameBoard.checkVisited(boardState.peekNext(move)))
.collect(Collectors.toList());
//If no more unrepeated states, make a random move to satisfy n moves
if (possibleMoves.isEmpty()) {
Move.of(legalMoves.get(numberGenerator.nextInt(legalMoves.size()))).execute(gameBoard);
}
else{
Move.of(possibleMoves.get(numberGenerator.nextInt(possibleMoves.size()))).execute(gameBoard);
}
}
}
}
|
package co.bucketstargram.command.library;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import co.bucketstargram.common.Command;
import co.bucketstargram.common.HttpRes;
public class LibraryAdd implements Command {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("\n--- LibraryAddForm.java ---");
String imagePath = request.getParameter("imagePath");
String bucketTitle = request.getParameter("bucketTitle");
String bucketContent = request.getParameter("bucketContent");
String bucketMemberId = request.getParameter("bucketMemberId");
System.out.println("imagePath = " + imagePath);
System.out.println("bucketTitle = " + bucketTitle);
System.out.println("bucketContent = " + bucketContent);
System.out.println("bucketMemberId = " + bucketMemberId);
request.setAttribute("imagePath", imagePath);
request.setAttribute("bucketTitle", bucketTitle);
request.setAttribute("bucketContent", bucketContent);
request.setAttribute("bucketMemberId", bucketMemberId);
String viewPage = "jsp/library/libraryForm.jsp";
//HttpRes.forward(request, response, viewPage);
response.getWriter().append("<script>")
.append("opener.location='"+viewPage+"';")
.append("</script>");
}
}
|
package gov.nih.mipav.view.renderer.WildMagic.Poisson.Octree;
public class RestrictedLaplacianMatrixFunction extends TerminatingNodeAdjacencyFunction{
public int depth;
public int[] offset = new int[3];
public Octree ot;
public float radius;
public int[] index = new int[Octree.DIMENSION];
public int[] scratch = new int[Octree.DIMENSION];
public int elementCount;
public MatrixEntry[] rowElements;
public int Function(final OctNode node1, final OctNode node2){
int[] d1 = new int[1];
int[] d2 = new int[1];
int[] off1 = new int[3];
int[] off2 = new int[3];
node1.depthAndOffset(d1,off1);
node2.depthAndOffset(d2,off2);
int dDepth=d2[0]-d1[0];
int d;
d=(off2[0]>>dDepth)-off1[0];
if(d<0){return 0;}
if( dDepth == 0){
if( d == 0){
d=off2[1]-off1[1];
if(d<0){return 0;}
else if( d == 0){
d=off2[2]-off1[2];
if(d<0){return 0;}
}
}
// Since we are getting the restricted matrix, we don't want to propogate out to terms that don't contribute...
if(!OctNode.Overlap2(depth,offset,0.5f,d1[0],off1,radius)){return 0;}
scratch[0]=FunctionData.SymmetricIndex(index[0],BinaryNode.Index(d1[0],off1[0]));
scratch[1]=FunctionData.SymmetricIndex(index[1],BinaryNode.Index(d1[0],off1[1]));
scratch[2]=FunctionData.SymmetricIndex(index[2],BinaryNode.Index(d1[0],off1[2]));
float temp=ot.GetLaplacian(scratch);
if(node1==node2){temp/=2;}
if((float)Math.abs(temp)> Octree.EPSILON){
rowElements[elementCount].Value=temp;
rowElements[elementCount].N=node1.nodeData.nodeIndex;
elementCount++;
}
return 0;
}
return 1;
}
}
|
package Academy;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import pageObjects.LandingPage;
import pageObjects.LoginPage;
import resources.Base;
public class Homepage extends Base {
public WebDriver driver;
public static Logger log=LogManager.getLogger(Base.class.getName());
@BeforeTest
public void initialize() throws IOException
{
driver=initializeDriver();
}
@Test(dataProvider = "getData")
public void basePageNavigation(String Username, String Password,String text) throws IOException
{
//driver=initializeDriver();
// driver.get("http://qaclickacademy.com");
//driver.manage().window().maximize();
driver.get("http://qaclickacademy.com");
driver.manage().window().maximize();
//creating the object of the class to invoke that getlogin (landing page) method
LandingPage l=new LandingPage(driver);
l.getLogin().click();
//creating the object of the class to invoke that getemail,getpwd (login page) method
LoginPage lp=new LoginPage(driver);
lp.getemail().sendKeys(Username);
lp.getpassword().sendKeys(Password);
//System.out.println(text);
log.info(text);
lp.loginbtn().click();
}
@DataProvider
public Object[][] getData()
{
//Row stands for howmany diff data types test should run
//column stands for how many values for each test
//here we gave [2] [2] in the array size because of we have two types of data and two types of values(username,password)
//array size is [2] [2] but data index always start every thing from 0
//so here is two set of data with size of 2 array
Object [][] data=new Object[2][3];
//0th row
data[0][0]="nonrestricteduser@qw.com";
data[0][1]="123456";
data[0][2]="nonrestricted user";
//1th row
data[1][0]="restricteduser@qw.com";
data[1][1]="123456";
data[1][2]="restricted user";
return data;
}
@AfterTest
public void tearDowm()
{
driver.close();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.davivienda.sara.dto;
import java.util.Objects;
/**
*
* @author jediazs
*/
public class ConfAccesoAplicacionDTO {
private boolean consultar;
private boolean actualizar;
private boolean ejecutar;
private boolean administrar;
private boolean crear;
private boolean borrar;
private String servicioAplicacion;
private long codigoServicioAplicacion;
private String usuarioAplicacion;
private Long version;
/**
* @return the consultar
*/
public boolean isConsultar() {
return consultar;
}
/**
* @param consultar the consultar to set
*/
public void setConsultar(boolean consultar) {
this.consultar = consultar;
}
/**
* @return the actualizar
*/
public boolean isActualizar() {
return actualizar;
}
/**
* @param actualizar the actualizar to set
*/
public void setActualizar(boolean actualizar) {
this.actualizar = actualizar;
}
/**
* @return the ejecutar
*/
public boolean isEjecutar() {
return ejecutar;
}
/**
* @param ejecutar the ejecutar to set
*/
public void setEjecutar(boolean ejecutar) {
this.ejecutar = ejecutar;
}
/**
* @return the administrar
*/
public boolean isAdministrar() {
return administrar;
}
/**
* @param administrar the administrar to set
*/
public void setAdministrar(boolean administrar) {
this.administrar = administrar;
}
/**
* @return the crear
*/
public boolean isCrear() {
return crear;
}
/**
* @param crear the crear to set
*/
public void setCrear(boolean crear) {
this.crear = crear;
}
/**
* @return the borrar
*/
public boolean isBorrar() {
return borrar;
}
/**
* @param borrar the borrar to set
*/
public void setBorrar(boolean borrar) {
this.borrar = borrar;
}
/**
* @return the servicioAplicacion
*/
public String getServicioAplicacion() {
return servicioAplicacion;
}
/**
* @param servicioAplicacion the servicioAplicacion to set
*/
public void setServicioAplicacion(String servicioAplicacion) {
this.servicioAplicacion = servicioAplicacion;
}
/**
* @return the usuarioAplicacion
*/
public String getUsuarioAplicacion() {
return usuarioAplicacion;
}
/**
* @param usuarioAplicacion the usuarioAplicacion to set
*/
public void setUsuarioAplicacion(String usuarioAplicacion) {
this.usuarioAplicacion = usuarioAplicacion;
}
/**
* @return the version
*/
public Long getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(Long version) {
this.version = version;
}
/**
* @return the codigoServicioAplicacion
*/
public long getCodigoServicioAplicacion() {
return codigoServicioAplicacion;
}
/**
* @param codigoServicioAplicacion the codigoServicioAplicacion to set
*/
public void setCodigoServicioAplicacion(long codigoServicioAplicacion) {
this.codigoServicioAplicacion = codigoServicioAplicacion;
}
@Override
public int hashCode() {
int hash = 7;
hash = 73 * hash + Objects.hashCode(this.servicioAplicacion);
hash = 73 * hash + (int) (this.codigoServicioAplicacion ^ (this.codigoServicioAplicacion >>> 32));
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ConfAccesoAplicacionDTO other = (ConfAccesoAplicacionDTO) obj;
if (this.codigoServicioAplicacion != other.codigoServicioAplicacion) {
return false;
}
if (!Objects.equals(this.servicioAplicacion, other.servicioAplicacion)) {
return false;
}
return true;
}
}
|
/*
* 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.web.server;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
/**
* Exception for errors that fit response status 400 (bad request) for use in
* Spring Web applications. The exception provides additional fields (e.g.
* an optional {@link MethodParameter} if related to the error).
*
* @author Rossen Stoyanchev
* @since 5.0
*/
@SuppressWarnings("serial")
public class ServerWebInputException extends ResponseStatusException {
@Nullable
private final MethodParameter parameter;
/**
* Constructor with an explanation only.
*/
public ServerWebInputException(String reason) {
this(reason, null, null);
}
/**
* Constructor for a 400 error linked to a specific {@code MethodParameter}.
*/
public ServerWebInputException(String reason, @Nullable MethodParameter parameter) {
this(reason, parameter, null);
}
/**
* Constructor for a 400 error with a root cause.
*/
public ServerWebInputException(String reason, @Nullable MethodParameter parameter, @Nullable Throwable cause) {
this(reason, parameter, cause, null, null);
}
/**
* Constructor with a message code and arguments for resolving the error
* "detail" via {@link org.springframework.context.MessageSource}.
* @since 6.0
*/
protected ServerWebInputException(String reason, @Nullable MethodParameter parameter, @Nullable Throwable cause,
@Nullable String messageDetailCode, @Nullable Object[] messageDetailArguments) {
super(HttpStatus.BAD_REQUEST, reason, cause, messageDetailCode, messageDetailArguments);
this.parameter = parameter;
}
/**
* Return the {@code MethodParameter} associated with this error, if any.
*/
@Nullable
public MethodParameter getMethodParameter() {
return this.parameter;
}
}
|
package com.example.todolist;
import android.widget.TextView;
import java.util.ArrayList;
public class ToDo {
public int id = -1;
public String name = "";
public String createdAt = "";
}
|
package com.example.controlecigarro;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Date;
public class Fumo {
private String emailUser;
private String tipo;
private Integer qtd;
private Date date;
public Fumo() {
}
public Fumo(String emailUser, String tipo, Integer qtd, Date date) {
this.emailUser = emailUser;
this.tipo = tipo;
this.qtd = qtd;
this.date = date;
}
public String getEmailUser() {
return emailUser;
}
public void setEmailUser(String emailUser) {
this.emailUser = emailUser;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public Integer getQtd() {
return qtd;
}
public void setQtd(Integer qtd) {
this.qtd = qtd;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void salvar(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("Fumo").child(emailUser).setValue(this);
}
}
|
package com.example.donisaurus.ecomplaint.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.android.volley.request.GsonRequest;
import com.example.donisaurus.ecomplaint.MyApplication;
import com.example.donisaurus.ecomplaint.R;
import com.example.donisaurus.ecomplaint.activity.KomentarActivity;
import com.example.donisaurus.ecomplaint.adapter.AdapterTL;
import com.example.donisaurus.ecomplaint.model.ModelLike;
import com.example.donisaurus.ecomplaint.model.ModelPost;
import com.example.donisaurus.ecomplaint.model.ModelPostDB;
import com.example.donisaurus.ecomplaint.model.ModelPostResponse;
import com.example.donisaurus.ecomplaint.model.ModelUser;
import com.example.donisaurus.ecomplaint.model.ResponOnly;
import com.example.donisaurus.ecomplaint.util.DroidPrefs;
import com.example.donisaurus.ecomplaint.util.HelperKey;
import com.example.donisaurus.ecomplaint.util.HelperStatus;
import com.example.donisaurus.ecomplaint.util.HelperUrl;
import com.example.donisaurus.ecomplaint.util.MySnackBar;
import com.google.gson.Gson;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import timber.log.Timber;
/**
* Created by ArikAchmad on 11/29/2015.
*/
public class FragTimeline extends Fragment implements AdapterTL.AdapterTLListener {
public static String TAG_URL = "tag_url";
public static String mUrl = null;
private RecyclerView mListTimeline;
private RequestQueue queue;
private View relativeLayout;
private AdapterTL mAdapter;
private static String TAG = FragTimeline.class.getSimpleName();
private ModelUser mUser;
public static List<ModelPost> listPosting = new ArrayList<>();
private void assignViews() {
mListTimeline = (RecyclerView) findViewById(R.id.listTimeline);
relativeLayout = getActivity().findViewById(R.id.relativeLayout);
queue = MyApplication.getInstance().getRequestQueue();
mAdapter = new AdapterTL(getActivity(), new ArrayList<ModelPost>());
mAdapter.setonItemClick(this);
}
@SuppressWarnings("ConstantConditions")
private View findViewById(int id) {
return getView().findViewById(id);
}
private void onSetView() {
mListTimeline.setHasFixedSize(true);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity());
mListTimeline.setLayoutManager(manager);
Bundle bundle = getArguments();
if (bundle != null) {
if (bundle.getInt(TAG_URL) == HelperUrl.TAG_ALL) {
mUrl = HelperUrl.GET_All;
} else if (bundle.getInt(TAG_URL) == HelperUrl.TAG_MOSTLIKE) {
mUrl = HelperUrl.GET_MOSTLIKE;
} else if (bundle.getInt(TAG_URL) == HelperUrl.TAG_ACAK) {
mUrl = HelperUrl.GET_ACAK;
} else if (bundle.getInt(TAG_URL) == HelperUrl.TAG_FILTER) {
mUrl = HelperUrl.GET_All;
} else {
mUrl = HelperUrl.GET_All;
}
} else {
mUrl = HelperUrl.GET_All;
}
}
private void get4Local() {
List<ModelPostDB> listPostDB = ModelPostDB.getALl();
List<ModelPost> listpost = new ArrayList<>();
for (ModelPostDB postDB : listPostDB) {
ModelPost post = new ModelPost();
post.setIdPost(postDB.getId_post());
post.setIdUser(postDB.getId_user());
post.setGambar(postDB.getGambar());
post.setWaktu(postDB.getWaktu());
post.setDiskripsi(postDB.getDiskripsi());
post.setLatitude(postDB.getLatitude());
post.setLongitude(postDB.getLongitude());
post.setNamaLokasi(postDB.getNama_lokasi());
post.setSuka(postDB.getSuka());
post.setNama(postDB.getUser());
post.setKomentar(postDB.getKomentar());
listpost.add(post);
}
mAdapter.onUpdate(listpost);
mListTimeline.setAdapter(mAdapter);
}
private void getDataPost() {
mAdapter.clear();
mUser = DroidPrefs.get(getActivity(), HelperKey.USER_KEY, ModelUser.class);
String mUrlLokal = mUrl + "/" + mUser.getIdUser();
queue.getCache().invalidate(mUrlLokal, true);
Log.d("url", mUrlLokal);
HashMap<String, String> params = new HashMap<>();
if (mAdapter.getItemCount() > 0) {
params.put("waktu", mAdapter.getItem(0).getWaktu());
} else {
params.put("waktu", String.valueOf(0));
}
Timber.d(mUrlLokal);
GsonRequest<ModelPostResponse> request = new GsonRequest<>(mUrlLokal, ModelPostResponse.class, null,
new PostResponse(),
new PostResponse()
);
request.setTag(FragTimeline.class.getSimpleName());
MyApplication.getInstance().addToRequestQueue(request);
//queue.add(request);
Log.d("error", request.toString());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_timeline, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
assignViews();
onSetView();
}
@Override
public void onPause() {
super.onPause();
if (queue != null) {
queue.cancelAll(FragTimeline.class.getSimpleName());
}
}
@Override
public void onResume() {
super.onResume();
getDataPost();
}
@Override
public void onClickViewAdapter(View view, int position) {
switch (view.getId()) {
case R.id.mLikeIc:
mAdapter.setonItemClick(null);
sendLike(position);
Toast.makeText(getActivity(), "like " + position, Toast.LENGTH_SHORT).show();
break;
case R.id.mCommentIc:
Intent pindahKomentar = new Intent(getActivity(), KomentarActivity.class);
pindahKomentar.putExtra(KomentarActivity.GET_IDPOST, mAdapter.getItem(position).getIdPost());
pindahKomentar.putExtra(KomentarActivity.GET_DISC, mAdapter.getItem(position).getDiskripsi());
startActivity(pindahKomentar);
break;
// case R.id.tl_map:
// Intent pindahMap = new Intent(getActivity(), ShowMapActivity.class);
// pindahMap.putExtra(ShowMapActivity.TAG_TITLE, mAdapter.getItem(position).getNamaLokasi());
// pindahMap.putExtra(ShowMapActivity.TAG_LAT, mAdapter.getItem(position).getLatitude());
// pindahMap.putExtra(ShowMapActivity.TAG_LNG, mAdapter.getItem(position).getLongitude());
// startActivity(pindahMap);
// break;
}
}
private void sendLike(int position) {
String mUrlLokal;
ModelPost post = mAdapter.getItem(position);
ModelLike like = new ModelLike();
if (post.getIdLike() == null) {
mUrlLokal = HelperUrl.POST_LIKE;
} else {
int tambahLike = post.getSuka() - 1;
BigDecimal idLike = new BigDecimal(post.getIdLike().toString());
Timber.d("idlike -->>" + idLike.intValue());
like.setIdLike(idLike.intValue());
post.setSuka(tambahLike);
post.setIdLike(null);
mAdapter.updateItem(post, position);
mUrlLokal = HelperUrl.DEL_LIKE;
}
like.setIdPost(post.getIdPost());
like.setIdUserLiked(mUser.getIdUser());
Timber.d(new Gson().toJson(like));
HashMap<String, String> params = new HashMap<>();
params.put("jsondata", new Gson().toJson(like));
GsonRequest<ResponOnly> request = new GsonRequest<>(
Request.Method.POST,
mUrlLokal,
ResponOnly.class,
null,
params,
new LiketResponse(post, position),
new LiketResponse(post, position)
);
queue.add(request);
}
private class LiketResponse implements Response.ErrorListener, Response.Listener<ResponOnly> {
private final ModelPost mPost;
private final int mPosition;
public LiketResponse(ModelPost post, int position) {
this.mPost = post;
this.mPosition = position;
}
@Override
public void onErrorResponse(VolleyError error) {
Timber.e(error.getMessage());
MySnackBar.init(relativeLayout, "Koneksi bermasalah").show();
mAdapter.setonItemClick(FragTimeline.this);
}
@Override
public void onResponse(ResponOnly response) {
mAdapter.setonItemClick(FragTimeline.this);
if (response.getStatus() != HelperStatus.SUKSES) {
MySnackBar.init(relativeLayout, "Server Bermasalah").show();
} else {
Timber.d("insert id ->" + response.getData().getInsertId());
if (response.getData().getInsertId() != 0) {
int tambahLike = mPost.getSuka() + 1;
mPost.setSuka(tambahLike);
mPost.setIdLike(response.getData().getInsertId());
mAdapter.updateItem(mPost, mPosition);
}
}
}
}
private class PostResponse implements Response.ErrorListener, Response.Listener<ModelPostResponse> {
@Override
public void onErrorResponse(VolleyError error) {
Timber.d("error", error.getMessage());
Log.d("error", error.getMessage());
MySnackBar.init(relativeLayout, "Koneksi bermasalah").show();
}
@Override
public void onResponse(ModelPostResponse response) {
if (response.getStatus() == HelperStatus.SUKSES){
if (!HelperUrl.FILTERED){
listPosting = response.getData();
}
if (HelperUrl.FILTERED){
mAdapter.onUpdate(listPosting);
HelperUrl.FILTERED = false;
}else {
mAdapter.onUpdate(response.getData());
}
mListTimeline.setAdapter(mAdapter);
MySnackBar.init(relativeLayout, "Koneksi berhasil").show();
// mAdapter.onUpdate(response.getData());
// mListTimeline.setAdapter(mAdapter);
//
// MySnackBar.init(relativeLayout, "Koneksi berhasil").show();
}else {
MySnackBar.init(relativeLayout, "Server bermasalah").show();
}
}
}
}
|
package com.dexvis.util;
import java.sql.Timestamp;
/**
* This class provides time related utilities.
*
* @author Patrick E. Martin
* @version 1.0
*
**/
public class SqlTimeFactory
{
/**
*
* This routine returns a timestamp containing the current time.
*
* @return A Timestamp containing the current time as known
* by the machine on which this routine is called.
*
**/
public static Timestamp currentTime()
{
return new Timestamp((new java.util.Date()).getTime());
}
/**
*
* This routine returns a timestamp containing the current time offset
* by a specified number of milliseconds.
*
* @param offset The number of milliseconds to offset this time by.
*
* @return A Timestamp containing the current time offset
* by the given offset. Current time is the current time
* as known by the machine on which this routine is called.
*
**/
public static Timestamp relativeTime(long offset)
{
return new Timestamp((new java.util.Date()).getTime() + offset);
}
/**
*
* This is a convenience function to convert a java.util.date to a
* Timestamp.
*
* @param date The date to convert.
*
* @return A Timestamp equivalent to the given date.
*
**/
public static Timestamp date2Timestamp(java.util.Date date)
{
//return new Timestamp(date.getYear(), date.getMonth(),
// date.getDate(), date.getHours(),
// date.getMinutes(), date.getSeconds(), 0);
return new Timestamp(date.getTime());
}
}
|
package pl.szymonleyk.jpa;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Address {
@Id
private int id;
private String city;
private String street;
@Column(name = "house_number")
private String houseNumber;
@Column(name = "flat_number")
private Integer flatNumber;
@Column(name = "post_code")
private String postCode;
public Address() {
}
public Address(String city, String street, String houseNumber, int flatNumber, String postCode) {
super();
this.id = id;
this.city = city;
this.street = street;
this.houseNumber = houseNumber;
this.flatNumber = flatNumber;
this.postCode = postCode;
}
@Override
public String toString() {
return "Address [id=" + id + ", city=" + city + ", street=" + street + ", houseNumber=" + houseNumber
+ ", flatNumber=" + flatNumber + ", postCode=" + postCode + "]";
}
}
|
/*
* 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.ledungcobra.scenes;
import com.ledungcobra.anotations.BackButton;
import com.ledungcobra.anotations.SearchTextField;
import com.ledungcobra.applicationcontext.AppContext;
import com.ledungcobra.entites.Class;
import com.ledungcobra.interfaces.Searchable;
import com.ledungcobra.models.ClassTableModel;
import com.ledungcobra.services.TeachingManagerService;
import lombok.SneakyThrows;
import lombok.val;
import org.hibernate.exception.ConstraintViolationException;
import javax.persistence.PersistenceException;
import javax.swing.*;
import java.util.List;
/**
* @author ledun
*/
public class ClassManagementScreen extends Screen implements Searchable
{
@BackButton
private javax.swing.JButton backBtn;
private javax.swing.JButton clearBtn;
private javax.swing.JButton deleteBtn;
private javax.swing.JButton editBtn;
private javax.swing.JButton insertBtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel addAClassLbl;
private javax.swing.JLabel jLabel6;
private javax.swing.JScrollPane jScrollPane1;
@SearchTextField
private javax.swing.JTextField searchTextField;
private javax.swing.JButton searchBtn;
private javax.swing.JTextField classNameTextField;
private javax.swing.JTable classListTable;
private TeachingManagerService service = AppContext.teachingManagerService;
private List<Class> classList;
private Class currentEditingClass;
private JPanel jPanel3;
private JPanel jPanel2;
private JPanel jPanel1;
// <editor-fold defaultstate="collapsed>
private void initComponents()
{
jPanel3 = new javax.swing.JPanel();
insertBtn = new javax.swing.JButton();
clearBtn = new javax.swing.JButton();
classNameTextField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
addAClassLbl = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
searchTextField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
searchBtn = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
deleteBtn = new javax.swing.JButton();
editBtn = new javax.swing.JButton();
backBtn = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
classListTable = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
insertBtn.setText("Insert");
clearBtn.setText("Clear");
jLabel2.setText("Class name");
addAClassLbl.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
addAClassLbl.setText("Add new class");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(classNameTextField)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(clearBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(insertBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(addAClassLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(addAClassLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(insertBtn)
.addComponent(clearBtn)
.addComponent(classNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(19, 19, 19))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Search", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 3, 14))); // NOI18N
jLabel1.setText("Keyword");
searchBtn.setText("Search");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
.addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 638, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(searchBtn)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(searchBtn))
.addContainerGap(23, Short.MAX_VALUE))
);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Manage Class", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 3, 14))); // NOI18N
deleteBtn.setBackground(new java.awt.Color(255, 51, 51));
deleteBtn.setText("Delete");
editBtn.setText("Edit");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(editBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(deleteBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(deleteBtn)
.addComponent(editBtn))
.addContainerGap())
);
backBtn.setText("Back");
jScrollPane1.setViewportView(classListTable);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(backBtn)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 858, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(24, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(backBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}
// </editor-fold>
private void classNameTextFieldActionPerformed(java.awt.event.ActionEvent evt)
{
}
private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt)
{
val selectedRowIndex = classListTable.getSelectedRow();
if (selectedRowIndex == -1)
{
JOptionPane.showMessageDialog(this, "You must select a row to delete");
return;
}
val row = this.classList.get(selectedRowIndex);
try
{
service.deleteAnClass(row);
} catch (Exception e)
{
JOptionPane.showMessageDialog(this, "A class have students in it you have to delete students first then perform this action latter");
return;
}
updateTableData();
}
private void editBtnActionPerformed(java.awt.event.ActionEvent evt)
{
val selectedRowIndex = classListTable.getSelectedRow();
if (selectedRowIndex == -1)
{
JOptionPane.showMessageDialog(this, "You must choose a record to edit");
return;
}
currentEditingClass = this.classList.get(selectedRowIndex);
this.classNameTextField.setText(currentEditingClass.getClassName());
this.insertBtn.setText("Update");
addAClassLbl.setText("Edit a class");
}
private void clearBtnActionPerformed(java.awt.event.ActionEvent evt)
{
classNameTextField.setText("");
this.currentEditingClass = null;
}
@SneakyThrows
private void insertBtnActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
val className = classNameTextField.getText();
if ("".equals(className))
{
JOptionPane.showMessageDialog(this, "Class name should not be empty");
} else
{
if (currentEditingClass != null)
{
currentEditingClass.setClassName(className);
service.updateClass(currentEditingClass);
currentEditingClass = null;
} else
{
val clazz = new Class();
clazz.setClassName(className);
service.addNewClass(clazz);
JOptionPane.showMessageDialog(this, "Add class name " + className + " done");
}
updateTableData();
}
} catch (ConstraintViolationException e)
{
JOptionPane.showMessageDialog(this, "Class name already exists");
} catch (PersistenceException e)
{
JOptionPane.showMessageDialog(this, "Class name already exists");
} finally
{
this.insertBtn.setText("Insert");
this.addAClassLbl.setText("Add new class");
this.classNameTextField.setText("");
}
}
public void searchBtnActionPerformed(java.awt.event.ActionEvent evt)
{
String keyword = searchTextField.getText();
if (keyword == null)
{
JOptionPane.showMessageDialog(this, "Keyword is null cannot perform this action");
return;
}
List<Class> resultClasses = service.searchClass(keyword);
updateTableData(resultClasses);
}
@Override
public void onCreateView()
{
initComponents();
updateTableData();
}
public void updateTableData()
{
this.classList = AppContext.teachingManagerService.getClasses();
classListTable
.setModel(new ClassTableModel(this.classList));
}
public void updateTableData(List<Class> updatedClasses)
{
this.classList = updatedClasses;
classListTable
.setModel(new ClassTableModel(this.classList));
}
@Override
public void addEventListener()
{
searchBtn.addActionListener(evt -> searchBtnActionPerformed(evt));
classNameTextField.addActionListener(evt -> classNameTextFieldActionPerformed(evt));
editBtn.addActionListener(evt -> editBtnActionPerformed(evt));
insertBtn.addActionListener(evt -> insertBtnActionPerformed(evt));
clearBtn.addActionListener(evt -> clearBtnActionPerformed(evt));
deleteBtn.addActionListener(evt -> deleteBtnActionPerformed(evt));
}
}
|
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.class2greylist;
import static com.google.common.truth.Truth.assertThat;
import static org.testng.Assert.expectThrows;
import static org.testng.Assert.assertThrows;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class ApiResolverTest extends AnnotationHandlerTestBase {
@Test
public void testFindPublicAlternativeExactly()
throws JavadocLinkSyntaxError, AlternativeNotFoundError,
RequiredAlternativeNotSpecifiedError {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("La/b/C;->foo(I)V", "La/b/C;->bar(I)V")));
ApiResolver resolver = new ApiResolver(publicApis);
resolver.resolvePublicAlternatives("{@link a.b.C#foo(int)}", "Lb/c/D;->bar()V", 1);
}
@Test
public void testFindPublicAlternativeDeducedPackageName()
throws JavadocLinkSyntaxError, AlternativeNotFoundError,
RequiredAlternativeNotSpecifiedError {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("La/b/C;->foo(I)V", "La/b/C;->bar(I)V")));
ApiResolver resolver = new ApiResolver(publicApis);
resolver.resolvePublicAlternatives("{@link C#foo(int)}", "La/b/D;->bar()V", 1);
}
@Test
public void testFindPublicAlternativeDeducedPackageAndClassName()
throws JavadocLinkSyntaxError, AlternativeNotFoundError,
RequiredAlternativeNotSpecifiedError {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("La/b/C;->foo(I)V", "La/b/C;->bar(I)V")));
ApiResolver resolver = new ApiResolver(publicApis);
resolver.resolvePublicAlternatives("{@link #foo(int)}", "La/b/C;->bar()V", 1);
}
@Test
public void testFindPublicAlternativeDeducedParameterTypes()
throws JavadocLinkSyntaxError, AlternativeNotFoundError,
RequiredAlternativeNotSpecifiedError {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("La/b/C;->foo(I)V", "La/b/C;->bar(I)V")));
ApiResolver resolver = new ApiResolver(publicApis);
resolver.resolvePublicAlternatives("{@link #foo}", "La/b/C;->bar()V", 1);
}
@Test
public void testFindPublicAlternativeFailDueToMultipleParameterTypes()
throws SignatureSyntaxError {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("La/b/C;->foo(I)V", "La/b/C;->bar(I)I", "La/b/C;->foo(II)V")));
ApiResolver resolver = new ApiResolver(publicApis);
MultipleAlternativesFoundError e = expectThrows(MultipleAlternativesFoundError.class,
() -> resolver.resolvePublicAlternatives("{@link #foo}", "La/b/C;->bar()V", 1));
assertThat(e.almostMatches).containsExactly(
ApiComponents.fromDexSignature("La/b/C;->foo(I)V"),
ApiComponents.fromDexSignature("La/b/C;->foo(II)V")
);
}
@Test
public void testFindPublicAlternativeFailNoAlternative() {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("La/b/C;->bar(I)V")));
ApiResolver resolver = new ApiResolver(publicApis);
assertThrows(MemberAlternativeNotFoundError.class, ()
-> resolver.resolvePublicAlternatives("{@link #foo(int)}", "La/b/C;->bar()V", 1));
}
@Test
public void testFindPublicAlternativeFailNoAlternativeNoParameterTypes() {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("La/b/C;->bar(I)V")));
ApiResolver resolver = new ApiResolver(publicApis);
assertThrows(MemberAlternativeNotFoundError.class,
() -> resolver.resolvePublicAlternatives("{@link #foo}", "La/b/C;->bar()V", 1));
}
@Test
public void testNoPublicClassAlternatives() {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>());
ApiResolver resolver = new ApiResolver(publicApis);
expectThrows(NoAlternativesSpecifiedError.class,
() -> resolver.resolvePublicAlternatives("Foo", "La/b/C;->bar()V", 1));
}
@Test
public void testPublicAlternativesJustPackageAndClassName()
throws JavadocLinkSyntaxError, AlternativeNotFoundError,
RequiredAlternativeNotSpecifiedError {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("La/b/C;->bar(I)V")));
ApiResolver resolver = new ApiResolver(publicApis);
resolver.resolvePublicAlternatives("Foo {@link a.b.C}", "Lb/c/D;->bar()V", 1);
}
@Test
public void testPublicAlternativesJustClassName()
throws JavadocLinkSyntaxError, AlternativeNotFoundError,
RequiredAlternativeNotSpecifiedError {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList("La/b/C;->bar(I)V")));
ApiResolver resolver = new ApiResolver(publicApis);
resolver.resolvePublicAlternatives("Foo {@link C}", "La/b/D;->bar()V", 1);
}
@Test
public void testNoPublicAlternativesButHasExplanation()
throws JavadocLinkSyntaxError, AlternativeNotFoundError,
RequiredAlternativeNotSpecifiedError {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>());
ApiResolver resolver = new ApiResolver(publicApis);
resolver.resolvePublicAlternatives("Foo {@code bar}", "La/b/C;->bar()V", 1);
}
@Test
public void testNoPublicAlternativesSpecifiedWithMaxSdk() {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>());
ApiResolver resolver = new ApiResolver(publicApis);
assertThrows(RequiredAlternativeNotSpecifiedError.class,
() -> resolver.resolvePublicAlternatives(null, "La/b/C;->bar()V", 29));
}
@Test
public void testNoPublicAlternativesSpecifiedWithMaxLessThanQ()
throws JavadocLinkSyntaxError, AlternativeNotFoundError,
RequiredAlternativeNotSpecifiedError {
Set<String> publicApis = Collections.unmodifiableSet(new HashSet<>());
ApiResolver resolver = new ApiResolver(publicApis);
resolver.resolvePublicAlternatives(null, "La/b/C;->bar()V", 28);
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.saml.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.xmlbeans.XmlObject;
import eu.unicore.samly2.SAMLConstants;
import eu.unicore.samly2.binding.HttpPostBindingSupport;
import eu.unicore.samly2.binding.HttpRedirectBindingSupport;
import eu.unicore.samly2.binding.SAMLMessageType;
import eu.unicore.samly2.exceptions.SAMLServerException;
import pl.edu.icm.unity.idpcommon.EopException;
import pl.edu.icm.unity.saml.SAMLProcessingException;
import pl.edu.icm.unity.saml.SamlProperties.Binding;
import pl.edu.icm.unity.saml.idp.FreemarkerHandler;
import pl.edu.icm.unity.server.utils.Log;
/**
* Base code for producing responses which are returned (some with the help of Freemarker) to the user's browser.
* Some of the responses (low level errors) are shown as an error page. Other responses (high level errors
* and correct responses) are producing a web page which is redirecting the user to the final destination.
* @author K. Benedyczak
*/
public abstract class ResponseHandlerBase
{
private static final Logger log = Log.getLogger(Log.U_SERVER_SAML, ResponseHandlerBase.class);
protected FreemarkerHandler freemarker;
public ResponseHandlerBase(FreemarkerHandler freemarker)
{
this.freemarker = freemarker;
}
/**
* Shows a page with error.
* @param error
* @param context
* @param response
* @throws SAMLProcessingException
* @throws IOException
* @throws EopException
*/
protected void showError(Exception error, HttpServletResponse response)
throws IOException, EopException
{
response.setContentType("application/xhtml+xml; charset=utf-8");
PrintWriter w = response.getWriter();
Map<String, String> data = new HashMap<String, String>();
data.put("error", error.getMessage());
if (error.getCause() != null)
data.put("errorCause", error.getCause().toString());
freemarker.process("finishError.ftl", data, w);
throw new EopException();
}
protected void sendBackErrorResponse(SAMLServerException error, String serviceUrl, String encodedResponse,
String relayState, HttpServletResponse response) throws SAMLProcessingException,
IOException, EopException
{
//security measure: if the request is invalid (usually not trusted) don't send the response,
//as it may happen that the response URL is evil.
SAMLConstants.SubStatus subStatus = error.getSamlSubErrorId();
if (subStatus != null && subStatus.equals(SAMLConstants.SubStatus.STATUS2_REQUEST_DENIED))
{
log.debug("Returning of an error response to the requester was blocked for security reasons."
+ " Instead an error page should be presented.");
throw new SAMLProcessingException(error);
}
Map<String, String> data = new HashMap<String, String>();
data.put("SAMLResponse", encodedResponse);
data.put("samlService", serviceUrl);
data.put("samlError", error.getMessage());
if (relayState != null)
data.put("RelayState", relayState);
response.setContentType("application/xhtml+xml; charset=utf-8");
PrintWriter w = response.getWriter();
freemarker.process("finishSaml.ftl", data, w);
throw new EopException();
}
protected void sendRequest(Binding binding, XmlObject requestDoc, String serviceUrl,
String relayState, HttpServletResponse response, String info)
throws IOException, EopException
{
switch (binding)
{
case HTTP_POST:
handlePostGeneric(requestDoc.xmlText(), info, SAMLMessageType.SAMLRequest,
serviceUrl, relayState, response);
break;
case HTTP_REDIRECT:
handleRedirectGeneric(requestDoc.xmlText(), info, SAMLMessageType.SAMLRequest,
serviceUrl, relayState, response);
break;
default:
throw new IllegalStateException("Unsupported binding: " + binding);
}
}
protected void sendResponse(Binding binding, XmlObject responseDoc, String serviceUrl,
String relayState, HttpServletResponse response, String info)
throws IOException, EopException
{
switch (binding)
{
case HTTP_POST:
handlePostGeneric(responseDoc.xmlText(), info, SAMLMessageType.SAMLResponse,
serviceUrl, relayState, response);
break;
case HTTP_REDIRECT:
handleRedirectGeneric(responseDoc.xmlText(), info, SAMLMessageType.SAMLResponse,
serviceUrl, relayState, response);
break;
default:
throw new IllegalStateException("Unsupported binding: " + binding);
}
}
protected void handleRedirectGeneric(String xml, String info, SAMLMessageType type, String serviceUrl,
String relayState, HttpServletResponse response) throws IOException, EopException
{
setCommonHeaders(response);
log.debug("Returning " + info + " " + type + " with HTTP Redirect binding to " + serviceUrl);
String redirectURL = HttpRedirectBindingSupport.getRedirectURL(type,
relayState, xml, serviceUrl);
if (log.isTraceEnabled())
{
log.trace("SAML " + type + " is:\n" + xml);
log.trace("Returned Redirect URL is:\n" + redirectURL);
}
response.sendRedirect(redirectURL);
throw new EopException();
}
protected void handlePostGeneric(String xml, String info, SAMLMessageType type, String serviceUrl,
String relayState, HttpServletResponse response) throws IOException, EopException
{
response.setContentType("text/html; charset=utf-8");
setCommonHeaders(response);
response.setDateHeader("Expires", -1);
log.debug("Returning " + info + " " + type + " with HTTP POST binding to " + serviceUrl);
String htmlResponse = HttpPostBindingSupport.getHtmlPOSTFormContents(
type, serviceUrl, xml, relayState);
if (log.isTraceEnabled())
{
log.trace("SAML " + info + " is:\n" + xml);
log.trace("Returned POST form is:\n" + htmlResponse);
}
response.getWriter().append(htmlResponse);
throw new EopException();
}
protected void setCommonHeaders(HttpServletResponse response)
{
response.setHeader("Cache-Control","no-cache,no-store");
response.setHeader("Pragma","no-cache");
}
}
|
package net.lvcy.card.eumn;
public enum CardStatus {
ACTIVE,DISABLE,SUCCESS
}
|
package solo;
import java.io.Serializable;
/**
* @author kokichi3000
*
*/
public final class CarControl implements Serializable{
/**
*
*/
private static final long serialVersionUID = -7556980105726757107L;
private static final int PRECISION_DIGIT = 6;
private static final int PRECISION = 1000000;
private static final int int10pow[] = {
1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000
};
private static final long long10pow[] = {
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000L,
100000000000L,
1000000000000L,
10000000000000L,
100000000000000L,
1000000000000000L,
10000000000000000L,
100000000000000000L,
1000000000000000000L
};
// private static final byte[] buf = new char[200];
public final static byte[] output = new byte[200];
private final static byte[] acc = {'(','a','c','c','e','l',' '};
private final static byte[] brk = {')','(','b','r','a','k','e',' '};
private final static byte[] gr = {')','(','g','e','a','r',' '};
private final static byte[] st = {')','(','s','t','e','e','r',' '};
private final static byte[] mt = {')','(','m','e','t','a',' '};
public double accel;
public double brake;
public int gear;
public double steer;
public int meta;//1 = RESTART, 2= SHUTDOWN
static{
System.arraycopy(acc, 0, output, 0, acc.length);
}
/**
* Copy Constructor
*
* @param carControl a <code>CarControl</code> object
*/
public CarControl(CarControl carControl)
{
this.accel = carControl.accel;
this.brake = carControl.brake;
this.gear = carControl.gear;
this.steer = carControl.steer;
this.meta = carControl.meta;
}
// public CarControl(String s){
// MessageParser mp = new MessageParser(s);
// String str = (String)(mp.getReading("accel"));
// accel = (str==null)?0:Double.parseDouble(str);
// str = (String)(mp.getReading("brake"));
// brake = (str==null)?0:Double.parseDouble(str);
// str = (String)(mp.getReading("gear"));
// gear = (str==null)?0:Integer.parseInt(str);
// str = (String)(mp.getReading("steer"));
// steer = (str==null)?0:Double.parseDouble(str);
// str = (String)(mp.getReading("meta"));
// meta = (str==null)?0:Integer.parseInt(str);
// }
public CarControl(){
meta = 1;
}
public CarControl(double accel, double brake, int gear, double steer,
int meta) {
this.accel = accel;
this.brake = brake;
this.gear = gear;
this.steer = steer;
this.meta = meta;
}
public CarControl(double accel, double brake, int gear, double steer) {
this.accel = accel;
this.brake = brake;
this.gear = gear;
this.steer = steer;
meta = 0;
}
// public void fromString(String s){
// MessageParser mp = new MessageParser(s);
// String str = (String)(mp.getReading("accel"));
// accel = (str==null)?0:Double.parseDouble(str);
// str = (String)(mp.getReading("brake"));
// brake = (str==null)?0:Double.parseDouble(str);
// str = (String)(mp.getReading("gear"));
// gear = (str==null)?0:Integer.parseInt(str);
// str = (String)(mp.getReading("steer"));
// steer = (str==null)?0:Double.parseDouble(str);
// str = (String)(mp.getReading("meta"));
// meta = (str==null)?0:Integer.parseInt(str);
// }
public double getAccel() {
return accel;
}
public void setAccel(double accel) {
this.accel = accel;
}
public double getBrake() {
return brake;
}
public void setBrake(double brake) {
this.brake = brake;
}
public int getGear() {
return gear;
}
public void setGear(int gear) {
this.gear = gear;
}
public double getSteer() {
return steer;
}
public void setSteer(double steer) {
this.steer = steer;
}
public int getMeta() {
return meta;
}
public void setMeta(int meta) {
this.meta = meta;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(80);
builder.append("(accel ");
builder.append(accel);
builder.append(")( brake ");
builder.append(brake);
builder.append(")( gear ");
builder.append(gear);
builder.append(")( steer ");
builder.append(steer);
builder.append(")( meta ");
builder.append(meta);
builder.append(")");
return builder.toString();
}
/**
* Constructs a <code>String</code> with all attributes
* in name = value format.
*
* @return a <code>String</code> representation
* of this object.
*/
public final int toBytes() {
byte[] output = CarControl.output;
int len = acc.length;
len = double2string(accel, output, len);
System.arraycopy(brk, 0, output, len, brk.length);
len+=brk.length;
len = double2string(this.brake, output, len);
System.arraycopy(gr, 0, output, len, gr.length);
len+=gr.length;
len = int2string(gear, output, len);
System.arraycopy(st, 0, output, len, st.length);
len+=st.length;
len = double2string(this.steer, output, len);
System.arraycopy(mt, 0, output, len, mt.length);
len+=mt.length;
len = int2string(meta, output, len);
output[len++] =')';
// System.out.println(new String(buf,0,len));
// System.out.println("toString() : "+toString());
return len;
}
private static final int int2string(int ivalue,byte[] s,int from){
if (ivalue==0){
s[from++]='0';
return from;
}
int ndigits = 0;
if (ivalue<0) {
s[from++] ='-';
ivalue = -ivalue;
}
while (ivalue>=int10pow[ndigits]) ndigits++;
int digitno = from+ndigits-1;
int c =ivalue%10;
while ( ivalue != 0){
s[digitno--] = (byte)(c+'0');
ivalue /= 10;
c = ivalue%10;
}
return from+ndigits;
}
private static final int double2string(double val,byte[] s,int from){
long lval = Math.round(val*PRECISION);
if (lval==0) {
s[from++]='0';
return from;
}
if (lval<0){
s[from++] = '-';
lval = -lval;
}
int ndigits = 0;
int rt = 0;
int dotIndex;
if (lval<=1000000000){
int ivalue = (int)lval;
while (ivalue>=int10pow[ndigits]) ndigits++;
dotIndex = ndigits-PRECISION_DIGIT;
if (dotIndex<=0) {
s[from++]='0';
s[from++]='.';
while (dotIndex++<0) s[from++]='0';
int digitno = from+ndigits-1;
rt = digitno;
rt++;
int c =ivalue%10;
while ( c == 0 && ivalue>0){
digitno--;
rt--;
ivalue /= 10;
c = ivalue%10;
}
while ( ivalue != 0){
s[digitno--] = (byte)(c+'0');
ivalue /= 10;
c = ivalue%10;
}
} else {
int c =ivalue%10;
while ( c == 0 && ndigits>dotIndex){
ndigits--;
ivalue /= 10;
c = ivalue%10;
}
int digitno = from+ndigits;
rt = digitno+1;
if (ndigits==dotIndex) {
digitno--;
rt--;
s[digitno--] = (byte)(c+'0');
ivalue /= 10;
c = ivalue%10;
while ( ivalue != 0){
s[digitno--] = (byte)(c+'0');
ivalue /= 10;
c = ivalue%10;
}
return rt;
}
while ( ivalue != 0){
if (ndigits==dotIndex) {
s[digitno--] = '.';
ndigits--;
}
ndigits--;
s[digitno--] = (byte)(c+'0');
ivalue /= 10;
c = ivalue%10;
}
}
} else {
while (lval>=long10pow[ndigits]) ndigits++;
dotIndex = ndigits-PRECISION_DIGIT;
if (dotIndex<=0) {
s[from++]='0';
s[from++]='.';
while (dotIndex++<0) s[from++]='0';
int digitno = from+ndigits-1;
rt = digitno;
rt++;
int c =(int)(lval%10L);
while ( c == 0 && lval>0){
digitno--;
rt--;
lval /= 10;
c =(int)(lval%10L);
}
while ( lval != 0){
s[digitno--] = (byte)(c+'0');
lval /= 10;
c =(int)(lval%10L);
}
} else {
int c =(int)(lval%10L);
while ( c == 0 && ndigits>dotIndex){
ndigits--;
lval /= 10;
c =(int)(lval%10L);
}
int digitno = from+ndigits;
rt = digitno+1;
if (lval<=Integer.MAX_VALUE){
int ivalue = (int)lval;
if (ndigits==dotIndex) {
digitno--;
rt--;
s[digitno--] = (byte)(c+'0');
ivalue /= 10;
c = ivalue%10;
while ( ivalue != 0){
s[digitno--] = (byte)(c+'0');
ivalue /= 10;
c = ivalue%10;
}
return rt;
}
while ( ivalue != 0){
if (ndigits==dotIndex) {
s[digitno--] = '.';
ndigits--;
}
ndigits--;
s[digitno--] = (byte)(c+'0');
ivalue /= 10;
c = ivalue%10;
}
} else {
if (ndigits==dotIndex) {
digitno--;
rt--;
s[digitno--] = (byte)(c+'0');
lval /= 10;
c =(int)(lval%10L);
while ( lval != 0){
s[digitno--] = (byte)(c+'0');
lval /= 10;
c =(int)(lval%10L);
}
return rt;
}
while ( lval != 0){
if (ndigits==dotIndex) {
s[digitno--] = '.';
ndigits--;
}
ndigits--;
s[digitno--] = (byte)(c+'0');
lval /= 10;
c =(int)(lval%10L);
}
}
}
}
return rt;
}
}
|
/*
* Created by Angel Leon (@gubatron), Alden Torres (aldenml)
* Copyright (c) 2011-2014, FrostWire(R). All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.frostwire.gui;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.frostwire.core.ConfigurationManager;
import com.frostwire.core.Constants;
import com.frostwire.core.FileDescriptor;
import com.frostwire.core.providers.ShareFilesDB;
import com.frostwire.core.providers.ShareFilesDB.Columns;
import com.frostwire.database.Cursor;
import com.frostwire.gui.bittorrent.TorrentUtil;
import com.frostwire.gui.library.LibraryMediator;
import com.frostwire.localpeer.Finger;
/**
* @author gubatron
* @author aldenml
*
*/
public final class Librarian {
private static final Logger LOG = Logger.getLogger(Librarian.class.getName());
public static final int FILE_STATE_UNSHARED = 0;
public static final int FILE_STATE_SHARING = 1;
public static final int FILE_STATE_SHARED = 2;
//private final Set<String> pathSharedSet;
private final Set<String> pathSharingSet;
private final ExecutorService shareFileExec;
private static final Librarian instance = new Librarian();
public static Librarian instance() {
return instance;
}
private Librarian() {
//this.pathSharedSet = Collections.synchronizedSet(new HashSet<String>());
this.pathSharingSet = Collections.synchronizedSet(new HashSet<String>());
this.shareFileExec = Executors.newSingleThreadExecutor();
}
public Finger finger() {
Finger finger = new Finger();
finger.uuid = ConfigurationManager.instance().getUUIDString();
finger.nickname = ConfigurationManager.instance().getNickname();
finger.frostwireVersion = Constants.FROSTWIRE_VERSION_STRING;
finger.totalShared = getNumSharedFiles();
DeviceInfo di = new DeviceInfo();
finger.deviceVersion = di.getVersion();
finger.deviceModel = di.getModel();
finger.deviceProduct = di.getProduct();
finger.deviceName = di.getName();
finger.deviceManufacturer = di.getManufacturer();
finger.deviceBrand = di.getBrand();
finger.deviceScreen = di.getScreenMetrics();
finger.numSharedAudioFiles = getNumSharedFiles(Constants.FILE_TYPE_AUDIO);
finger.numSharedVideoFiles = getNumSharedFiles(Constants.FILE_TYPE_VIDEOS);
finger.numSharedPictureFiles = getNumSharedFiles(Constants.FILE_TYPE_PICTURES);
finger.numSharedDocumentFiles = getNumSharedFiles(Constants.FILE_TYPE_DOCUMENTS);
finger.numSharedApplicationFiles = getNumSharedFiles(Constants.FILE_TYPE_APPLICATIONS);
finger.numSharedRingtoneFiles = getNumSharedFiles(Constants.FILE_TYPE_RINGTONES);
return finger;
}
public int getNumSharedFiles() {
int result = 0;
for (byte i = 0; i < 6; i++) {
result += getNumSharedFiles(i);
}
return result;
}
/**
*
* @param fileType
* @param onlyShared - If false, forces getting all files, shared or unshared.
* @return
*/
public int getNumSharedFiles(byte fileType) {
Cursor c = null;
int numFiles = 0;
try {
ShareFilesDB db = ShareFilesDB.intance();
String[] columns = new String[] { Columns.ID, Columns.FILE_PATH, Columns.SHARED };
String where = Columns.FILE_TYPE + " = ? AND " + Columns.SHARED + " = ?";
String[] whereArgs = new String[] { String.valueOf(fileType), String.valueOf(true) };
c = db.query(columns, where, whereArgs, null);
List<FileDescriptor> fds = filteredOutBadRows(c);
numFiles = fds.size();
} catch (Exception e) {
LOG.log(Level.WARNING, "Failed to get num of shared files", e);
} finally {
if (c != null) {
c.close();
}
}
return numFiles;
}
public boolean isFileShared(String filePath) {
Cursor c = null;
boolean isShared = false;
try {
ShareFilesDB db = ShareFilesDB.intance();
String[] columns = new String[] { Columns.ID, Columns.FILE_PATH, Columns.SHARED };
String where = Columns.FILE_PATH + " = ?";
String[] whereArgs = new String[] { filePath };
c = db.query(columns, where, whereArgs, null);
List<FileDescriptor> fds = filteredOutBadRows(c);
isShared = fds.size() == 1;
} catch (Exception e) {
LOG.log(Level.WARNING, "Failed to get num of shared files", e);
} finally {
if (c != null) {
c.close();
}
}
return isShared;
}
private List<FileDescriptor> filteredOutBadRows(Cursor c) {
int filePathCol = c.getColumnIndex(Columns.FILE_PATH);
if (filePathCol == -1) {
throw new IllegalArgumentException("Can't perform filtering without file path column in cursor");
}
List<FileDescriptor> fds = new LinkedList<FileDescriptor>();
final Set<String> toRemove = new HashSet<String>();
while (c.moveToNext()) {
String filePath = c.getString(filePathCol);
if (!(new File(filePath)).exists()) {
//pathSharedSet.remove(filePath);
toRemove.add(filePath);
continue;
}
FileDescriptor fd = cursorToFileDescriptor(c);
fds.add(fd);
}
shareFileExec.execute(new Runnable() {
@Override
public void run() {
try {
for (String filePath : toRemove) {
deleteFromShareTable(filePath);
}
} catch (Throwable e) {
LOG.log(Level.WARNING, "Error deleting no existent files", e);
}
}
});
return fds;
}
public List<FileDescriptor> getSharedFiles(byte fileType) {
List<FileDescriptor> result = new ArrayList<FileDescriptor>();
Cursor c = null;
try {
ShareFilesDB db = ShareFilesDB.intance();
String[] columns = new String[] { Columns.ID, Columns.FILE_TYPE, Columns.FILE_PATH, Columns.FILE_SIZE, Columns.MIME, Columns.DATE_ADDED, Columns.DATE_MODIFIED, Columns.SHARED, Columns.TITLE, Columns.ARTIST, Columns.ALBUM, Columns.YEAR };
String where = Columns.FILE_TYPE + " = ? AND " + Columns.SHARED + " = ?";
String[] whereArgs = new String[] { String.valueOf(fileType), String.valueOf(true) };
c = db.query(columns, where, whereArgs, null);
List<FileDescriptor> fds = filteredOutBadRows(c);
return fds;
} catch (Throwable e) {
LOG.log(Level.WARNING, "General failure getting files", e);
} finally {
if (c != null) {
c.close();
}
}
return result;
}
public void scan(File file) {
scan(file, TorrentUtil.getIgnorableFiles());
}
public int getFileShareState(String filePath) {
if (pathSharingSet.contains(filePath)) {
return FILE_STATE_SHARING;
}
if (isFileShared(filePath)) {// pathSharedSet.contains(path)) {
return FILE_STATE_SHARED;
}
return FILE_STATE_UNSHARED;
}
private void scan(File file, Set<File> ignorableFiles) {
if (ignorableFiles.contains(file)) {
return;
}
if (file.isDirectory()) {
for (File child : file.listFiles()) {
if (child.isDirectory() || child.isFile()) {
scan(child);
}
}
} else if (file.isFile()) {
new UniversalScanner().scan(file.getAbsolutePath());
}
}
public void shareFile(final String filePath, final boolean share) {
shareFile(filePath, share, true);
}
public void shareFile(final String filePath, final boolean share, final boolean refreshPing) {
if (pathSharingSet.contains(filePath)) {
return;
}
pathSharingSet.add(filePath);
Runnable r = new Runnable() {
@Override
public void run() {
deleteFromShareTable(filePath);
if (share) {
new UniversalScanner().scan(filePath);
//pathSharedSet.add(filePath);
}
pathSharingSet.remove(filePath);
if (refreshPing) {
LibraryMediator.instance().getDeviceDiscoveryClerk().updateLocalPeer();
}
}
};
shareFileExec.execute(r);
}
private void deleteFromShareTable(String filePath) {
String where = Columns.FILE_PATH + " = ?";
String[] whereArgs = new String[] { filePath };
ShareFilesDB db = ShareFilesDB.intance();
db.delete(where, whereArgs);
}
public void deleteFolderFilesFromShareTable(String folderPath) {
String where = Columns.FILE_PATH + " LIKE ?";
String[] whereArgs = new String[] { folderPath + "%" };
ShareFilesDB db = ShareFilesDB.intance();
try {
db.delete(where, whereArgs);
} catch (Exception e) {
}
}
private FileDescriptor cursorToFileDescriptor(Cursor c) {
FileDescriptor fd = new FileDescriptor();
int col = -1;
col = c.getColumnIndex(Columns.ID);
if (col != -1) {
fd.id = c.getInt(col);
}
col = c.getColumnIndex(Columns.FILE_TYPE);
if (col != -1) {
fd.fileType = c.getByte(col);
}
col = c.getColumnIndex(Columns.FILE_PATH);
if (col != -1) {
fd.filePath = c.getString(col);
}
col = c.getColumnIndex(Columns.FILE_SIZE);
if (col != -1) {
fd.fileSize = c.getLong(col);
}
col = c.getColumnIndex(Columns.MIME);
if (col != -1) {
fd.mime = c.getString(col);
}
col = c.getColumnIndex(Columns.DATE_ADDED);
if (col != -1) {
fd.dateAdded = c.getLong(col);
}
col = c.getColumnIndex(Columns.DATE_MODIFIED);
if (col != -1) {
fd.dateModified = c.getLong(col);
}
col = c.getColumnIndex(Columns.SHARED);
if (col != -1) {
fd.shared = c.getBoolean(col);
}
col = c.getColumnIndex(Columns.TITLE);
if (col != -1) {
fd.title = c.getString(col);
}
col = c.getColumnIndex(Columns.ARTIST);
if (col != -1) {
fd.artist = c.getString(col);
}
col = c.getColumnIndex(Columns.ALBUM);
if (col != -1) {
fd.album = c.getString(col);
}
col = c.getColumnIndex(Columns.YEAR);
if (col != -1) {
fd.year = c.getString(col);
}
return fd;
}
public FileDescriptor getSharedFileDescriptor(byte fileType, int fileId) {
FileDescriptor result = null;
Cursor c = null;
try {
ShareFilesDB db = ShareFilesDB.intance();
String[] columns = new String[] { Columns.ID, Columns.FILE_TYPE, Columns.FILE_PATH, Columns.FILE_SIZE, Columns.MIME, Columns.DATE_ADDED, Columns.DATE_MODIFIED, Columns.SHARED, Columns.TITLE, Columns.ARTIST, Columns.ALBUM, Columns.YEAR };
String where = Columns.FILE_TYPE + " = ? AND " + Columns.ID + " = ? AND " + Columns.SHARED + " = ?";
String[] whereArgs = new String[] { String.valueOf(fileType), String.valueOf(fileId), String.valueOf(true) };
c = db.query(columns, where, whereArgs, null);
List<FileDescriptor> fds = filteredOutBadRows(c);
return fds.size() > 0 ? fds.get(0) : null;
} catch (Throwable e) {
LOG.log(Level.WARNING, "General failure getting files", e);
} finally {
if (c != null) {
c.close();
}
}
return result;
}
}
|
package com.pyg.shop.controller;
import ReturnResult.Results;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import utils.FastDFSClient;
import java.io.File;
import java.io.Serializable;
/**
* 文件上传Controller
*/
@RestController
public class UploadController implements Serializable {
@Value("${FILE_SERVER_URL}")
private String file_server_url;//文件服务器地址
@RequestMapping("/upload")
public Results upload(MultipartFile file){
//取文件拓展名
String originalFilename = file.getOriginalFilename();
String ex = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
try {
//2、创建一个 FastDFS 的客户端
FastDFSClient fastDFSClient =new FastDFSClient("classpath:config/fdfs_client.conf");
//3、执行上传处理
String path = fastDFSClient.uploadFile(file.getBytes(), ex);
String url=file_server_url+path;
return new Results(true,url);
} catch (Exception e) {
e.printStackTrace();
return new Results(false,"上传失败");
}
}
}
|
package com.esum.comp.dbm.util.sql;
public interface ScriptConstants {
public final String CURRENT_DATE = "date";
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.