code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package GUI;
import java.awt.Choice;
import java.awt.Dimension;
import BackendSimulation.*;
import ImportsAndExports.*;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.BoundedRangeModel;
import javax.swing.ComboBoxModel;
import javax.swing.DebugGraphics;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.PlainDocument;
import oracle.jdeveloper.layout.VerticalFlowLayout;
import oracle.jdeveloper.layout.XYConstraints;
import oracle.jdeveloper.layout.XYLayout;
public class Training extends JFrame {
int f = 0;
static LinkedList<String> drills = dbImporting.readDB("Training drills.txt");
static LinkedList<String> explicatii = dbImporting.readDB("Explicatii.txt");
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private JPanel jPanel1 = new JPanel();
private JPanel jPanel2 = new JPanel();
private JLabel jLabel1 = new JLabel();
private JLabel jLabel2 = new JLabel();
private JLabel jLabel3 = new JLabel();
private JLabel jLabel4 = new JLabel();
private JLabel jLabel5 = new JLabel();
private JLabel jLabel6 = new JLabel();
private JLabel jLabel7 = new JLabel();
private JSlider jSlider1 = new JSlider();
private JLabel jLabel8 = new JLabel();
private JLabel jLabel9 = new JLabel();
private JScrollPane jScrollPane1 = new JScrollPane();
private JTextArea jTextArea1 = new JTextArea();
private JLabel jLabel10 = new JLabel();
private JScrollPane jScrollPane2 = new JScrollPane();
private JList jList1 = new JList(new TrainingList());
private JScrollPane jScrollPane3 = new JScrollPane();
private JTextArea jTextArea2 = new JTextArea();
static int trainingIntensity;
private JPanel jPanel3 = new JPanel();
private Choice choice1 = new Choice();
private Choice choice3 = new Choice();
private Choice choice4 = new Choice();
private Choice choice5 = new Choice();
private Choice choice2 = new Choice();
private XYLayout xYLayout1 = new XYLayout();
private Choice choice6 = new Choice();
private Choice choice7 = new Choice();
public Training() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize(new Dimension(435, 333));
jTabbedPane1.setBounds(new Rectangle(5, 10, 425, 295));
jPanel1.setLayout(null);
jPanel2.setLayout(null);
jLabel1.setText("Monday");
jLabel1.setBounds(new Rectangle(0, 10, 65, 20));
jLabel2.setText("Tuesday");
jLabel2.setBounds(new Rectangle(0, 30, 65, 20));
jLabel3.setText("Thursday");
jLabel3.setBounds(new Rectangle(0, 50, 65, 20));
jLabel4.setText("Wedensday");
jLabel4.setBounds(new Rectangle(0, 70, 75, 20));
jLabel5.setText("Friday");
jLabel5.setBounds(new Rectangle(0, 90, 65, 20));
jLabel6.setText("Saturday");
jLabel6.setBounds(new Rectangle(0, 110, 65, 20));
jLabel7.setText("Sunday");
jLabel7.setBounds(new Rectangle(0, 130, 65, 20));
jSlider1.setBounds(new Rectangle(115, 180, 290, 25));
jSlider1.addChangeListener(new BoundedChangeListener());
jLabel8.setText("Training workload");
jLabel8.setBounds(new Rectangle(10, 185, 100, 15));
jLabel9.setText("Notes :");
jLabel9.setBounds(new Rectangle(255, 5, 70, 15));
jScrollPane1.setBounds(new Rectangle(245, 25, 160, 130));
jTextArea1.setLineWrap(true);
jLabel10.setText("Select a training drill to view its description");
jLabel10.setBounds(new Rectangle(5, 10, 285, 25));
jScrollPane2.setBounds(new Rectangle(10, 45, 200, 205));
jList1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
jList1_mouseClicked(e);
}
public void mousePressed(MouseEvent e) {
jList1_mousePressed(e);
}
public void mouseReleased(MouseEvent e) {
jList1_mouseReleased(e);
}
});
jScrollPane3.setBounds(new Rectangle(225, 45, 185, 205));
jTextArea2.setEditable(false);
jPanel3.setBounds(new Rectangle(70, 5, 170, 155));
jPanel3.setLayout(xYLayout1);
jPanel3.add(choice7, new XYConstraints(5, 125, 165, 20));
jPanel3.add(choice6, new XYConstraints(5, 105, 165, 20));
jPanel3.add(choice1, new XYConstraints(5, 5, 165, 20));
jPanel3.add(choice3, new XYConstraints(5, 25, 165, 20));
jPanel3.add(choice4, new XYConstraints(5, 45, 165, 20));
jPanel3.add(choice2, new XYConstraints(5, 65, 165, 20));
jPanel3.add(choice5, new XYConstraints(5, 85, 165, 20));
this.initChoices();
jPanel1.add(jPanel3, null);
jScrollPane1.getViewport().add(jTextArea1, null);
jPanel1.add(jScrollPane1, null);
jPanel1.add(jLabel9, null);
jPanel1.add(jLabel8, null);
jPanel1.add(jSlider1, null);
jPanel1.add(jLabel7, null);
jPanel1.add(jLabel6, null);
jPanel1.add(jLabel5, null);
jPanel1.add(jLabel4, null);
jPanel1.add(jLabel3, null);
jPanel1.add(jLabel2, null);
jPanel1.add(jLabel1, null);
jTabbedPane1.addTab("Training Programme", jPanel1);
jScrollPane2.getViewport().add(jList1, null);
jScrollPane3.getViewport().add(jTextArea2, null);
jPanel2.add(jScrollPane3, null);
jPanel2.add(jScrollPane2, null);
jPanel2.add(jLabel10, null);
jTabbedPane1.addTab("Details", jPanel2);
this.getContentPane().add(jTabbedPane1, null);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
this_windowClosing(e);
}
});
}
void initChoices(){
for (String s : drills){
this.choice1.add(s);
this.choice2.add(s);
this.choice3.add(s);
this.choice4.add(s);
this.choice5.add(s);
this.choice6.add(s);
this.choice7.add(s);
}
}
private void jList1_mouseClicked(MouseEvent e) {
System.out.println("Click !!!");
jTextArea2.setText(explicatii.get(jList1.getSelectedIndex()));
}
private void jList1_mousePressed(MouseEvent e) {
f ++;
}
private void jList1_mouseReleased(MouseEvent e) {
f++;
if (f == 2) {
jTextArea2.setText(explicatii.get(jList1.getSelectedIndex()));
}
f = 0;
}
private void this_windowClosing(WindowEvent e) {
new ManagerHome();
}
class TrainingList extends AbstractListModel{
LinkedList<String> data = drills;
public TrainingList(){
}
@Override
public int getSize() {
return data.size();
}
@Override
public Object getElementAt(int index) {
return data.get(index);
}
}
class BoundedChangeListener implements ChangeListener{
@Override
public void stateChanged(javax.swing.event.ChangeEvent e) {
Object source = e.getSource();
if (source instanceof JSlider){
JSlider model = (JSlider) source ;
if (!model.getValueIsAdjusting()){
System.out.println("Changed : "+model.getValue());
trainingIntensity = model.getValue();
}
}
}
}
}
| Java |
package BackendSimulation;
public class Data {
public int zi;
public int luna;
public int an;
public String[] numeLuni = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
public int[] nrzile = {31,28,31,30,31,30,31,31,30,31,30,30};
public Data() {
super();
}
public Data(int zi,int luna,int an) {
this.zi = zi;
this.luna = luna;
this.an = an;
}
public String dateToString() {
return this.zi + " " + numeLuni[this.luna - 1] + " " + this.an;
}
public Data urmatoareaZi() {
if (zi == nrzile[luna-1])
{
if (luna == 12)
{zi = 1; luna = 1; an++;}
else
{
luna++;
zi = 1;
}
}
else
zi++;
return new Data(zi,luna,an);
}
public static int nrZileIntreDate(Data a,Data b) {
int rv=0;
boolean f = false;
while (f == false) {
if ((a.zi == b.zi) && (a.luna == b.luna) )
{f = true;}
else
{rv++;
a = a.urmatoareaZi();}
}
return rv-1;
}
// FOR DEBUG PURPOSES
public static void main(String args[]){
Data d1 = new Data(1,1,1111);
Data d2 = new Data(11,1,1111);
System.out.println(nrZileIntreDate(d1,d2));
}
}
| Java |
package BackendSimulation;
import java.security.SecureRandom;
import java.util.*;
import java.math.*;
import javax.xml.crypto.Data;
public class Brackets{
int numarAtleti;
String[] depthName = {"Serii","Saisprezecimi","Optimi","Sferturi","Semifinala","Finala","Castigator"};
static Random generator = new Random();
LinkedList<Atlet> allAthletes = new LinkedList<Atlet>();
int[] depthValues = {0,1,2,3,4,5};
int[] toStopAtDepth = {32,16,8,4,2,1,0};
public LinkedList<LinkedList<Atlet>> comp = new LinkedList<LinkedList<Atlet>>();
static int iterator = 0;
public Brackets(int uid){
for (Atlet a : staticData.atlet)
{
for (int i : staticData.competitii.get(uid).atletiInscrisi)
{
if (a.uniqueID == i)
{allAthletes.add(a);System.out.println("Added : "+a); }
}
}
numarAtleti = staticData.competitii.get(uid).nrAtleti[staticData.competitii.get(uid).clasa-1];
System.out.println("DebugData, nrAtleti = "+numarAtleti);
switch (numarAtleti) {
case 256: {
iterator = 0;
this.initialiseBracket();
allAthletes = this.avansareSerii();
this.initialiseBracket();
allAthletes = this.avansareSaisprezecimi();
this.initialiseBracket();
allAthletes = this.avansareOptimi();
this.initialiseBracket();
allAthletes = this.avansareSferturi();
this.initialiseBracket();
allAthletes = this.avansareSemifinale();
this.initialiseBracket();
numarAtleti = 1;
allAthletes = this.finala();
break;
}
case 128 :{
for (int i=0;i<32;i++) {comp.add(null);}
iterator = 1;
this.initialiseBracket();
allAthletes = this.avansareSaisprezecimi();
this.initialiseBracket();
allAthletes = this.avansareOptimi();
this.initialiseBracket();
allAthletes = this.avansareSferturi();
this.initialiseBracket();
allAthletes = this.avansareSemifinale();
this.initialiseBracket();
numarAtleti = 1;
allAthletes = this.finala();
break;
}
case 64 :{
for (int i=0;i<48;i++) {comp.add(null);}
iterator = 2;
this.initialiseBracket();
allAthletes = this.avansareOptimi();
this.initialiseBracket();
allAthletes = this.avansareSferturi();
this.initialiseBracket();
allAthletes = this.avansareSemifinale();
this.initialiseBracket();
numarAtleti = 1;
allAthletes = this.finala();
break;
}
case 32 :{
for (int i=0;i<56;i++) {comp.add(null);}
iterator = 3;
this.initialiseBracket();
allAthletes = this.avansareSferturi();
this.initialiseBracket();
allAthletes = this.avansareSemifinale();
this.initialiseBracket();
numarAtleti = 1;
allAthletes = this.finala();
break;
}
case 16 :{
for (int i=0;i<60;i++) {comp.add(null);}
iterator = 4;
this.initialiseBracket();
allAthletes = this.avansareSemifinale();
this.initialiseBracket();
numarAtleti = 1;
allAthletes = this.finala();
break;
}
case 8:{
for (int i=0;i<62;i++) {comp.add(null);}
iterator = 5;
this.initialiseBracket();
break;
}
}
//this.printData();
}
public void initialiseBracket()
{
if (this.numarAtleti == 1)
{comp.add(allAthletes);}
else
{
allAthletes = this.generateTimp(allAthletes);
iterator++;
for (int i=0;i<this.numarAtleti/8;i++)
{
comp.add(split());
}
}
numarAtleti /= 2;
}
public LinkedList<Atlet> split(){
LinkedList<Atlet> returnValue = new LinkedList<Atlet>();
if (this.allAthletes.isEmpty() == true) {return null;}
else
{
for (int j=0;j<8;j++)
{int i;
if (this.allAthletes.size() == 1) {i = 0;}
else {i = generator.nextInt(this.allAthletes.size() - 1);}
returnValue.add(allAthletes.get(i));
this.allAthletes.remove(i);
}
}
return returnValue;
}
public LinkedList<Atlet> avansareSerii()
{
LinkedList<Atlet> returnValue = new LinkedList<Atlet>();
for (int i=0;i<this.toStopAtDepth[0];i++)
{
for (Atlet x : comp.get(i))
{
returnValue.add(x);
}
}
returnValue = sortList(returnValue);
for (int i = 0;i<128;i++) {returnValue.removeLast();}
// for (Atlet i : returnValue) {i.competitionTime = 99.99f;}
return returnValue;
}
public LinkedList<Atlet> avansareSaisprezecimi()
{
LinkedList<Atlet> returnValue = new LinkedList<Atlet>();
for (int i = 32;i<48;i++)
{
comp.set(i, this.sortList(comp.get(i)));
}
for (int i = 32; i < 48;i++)
{
for (int j=0;j<4;j++)
{
returnValue.add(comp.get(i).get(j));
}
}
// returnValue = this.setDefaultTime(returnValue);
return returnValue;
}
public LinkedList<Atlet> avansareOptimi()
{
LinkedList<Atlet> returnValue = new LinkedList<Atlet>();
for (int i = 48;i<56;i++)
{
comp.set(i, this.sortList(comp.get(i)));
}
for (int i=48; i<56;i++)
{
for (int j=0;j<4;j++)
{
returnValue.add(comp.get(i).get(j));
}
}
// returnValue = this.setDefaultTime(returnValue);
return returnValue;
}
public LinkedList<Atlet> avansareSferturi()
{
LinkedList<Atlet> returnValue = new LinkedList<Atlet>();
for (int i = 56;i<60;i++)
{
comp.set(i, this.sortList(comp.get(i)));
}
for (int i=56; i<60;i++)
{
for (int j=0;j<4;j++)
{
returnValue.add(comp.get(i).get(j));
}
}
// returnValue = this.setDefaultTime(returnValue);
return returnValue;
}
public LinkedList<Atlet> avansareSemifinale()
{
LinkedList<Atlet> returnValue = new LinkedList<Atlet>();
for (int i = 60;i<62;i++)
{
comp.set(i, this.sortList(comp.get(i)));
}
for (int i=60; i<62;i++)
{
for (int j=0;j<4;j++)
{
returnValue.add(comp.get(i).get(j));
}
}
// returnValue = this.setDefaultTime(returnValue);
return returnValue;
}
public LinkedList<Atlet> finala()
{
LinkedList<Atlet> returnValue = new LinkedList<Atlet>();
int i = 62;
comp.set(i, this.sortList(comp.get(i)));
returnValue.add(comp.get(i).get(0));
returnValue.get(0).competitionTime[6] = returnValue.get(0).competitionTime[5];
return returnValue;
}
public void printData()
{int iter1 = 1,iter2 = 0;
for (LinkedList<Atlet> lista : comp)
{
{if (toStopAtDepth[iter2] == iter1-1) {iter2++; iter1 = 1;} }
System.out.println(depthName[iter2]+iter1);
for (Atlet i : lista)
{
System.out.print(i.firstName+": "+i.competitionTime[iter2]+"; ");
}
System.out.println();
iter1++;
}
}
public LinkedList<Atlet> sortList(LinkedList<Atlet> lista)
{
for (int i=0;i<lista.size()-1;i++)
for (int j=i+1;j<lista.size();j++)
if (lista.get(i).competitionTime[iterator-1] > lista.get(j).competitionTime[iterator-1])
{
Atlet aux = lista.get(i);
lista.set(i,lista.get(j));
lista.set(j, aux);
}
return lista;
}
public float round(float f)
{
String s = f+"";
String real,fract;
if (s.startsWith("1") == true)
{
if (s.length() == 4 || s.length() == 5) {return f;}
else{
real = s.substring(0, 2);
fract = s.substring(3,6);
}
}
else
{
if (s.length() == 3 || s.length() == 4) {return f;}
else {
real = s.substring(0,1);
fract = s.substring(2,5);
}
}
float r = Float.parseFloat(real);
float fr = Float.parseFloat(fract);
if (fr%10 >= 5f) {fr = fr + (10-fr%10);}
else {fr = fr - fr%10;}
return (float) (r + (float) (fr/1000) );
}
public LinkedList<Atlet> generateTimp(LinkedList<Atlet> toParse)
{
for (Atlet a : toParse)
{
generator.setSeed(System.nanoTime() * System.currentTimeMillis() * + generator.nextLong());
float phasePenalty = 0f;
float formaDeMoment = -0.15f;
formaDeMoment += (float) generator.nextInt(10)/100;
formaDeMoment += a.fitness/2000;
float speed = 8.6f;
int decider = generator.nextInt(3);
int concentrValue = (int) a.concentration;
System.out.println("ConcValue : "+concentrValue);
float bonus = generator.nextInt(20*concentrValue + 1)/100 ;
float plecare = (float) generator.nextInt(200)/10000;
boolean bonusSutime = generator.nextBoolean();
switch (iterator)
{
case 0: {phasePenalty = (float) (0.25 + (generator.nextInt(10)/100)) ; break;}
case 1: {phasePenalty = (float) (0.15 + (generator.nextInt(10)/100)) ; break;}
case 2: {phasePenalty = (float) (0.10 + (generator.nextInt(10)/100)) ; break;}
case 3: {phasePenalty = (float) (0.10 + (generator.nextInt(5)/100)) ; break;}
case 4: {phasePenalty = (float) (generator.nextInt(10)/100) ; break;}
case 5: {break;}
}
switch (decider)
{
case 0 : {break;}
case 1 : {speed += 0.00854152f * bonus; break;}
case 2 : {speed += 0.00640614f * bonus; break;}
case 3 : {speed += 0.00640614f * bonus; break;}
}
speed += 0.00854152 * a.acceleration;
speed += 0.00640614f * a.speed;
speed += 0.00640614f * a.pace;
speed += (-1 + 0.01*a.fitness);
float timp = (float) 100/speed ;
timp += 0.655f - 0.0053*a.reaction;
timp += plecare;
timp += phasePenalty;
timp += formaDeMoment;
if (bonusSutime) {timp -= 0.01;}
staticData.atlet.get(a.uniqueID).competitionTime[iterator] = this.round(timp);
}
return toParse;
}
} | Java |
package BackendSimulation;
import ImportsAndExports.*;
import java.util.LinkedList;
public class staticData {
public static int competitionCount = 0;
public static LinkedList<Integer> passedComp = new LinkedList<Integer>();
public static LinkedList<Atlet> atlet = new LinkedList<Atlet>();
public static LinkedList<Competition> competitii = new LinkedList<Competition>();
public static LinkedList<Manager> managers = new LinkedList<Manager>();
public static Atlet player = new Atlet();
public static Data dataCurenta = new Data(1,1,2011);
public static float recordMondial = 9.56f;
public static String detinatorRecordMondial = "Usain Bolt, Jamaica";
public static Data dataStabiliriiWR = new Data(1,1,2011);
public static String loculStabiliriiWR = "";
public staticData(int i) {
super();
this.passedComp.clear();
}
public staticData() {
super();
this.athleteImport();
this.competitionsImport();
this.managersImport();
}
void athleteImport() {
this.atlet = dbImporting.parseAtletImport();
for (int i=0;i<this.atlet.size();i++)
atlet.get(i).age = this.dataCurenta.an - atlet.get(i).dataNasterii.an;
}
void competitionsImport(){
this.competitii = dbImporting.parseCompetitionImport();
}
public static void setNewWR(float f,Atlet a,Competition comp) {
recordMondial = f;
detinatorRecordMondial = a.firstName + " " + a.lastName + ", " + a.nationality;
dataStabiliriiWR = dataCurenta;
loculStabiliriiWR = comp.numeleConcursului+", "+comp.orasulConcursului;
}
void managersImport(){
managers = dbImporting.parseManagerImport();
for (int i=0;i<this.managers.size();i++)
managers.get(i).age = this.dataCurenta.an - managers.get(i).dataNasterii.an;
}
}
| Java |
package BackendSimulation;
import java.util.LinkedList;
import java.util.Random;
public class AttributesCheck {
static LinkedList<Integer> diff = new LinkedList<Integer>();
static Random generator = new Random();
public AttributesCheck() {
super();
}
public static void updateDaily(){
for (Atlet a : staticData.atlet) {
a.acceleration += 0.03;
a.speed += 0.03;
a.pace += 0.03;
a.reaction += 0.03;
a.concentration += 0.03;
a.currentAbility += 0.03;
}
}
public static void setNewCA(){
int iter = 0;
for (Atlet a : staticData.atlet) {
diff.add(generator.nextInt(17));
if (a.currentAbility + diff.get(iter) < a.potentialAbility)
a.currentAbility += diff.get(iter);
else
a.currentAbility = a.potentialAbility;
}
}
public static void updateMonthly(){
float aux = 0f;
int iter = 0;
setNewCA();
for (Atlet a : staticData.atlet) {
if (a.currentAbility != a.potentialAbility) {
aux = generator.nextInt(10)/10;
if ((a.acceleration + aux) > (a.currentAbility/10))
a.acceleration = a.currentAbility/10;
else
a.acceleration += aux;
aux = generator.nextInt(10)/10;
if ((a.speed + aux) > (a.currentAbility/10))
a.speed = a.currentAbility/10;
else
a.speed += aux;
aux = generator.nextInt(10)/10;
if ((a.pace + aux) > (a.currentAbility/10))
a.pace = a.currentAbility/10;
else
a.pace += aux;
aux = generator.nextInt(10)/10;
if ((a.reaction + aux) > (a.currentAbility/10))
a.reaction = a.currentAbility/10;
else
a.reaction += aux;
aux = generator.nextInt(10)/10;
if ((a.concentration + aux) > (a.currentAbility/10))
a.concentration = a.currentAbility/10;
else
a.concentration += aux;
iter ++ ;
}
else {
aux = generator.nextInt(10)/10;
if ((a.acceleration + aux) > (a.currentAbility/10))
a.acceleration = a.currentAbility/10;
else
a.acceleration += aux;
aux = generator.nextInt(10)/10;
if ((a.speed + aux) > (a.currentAbility/10))
a.speed = a.currentAbility/10;
else
a.speed += aux;
aux = generator.nextInt(10)/10;
if ((a.pace + aux) > (a.currentAbility/10))
a.pace = a.currentAbility/10;
else
a.pace += aux;
aux = generator.nextInt(10)/10;
if ((a.reaction + aux) > (a.currentAbility/10))
a.reaction = a.currentAbility/10;
else
a.reaction += aux;
aux = generator.nextInt(10)/10;
if ((a.concentration + aux) > (a.currentAbility/10))
a.concentration = a.currentAbility/10;
else
a.concentration += aux;
}
}
}
}
| Java |
package BackendSimulation;
/*
* The backend simulation page
*
*/ | Java |
package BackendSimulation;
import java.util.LinkedList;
public class Competition {
public int uniqueID;
public int clasa;
public String[] numeClasa = {"Olympic Games","World Championships","Diamond League","World Athletics Series","Meeting"};
public int[] nrAtleti = {256,256,128,64,32};
public Data dataConcursului;
public String numeleConcursului;
public String orasulConcursului;
public String taraConcursului;
public float record;
public Data dataRecordului;
public String numeDetinator;
public LinkedList<Integer> atletiInscrisi = new LinkedList<Integer>();
public LinkedList<LinkedList<Atlet>> rezultate ;
public LinkedList<LinkedList<Atlet>> istoric ;
public Competition(LinkedList<String> aux) {
this.uniqueID = Integer.valueOf(aux.get(0));
this.clasa = Integer.valueOf(aux.get(1));
this.dataConcursului = new Data(Integer.valueOf(aux.get(2)),Integer.valueOf(aux.get(3)),Integer.valueOf(aux.get(4)));
this.numeleConcursului = aux.get(5);
this.orasulConcursului = aux.get(6);
this.taraConcursului = aux.get(7);
this.record = Float.valueOf(aux.get(8));
this.dataRecordului = new Data(Integer.valueOf(aux.get(9)),Integer.valueOf(aux.get(10)),Integer.valueOf(aux.get(11)));
this.numeDetinator = aux.get(12);
if (aux.get(13).contains("null")) {
atletiInscrisi = null;
}
else
{
String[] s = aux.get(13).split(" ");
for (String substr : s){
atletiInscrisi.add(Integer.valueOf(substr));
}
}
}
public Competition() {
super();
}
public void setNewRecord(Atlet ath,float time,Data data) {
this.record = time;
this.dataRecordului = data;
this.numeDetinator = ath.firstName + " " + ath.lastName;
}
}
| Java |
package BackendSimulation;
import java.util.LinkedList;
public class Atlet {
public int uniqueID;
public float acceleration;
public float speed;
public float pace;
public float reaction;
public float concentration;
public float fitness;
public float morale;
public float currentAbility;
public float potentialAbility;
public String firstName;
public String lastName;
public String nationality;
public Data dataNasterii;
public int age;
public float personalBest;
public float seasonBest;
public Data personalBestDate;
public String personalBestLocation;
public Data seasonBestDate;
public String seasonBestLocation;
public Data dataFinalaContract;
public int idManager;
public float[] competitionTime = new float[7];
public LinkedList<Float> history = new LinkedList<Float>();
public Atlet(LinkedList<String> info) {
this.uniqueID = Integer.valueOf(info.get(0));
this.acceleration = Float.valueOf(info.get(1));
this.speed = Float.valueOf(info.get(2));
this.pace = Float.valueOf(info.get(3));
this.reaction = Float.valueOf(info.get(4));
this.concentration = Float.valueOf(info.get(5));
this.fitness = Float.valueOf(info.get(6));
this.morale = Float.valueOf(info.get(7));
this.currentAbility = Float.valueOf(info.get(8));
this.potentialAbility = Float.valueOf(info.get(9));
this.firstName = info.get(10);
this.lastName = info.get(11);
this.nationality = info.get(12);
this.dataNasterii = new Data(Integer.valueOf(info.get(13)),Integer.valueOf(info.get(14)),Integer.valueOf(info.get(15)));
this.personalBest = Float.valueOf(info.get(16));
this.personalBestDate = new Data(Integer.valueOf(info.get(17)),Integer.valueOf(info.get(18)),Integer.valueOf(info.get(19)));
this.personalBestLocation = info.get(20);
this.seasonBest = Float.valueOf(info.get(21));
this.seasonBestDate = new Data(Integer.valueOf(info.get(22)),Integer.valueOf(info.get(23)),Integer.valueOf(info.get(24)));
this.seasonBestLocation = info.get(25);
if (info.get(26).contains("null") == false)
{
String[] s = info.get(26).split(" ");
for (String str : s) {
float aux = Float.valueOf(str);
this.history.add(aux);
}
}
}
public Atlet() {
super();
}
public void setNewPersonalBest(float time,Competition comp){
this.personalBest = time;
this.personalBestDate = comp.dataConcursului;
this.personalBestLocation = comp.numeleConcursului + ", " + comp.orasulConcursului + ", " + comp.taraConcursului;
}
public void setNewSeasonBest(float time,Competition comp){
this.seasonBest = time;
this.seasonBestDate = comp.dataConcursului;
this.seasonBestLocation = comp.numeleConcursului + ", " + comp.orasulConcursului + ", " + comp.taraConcursului;
}
public void addResultsToHistory(){
for (int i=0;i<7;i++)
if (this.competitionTime[i] != 0f)
{history.add(this.competitionTime[i]);System.out.println("Timp : "+this.competitionTime[i]); }
}
}
| Java |
package BackendSimulation;
import java.util.LinkedList;
public class Manager {
public int uniqueID;
public String firstName;
public String lastName;
public String nationalitate;
public Data dataNasterii;
public int age;
public LinkedList<Integer> idAtletiSubContract = new LinkedList<Integer>();
public float training;
public float business;
public float knowledge;
public float renume;
public float ability;
public Manager(LinkedList<String> aux) {
this.uniqueID = Integer.valueOf(aux.get(0));
this.firstName = aux.get(1);
this.lastName = aux.get(2);
this.nationalitate = aux.get(3);
this.dataNasterii = new Data(Integer.valueOf(aux.get(4)),Integer.valueOf(aux.get(5)),Integer.valueOf(aux.get(6)));
this.training = Float.valueOf(aux.get(7));
this.business = Float.valueOf(aux.get(8));
this.knowledge = Float.valueOf(aux.get(9));
this.renume = Float.valueOf(aux.get(10));
this.ability = Float.valueOf(aux.get(11));
if (aux.get(12).contains("null")) {
this.idAtletiSubContract = null;
}
else
{
String[] s = aux.get(12).split(" ");
for (int i=0;i<s.length;i++)
this.idAtletiSubContract.add(Integer.valueOf(s[i]));
}
}
public Manager() {
super();
}
}
| Java |
package Main;
import GUI.*;
public class Main {
public Main() {
}
public static void main(String args[]){
new GUI.Main();
}
}
| Java |
package com.busi.system.manager;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import com.busi.framework.base.BaseManager;
import com.busi.system.model.SystemPermission;
public class SystemPermissionManager extends BaseManager{
}
| Java |
package com.busi.system.dao;
import com.busi.framework.base.BaseDao;
import com.busi.system.model.SystemPermission;
public class SystemPermissionDao extends BaseDao{
public Class getEntityClass(){
return SystemPermission.class;
}
}
| Java |
package com.busi.framework.exception;
public class CheckKeyWordException extends Exception {
private static final long serialVersionUID = 1L;
public CheckKeyWordException() {
super();
}
public CheckKeyWordException(String message, Throwable arg1) {
super(message, arg1);
}
public CheckKeyWordException(String message) {
super(message);
}
public CheckKeyWordException(Throwable message) {
super(message);
}
}
| Java |
package com.busi.framework.base.db;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionPool {
public static Connection getConnPool(){
Connection con = null;
try{
Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
con = DriverManager.getConnection("proxool.dbname");
}catch(Exception e){
//con = JdbcConnection.getInstance1();
e.printStackTrace();
}
return con;
}
public static void main(String[] args){
ConnectionPool.getConnPool();
}
}
| Java |
package com.busi.framework.base.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.logicalcobwebs.proxool.configuration.PropertyConfigurator;
import com.busi.framework.base.CC;
import com.busi.system.password.PasswordUtil;
public class JdbcConnection {
private static Connection con = null;
public static Connection getInstance1(){
if(con == null){
con = getConnection();
}
return con;
}
private static Connection getConnection(){
Map map = parseDbXml();
//String url = "jdbc:oracle:thin:@192.168.0.94:1521:orcl";
//String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
String url = PasswordUtil.getInstance().decryption((String)map.get("driver-url"));
String username = PasswordUtil.getInstance().decryption((String)map.get("user"));
String password = PasswordUtil.getInstance().decryption((String)map.get("password"));
try{
Class.forName((String)map.get("driver-class"));
con = DriverManager.getConnection(url , username , password);
}catch(Exception e){
e.printStackTrace();
}
return con;
}
private static Map parseDbXml(){
Map map = new HashMap();
String xmlPath = CC.REAL_PATH + "/WEB-INF/proxool.xml";
//String xmlPath = "E:\\hhdc\\hdjs\\web\\WebContent\\WEB-INF\\proxool.xml";
SAXBuilder builder = new SAXBuilder(false);
try{
Document doc = builder.build(xmlPath);
Element root= doc.getRootElement();
List listProxool = root.getChildren("proxool");
Element proxool = (Element)listProxool.get(0);
map.put("driver-url", proxool.getChildText("driver-url"));
map.put("driver-class", proxool.getChildText("driver-class"));
Element driverProp = proxool.getChild("driver-properties");
List listProp = driverProp.getChildren();
for(int i = 0 ; i < listProp.size() ; i ++ ){
Element prop = (Element)listProp.get(i);
String attributeValue = prop.getAttributeValue("name");
if(attributeValue.equals("user")){
map.put("user", prop.getAttributeValue("value"));
}
if(attributeValue.equals("password")){
map.put("password", prop.getAttributeValue("value"));
}
}
}catch(Exception e){
e.printStackTrace();
}
return map;
}
}
| Java |
package com.busi.framework.base;
public interface Model {
public String getLogField();
}
| Java |
package com.busi.framework.base;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class HttpSessionTread {
private static ThreadLocal tread = new ThreadLocal() {
protected synchronized Object initialValue() {
return new HttpSessionTread();
}
};
public static HttpSessionTread get() {
return (HttpSessionTread) tread.get();
}
private HttpServletRequest httpServletRequest;
private String loginUserName;
public String getLoginUserName() {
return loginUserName;
}
public void setLoginUserName(String loginUserName) {
this.loginUserName = loginUserName;
}
public HttpServletRequest getHttpServletRequest() {
return httpServletRequest;
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
}
| Java |
package com.busi.framework.base;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.busi.system.dao.SystemDeptDao;
import com.busi.system.dao.SystemMenuDao;
import com.busi.system.dao.SystemMenuOperationDao;
import com.busi.system.dao.SystemPermissionDao;
import com.busi.system.dao.SystemUserDao;
public class BaseManager{
protected final Log log = LogFactory.getLog(getClass());
public BaseDao baseDao;
public SystemUserDao systemUserDao;
public SystemMenuDao systemMenuDao;
public SystemDeptDao systemDeptDao;
public SystemMenuOperationDao systemOperationDao;
public SystemPermissionDao systemPermissionDao;
public SystemMenuDao getSystemMenuDao() {
return systemMenuDao;
}
public void setSystemMenuDao(SystemMenuDao systemMenuDao) {
this.systemMenuDao = systemMenuDao;
}
public SystemUserDao getSystemUserDao() {
return systemUserDao;
}
public void setSystemUserDao(SystemUserDao systemUserDao) {
this.systemUserDao = systemUserDao;
}
public BaseDao getBaseDao() {
return baseDao;
}
public void setBaseDao(BaseDao baseDao) {
this.baseDao = baseDao;
}
public SystemDeptDao getSystemDeptDao() {
return systemDeptDao;
}
public void setSystemDeptDao(SystemDeptDao systemDeptDao) {
this.systemDeptDao = systemDeptDao;
}
public SystemMenuOperationDao getSystemOperationDao() {
return systemOperationDao;
}
public void setSystemOperationDao(SystemMenuOperationDao systemOperationDao) {
this.systemOperationDao = systemOperationDao;
}
public SystemPermissionDao getSystemPermissionDao() {
return systemPermissionDao;
}
public void setSystemPermissionDao(SystemPermissionDao systemPermissionDao) {
this.systemPermissionDao = systemPermissionDao;
}
}
| Java |
package com.busi.framework.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.busi.framework.base.CC;
import com.busi.framework.base.HttpSessionTread;
import com.busi.framework.exception.CheckKeyWordException;
public class DispatchActionTread extends DispatchAction{
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response){
ActionForward af = null;
try{
String loginName = (String)request.getSession().getAttribute(CC.COMMON_LOGIN_NAME);
HttpSessionTread.get().setLoginUserName(loginName);
HttpSessionTread.get().setHttpServletRequest(request);
af = super.execute(mapping, form, request, response);
}catch(CheckKeyWordException kwe){
String loginUrl = CC.CTX + "/index.do?method=toInputErrorKey";
af = new ActionForward(loginUrl);
af.setRedirect(true);
}catch(Exception ne){
ne.printStackTrace();
//String loginUrl = CC.CTX + "/index.do?method=login";
//af = new ActionForward(loginUrl);
//af.setRedirect(true);
}
return af;
}
}
| Java |
package com.busi.framework.action;
import java.util.HashMap;
import java.util.Map;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.busi.utils.tools.StringTools;
public class ParameterActionForward extends ActionMapping{
private ActionForward forward = null;
private Map map = new HashMap();
public void setParam(String key , String value){
map.put(key, value);
}
public ParameterActionForward(ActionForward forward){
this.forward = forward;
}
public ActionForward findForwardParam(){
return replaceParamInPath(forward , map);
}
private ActionForward replaceParamInPath(ActionForward forward , Map map){
String path = StringTools.setParameters(forward.getPath() , map);
ActionForward newForward = new ActionForward();
newForward.setPath(path);
newForward.setRedirect(forward.getRedirect());
return newForward;
}
}
| Java |
package com.busi.relevance;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
public class RelevanceXml extends HttpServlet {
private final String xmlPath = "/WEB-INF/RelevanceConfig/relev_cfg.xml";
private static Element rootEle;
private static RelevanceXml relevanceXml;
public static RelevanceXml getInstance(){
if(relevanceXml == null){
relevanceXml = new RelevanceXml();
}
return relevanceXml;
}
ServletConfig config;
public ServletConfig getConfig() {
return config;
}
public void setConfig(ServletConfig config) {
this.config = config;
}
public void init(ServletConfig conf)throws ServletException{
this.config=conf;
String strXmlPath = conf.getServletContext().getRealPath("/") + xmlPath;
SAXBuilder sax = new SAXBuilder();
try{
Document doc = sax.build(strXmlPath);
RelevanceXml.getInstance().rootEle = doc.getRootElement();
}catch(Exception e){
e.printStackTrace();
}
}
public List getSqlListByName(String name){
List list = new ArrayList();
try{
List<Element> listEle = RelevanceXml.getInstance().rootEle.getChildren();
for(Element e : listEle){
if(e.getAttribute("name").getValue().equals(name)){
List<Element> listSql = e.getChildren("hql");
for(Element esql : listSql){
list.add(esql.getTextTrim());
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
public static void main(String[] args) throws Exception{
RelevanceXml x = RelevanceXml.getInstance();
String path = "E:\\xf\\xfweb\\web\\xfweb\\WebContent\\WEB-INF\\RelevanceConfig\\relev_cfg.xml";
SAXBuilder sax = new SAXBuilder();
Document doc = sax.build(path);
x.rootEle = doc.getRootElement();
x.getSqlListByName("templetId");
}
}
| Java |
package com.duying.gdc;
import com.busi.framework.action.BaseAction;
import com.duying.gdc.manager.GdMcCompareManager;
import com.duying.gdc.manager.GdMcImportManager;
import com.duying.gdc.manager.GdMcPersonManager;
public class GdBaseAction extends BaseAction{
public GdMcImportManager gdMcImportManager;
public GdMcPersonManager gdMcPersonManager;
public GdMcCompareManager gdMcCompareManager;
public GdMcPersonManager getGdMcPersonManager() {
return gdMcPersonManager;
}
public GdMcCompareManager getGdMcCompareManager() {
return gdMcCompareManager;
}
public void setGdMcCompareManager(GdMcCompareManager gdMcCompareManager) {
this.gdMcCompareManager = gdMcCompareManager;
}
public void setGdMcPersonManager(GdMcPersonManager gdMcPersonManager) {
this.gdMcPersonManager = gdMcPersonManager;
}
public GdMcImportManager getGdMcImportManager() {
return gdMcImportManager;
}
public void setGdMcImportManager(GdMcImportManager gdMcImportManager) {
this.gdMcImportManager = gdMcImportManager;
}
}
| Java |
package com.duying.gdc.manager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts.upload.FormFile;
import com.busi.framework.base.PageSupport;
import com.busi.utils.tools.DateTools;
import com.busi.utils.tools.StringTools;
import com.duying.gdc.GdBaseManager;
import com.duying.gdc.action.form.GdMcImportForm;
import com.duying.gdc.model.GdMcImport;
import com.duying.gdc.model.GdMcPerson;
public class GdMcImportManager extends GdBaseManager{
public PageSupport getPage(Map map){
return this.gdMcImportDao.getPage(map);
}
public GdMcImport getObjByDate(Date adate){
String hql = "from GdMcImport gmi where gmi.import_date =:import_date";
Map map = new HashMap();
map.put("import_date", adate);
Object obj = this.baseDao.getUniqueBy(hql, map);
if(obj == null){
return null;
}else{
return (GdMcImport)obj;
}
}
public void saveToDb(GdMcImportForm gmiForm){
GdMcImport gmi = new GdMcImport();
gmi.setImport_date(DateTools.stringToDate(gmiForm.getStr_import_date(), DateTools.FULL_YM));
gmi.setGd_number(gmiForm.getGd_number());
gmi.setJg_number(gmiForm.getJg_number());
gmi.setJg_gp_number(gmiForm.getJg_gp_number());
this.baseDao.saveOrUpdateLog(gmi);
Integer totalCgsl = 0;
try{
FormFile ff = gmiForm.getFormFile();
InputStreamReader isr = new InputStreamReader(ff.getInputStream());
BufferedReader br = new BufferedReader(isr);
String aline = br.readLine();
String[] cellValue;
while(aline != null){
cellValue = aline.split(",");
GdMcPerson gmp = new GdMcPerson();
gmp.setXh(StringTools.formatStr2Int(cellValue[0]));
gmp.setZqzh(cellValue[1]);
gmp.setGdmc(cellValue[2]);
gmp.setZjhm(cellValue[3]);
Integer cgsl = StringTools.formatStr2Int(cellValue[4]);
totalCgsl += cgsl;
gmp.setCgsl(cgsl);
gmp.setCgbl(cellValue[5]);
gmp.setGdMcImport(gmi);
this.baseDao.saveOrUpdateLog(gmp);
aline = br.readLine();
}
}catch(Exception e){
e.printStackTrace();
}
gmi.setGp_number(totalCgsl);
this.baseDao.saveOrUpdateLog(gmi);
}
public List getLastThirteenImport(Date import_date){
String hql = "from GdMcImport gmi where gmi.import_date <=:import_date order by gmi.import_date desc";
Map map = new HashMap();
map.put("import_date", import_date);
return this.baseDao.findPageByHql(hql, 13, 1, map).getItems();
}
}
| Java |
package com.duying.gdc.manager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.duying.gdc.GdBaseManager;
public class GdMcPersonManager extends GdBaseManager{
public List getByImportIdOrderByXH(Integer importId){
String hql = "from GdMcPerson gmp where gmp.gdMcImport.id =:importId order by gmp.xh asc";
Map map = new HashMap();
map.put("importId", importId);
List list = this.baseDao.getByHQL(hql, map);
return list;
}
public List getByImportIdOrderByZQZH(Integer importId){
String hql = "from GdMcPerson gmp where gmp.gdMcImport.id =:importId order by gmp.zqzh asc";
Map map = new HashMap();
map.put("importId", importId);
List list = this.baseDao.getByHQL(hql, map);
return list;
}
}
| Java |
package com.duying.gdc.dao;
import java.util.Map;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import com.busi.framework.base.BaseDao;
import com.busi.framework.base.CC;
import com.busi.framework.base.PageSupport;
import com.busi.utils.tools.NumberTools;
import com.duying.gdc.model.GdMcImport;
public class GdMcImportDao extends BaseDao{
public Class getEntityClass(){
return GdMcImport.class;
}
public PageSupport getPage(Map map){
DetachedCriteria dc = DetachedCriteria.forClass(getEntityClass());
int pageSize = 0;
int pageNo = 1;
if(map != null){
Object objPageSize = map.get("pageSize");
if(objPageSize != null){
pageSize = NumberTools.formatObject2IntDefaultZeroNoExp(objPageSize);
}else{
pageSize = CC.PAGE_SIZE;
}
Object objPageNo = map.get("pageNo");
if(objPageNo != null){
pageNo = NumberTools.formatObject2IntDefaultZeroNoExp(objPageNo);
}else{
pageNo = 1;
}
}
dc.addOrder(Order.desc("import_date"));
return findPageByCriteria(dc , pageSize , pageNo);
}
}
| Java |
package com.duying.gdc;
import com.busi.framework.base.BaseManager;
import com.duying.gdc.dao.GdMcImportDao;
public class GdBaseManager extends BaseManager{
public GdMcImportDao gdMcImportDao;
public GdMcImportDao getGdMcImportDao() {
return gdMcImportDao;
}
public void setGdMcImportDao(GdMcImportDao gdMcImportDao) {
this.gdMcImportDao = gdMcImportDao;
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.ObjectParser;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Abstract thread-safe Google client.
*
* @since 1.12
* @author Yaniv Inbar
*/
public abstract class AbstractGoogleClient {
static final Logger LOGGER = Logger.getLogger(AbstractGoogleClient.class.getName());
/** The request factory for connections to the server. */
private final HttpRequestFactory requestFactory;
/**
* Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for
* none.
*/
private final GoogleClientRequestInitializer googleClientRequestInitializer;
/**
* Root URL of the service, for example {@code "https://www.googleapis.com/"}. Must be URL-encoded
* and must end with a "/".
*/
private final String rootUrl;
/**
* Service path, for example {@code "tasks/v1/"}. Must be URL-encoded and must end with a "/".
*/
private final String servicePath;
/**
* Application name to be sent in the User-Agent header of each request or {@code null} for none.
*/
private final String applicationName;
/** Object parser or {@code null} for none. */
private final ObjectParser objectParser;
/** Whether discovery pattern checks should be suppressed on required parameters. */
private boolean suppressPatternChecks;
/**
* Constructor with required parameters.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param objectParser object parser
*/
protected AbstractGoogleClient(HttpTransport transport,
HttpRequestInitializer httpRequestInitializer, String rootUrl, String servicePath,
ObjectParser objectParser) {
this(transport, httpRequestInitializer, rootUrl, servicePath, objectParser, null, null, false);
}
/**
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param objectParser object parser or {@code null} for none
* @param googleClientRequestInitializer Google request initializer or {@code null} for none
* @param applicationName application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @param suppressPatternChecks whether discovery pattern checks should be suppressed on required
* parameters
*/
protected AbstractGoogleClient(HttpTransport transport,
HttpRequestInitializer httpRequestInitializer, String rootUrl, String servicePath,
ObjectParser objectParser, GoogleClientRequestInitializer googleClientRequestInitializer,
String applicationName, boolean suppressPatternChecks) {
this.googleClientRequestInitializer = googleClientRequestInitializer;
this.rootUrl = normalizeRootUrl(rootUrl);
this.servicePath = normalizeServicePath(servicePath);
if (Strings.isNullOrEmpty(applicationName)) {
LOGGER.warning("Application name is not set. Call Builder#setApplicationName.");
}
this.applicationName = applicationName;
this.requestFactory = httpRequestInitializer == null
? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer);
this.objectParser = objectParser;
this.suppressPatternChecks = suppressPatternChecks;
}
/**
* Returns the URL-encoded root URL of the service, for example
* {@code "https://www.googleapis.com/"}.
*
* <p>
* Must end with a "/".
* </p>
*/
public final String getRootUrl() {
return rootUrl;
}
/**
* Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}.
*
* <p>
* Must end with a "/" and not begin with a "/". It is allowed to be an empty string {@code ""} or
* a forward slash {@code "/"}, if it is a forward slash then it is treated as an empty string
* </p>
*/
public final String getServicePath() {
return servicePath;
}
/**
* Returns the URL-encoded base URL of the service, for example
* {@code "https://www.googleapis.com/tasks/v1/"}.
*
* <p>
* Must end with a "/". It is guaranteed to be equal to {@code getRootUrl() + getServicePath()}.
* </p>
*/
public final String getBaseUrl() {
return rootUrl + servicePath;
}
/**
* Returns the application name to be sent in the User-Agent header of each request or
* {@code null} for none.
*/
public final String getApplicationName() {
return applicationName;
}
/** Returns the HTTP request factory. */
public final HttpRequestFactory getRequestFactory() {
return requestFactory;
}
/** Returns the Google client request initializer or {@code null} for none. */
public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() {
return googleClientRequestInitializer;
}
/**
* Returns the object parser or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public ObjectParser getObjectParser() {
return objectParser;
}
/**
* Initializes a {@link AbstractGoogleClientRequest} using a
* {@link GoogleClientRequestInitializer}.
*
* <p>
* Must be called before the Google client request is executed, preferably right after the request
* is instantiated. Sample usage:
* </p>
*
* <pre>
public class Get extends HttpClientRequest {
...
}
public Get get(String userId) throws IOException {
Get result = new Get(userId);
initialize(result);
return result;
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @param httpClientRequest Google client request type
*/
protected void initialize(AbstractGoogleClientRequest<?> httpClientRequest) throws IOException {
if (getGoogleClientRequestInitializer() != null) {
getGoogleClientRequestInitializer().initialize(httpClientRequest);
}
}
/**
* Create an {@link BatchRequest} object from this Google API client instance.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
client.batch()
.queue(...)
.queue(...)
.execute();
* </pre>
*
* @return newly created Batch request
*/
public final BatchRequest batch() {
return batch(null);
}
/**
* Create an {@link BatchRequest} object from this Google API client instance.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
client.batch(httpRequestInitializer)
.queue(...)
.queue(...)
.execute();
* </pre>
*
* @param httpRequestInitializer The initializer to use when creating the top-level batch HTTP
* request or {@code null} for none
* @return newly created Batch request
*/
public final BatchRequest batch(HttpRequestInitializer httpRequestInitializer) {
BatchRequest batch =
new BatchRequest(getRequestFactory().getTransport(), httpRequestInitializer);
batch.setBatchUrl(new GenericUrl(getRootUrl() + "batch"));
return batch;
}
/** Returns whether discovery pattern checks should be suppressed on required parameters. */
public final boolean getSuppressPatternChecks() {
return suppressPatternChecks;
}
/** If the specified root URL does not end with a "/" then a "/" is added to the end. */
static String normalizeRootUrl(String rootUrl) {
Preconditions.checkNotNull(rootUrl, "root URL cannot be null.");
if (!rootUrl.endsWith("/")) {
rootUrl += "/";
}
return rootUrl;
}
/**
* If the specified service path does not end with a "/" then a "/" is added to the end. If the
* specified service path begins with a "/" then the "/" is removed.
*/
static String normalizeServicePath(String servicePath) {
Preconditions.checkNotNull(servicePath, "service path cannot be null");
if (servicePath.length() == 1) {
Preconditions.checkArgument(
"/".equals(servicePath), "service path must equal \"/\" if it is of length 1.");
servicePath = "";
} else if (servicePath.length() > 0) {
if (!servicePath.endsWith("/")) {
servicePath += "/";
}
if (servicePath.startsWith("/")) {
servicePath = servicePath.substring(1);
}
}
return servicePath;
}
/**
* Builder for {@link AbstractGoogleClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
public abstract static class Builder {
/** HTTP transport. */
private final HttpTransport transport;
/**
* Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for
* none.
*/
private GoogleClientRequestInitializer googleClientRequestInitializer;
/** HTTP request initializer or {@code null} for none. */
private HttpRequestInitializer httpRequestInitializer;
/** Object parser to use for parsing responses. */
private final ObjectParser objectParser;
/** The root URL of the service, for example {@code "https://www.googleapis.com/"}. */
private String rootUrl;
/** The service path of the service, for example {@code "tasks/v1/"}. */
private String servicePath;
/**
* Application name to be sent in the User-Agent header of each request or {@code null} for
* none.
*/
private String applicationName;
/** Whether discovery pattern checks should be suppressed on required parameters. */
private boolean suppressPatternChecks;
/**
* Returns an instance of a new builder.
*
* @param transport The transport to use for requests
* @param rootUrl root URL of the service. Must end with a "/"
* @param servicePath service path
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
*/
protected Builder(HttpTransport transport, String rootUrl, String servicePath,
ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) {
this.transport = Preconditions.checkNotNull(transport);
this.objectParser = Preconditions.checkNotNull(objectParser);
setRootUrl(rootUrl);
setServicePath(servicePath);
this.httpRequestInitializer = httpRequestInitializer;
}
/** Builds a new instance of {@link AbstractGoogleClient}. */
public abstract AbstractGoogleClient build();
/** Returns the HTTP transport. */
public final HttpTransport getTransport() {
return transport;
}
/**
* Returns the object parser used or {@code null} if not specified. *
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public ObjectParser getObjectParser() {
return objectParser;
}
/**
* Returns the URL-encoded root URL of the service, for example
* {@code https://www.googleapis.com/}.
*
* <p>
* Must be URL-encoded and must end with a "/".
* </p>
*/
public final String getRootUrl() {
return rootUrl;
}
/**
* Sets the URL-encoded root URL of the service, for example {@code https://www.googleapis.com/}
* .
* <p>
* If the specified root URL does not end with a "/" then a "/" is added to the end.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setRootUrl(String rootUrl) {
this.rootUrl = normalizeRootUrl(rootUrl);
return this;
}
/**
* Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}.
*
* <p>
* Must be URL-encoded and must end with a "/" and not begin with a "/". It is allowed to be an
* empty string {@code ""}.
* </p>
*/
public final String getServicePath() {
return servicePath;
}
/**
* Sets the URL-encoded service path of the service, for example {@code "tasks/v1/"}.
*
* <p>
* It is allowed to be an empty string {@code ""} or a forward slash {@code "/"}, if it is a
* forward slash then it is treated as an empty string. This is determined when the library is
* generated and normally should not be changed.
* </p>
*
* <p>
* If the specified service path does not end with a "/" then a "/" is added to the end. If the
* specified service path begins with a "/" then the "/" is removed.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setServicePath(String servicePath) {
this.servicePath = normalizeServicePath(servicePath);
return this;
}
/** Returns the Google client request initializer or {@code null} for none. */
public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() {
return googleClientRequestInitializer;
}
/**
* Sets the Google client request initializer or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setGoogleClientRequestInitializer(
GoogleClientRequestInitializer googleClientRequestInitializer) {
this.googleClientRequestInitializer = googleClientRequestInitializer;
return this;
}
/** Returns the HTTP request initializer or {@code null} for none. */
public final HttpRequestInitializer getHttpRequestInitializer() {
return httpRequestInitializer;
}
/**
* Sets the HTTP request initializer or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) {
this.httpRequestInitializer = httpRequestInitializer;
return this;
}
/**
* Returns the application name to be used in the UserAgent header of each request or
* {@code null} for none.
*/
public final String getApplicationName() {
return applicationName;
}
/**
* Sets the application name to be used in the UserAgent header of each request or {@code null}
* for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setApplicationName(String applicationName) {
this.applicationName = applicationName;
return this;
}
/** Returns whether discovery pattern checks should be suppressed on required parameters. */
public final boolean getSuppressPatternChecks() {
return suppressPatternChecks;
}
/**
* Sets whether discovery pattern checks should be suppressed on required parameters.
*
* <p>
* Default value is {@code false}.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
this.suppressPatternChecks = suppressPatternChecks;
return this;
}
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services.json;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.json.JsonCContent;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.subscriptions.json.JsonSubscribeRequest;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.UriTemplate;
import com.google.api.client.http.json.JsonHttpContent;
import java.io.IOException;
/**
* Google JSON request for a {@link AbstractGoogleJsonClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @param <T> type of the response
* @since 1.12
* @author Yaniv Inbar
*/
public abstract class AbstractGoogleJsonClientRequest<T> extends AbstractGoogleClientRequest<T> {
/** POJO that can be serialized into JSON content or {@code null} for none. */
private final Object jsonContent;
/**
* @param abstractGoogleJsonClient Google JSON client
* @param requestMethod HTTP Method
* @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/"
* the base path from the base URL will be stripped out. The URI template can also be a
* full URL. URI template expansion is done using
* {@link UriTemplate#expand(String, String, Object, boolean)}
* @param jsonContent POJO that can be serialized into JSON content or {@code null} for none
* @param responseClass response class to parse into
*/
protected AbstractGoogleJsonClientRequest(AbstractGoogleJsonClient abstractGoogleJsonClient,
String requestMethod, String uriTemplate, Object jsonContent, Class<T> responseClass) {
super(abstractGoogleJsonClient, requestMethod, uriTemplate, jsonContent == null
? null : (abstractGoogleJsonClient.getObjectParser() instanceof JsonCParser)
? new JsonCContent(abstractGoogleJsonClient.getJsonFactory(), jsonContent)
: new JsonHttpContent(abstractGoogleJsonClient.getJsonFactory(), jsonContent),
responseClass);
this.jsonContent = jsonContent;
}
@Override
public AbstractGoogleJsonClient getAbstractGoogleClient() {
return (AbstractGoogleJsonClient) super.getAbstractGoogleClient();
}
@Override
public AbstractGoogleJsonClientRequest<T> setDisableGZipContent(boolean disableGZipContent) {
return (AbstractGoogleJsonClientRequest<T>) super.setDisableGZipContent(disableGZipContent);
}
@Override
public AbstractGoogleJsonClientRequest<T> setRequestHeaders(HttpHeaders headers) {
return (AbstractGoogleJsonClientRequest<T>) super.setRequestHeaders(headers);
}
/**
* Queues the request into the specified batch request container.
*
* <p>
* Batched requests are then executed when {@link BatchRequest#execute()} is called.
* </p>
* <p>
* Example usage:
* </p>
*
* <pre>
request.queue(batchRequest, new JsonBatchCallback<SomeResponseType>() {
public void onSuccess(SomeResponseType content, HttpHeaders responseHeaders) {
log("Success");
}
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
log(e.getMessage());
}
});
* </pre>
*
*
* @param batchRequest batch request container
* @param callback batch callback
*/
public final void queue(BatchRequest batchRequest, JsonBatchCallback<T> callback)
throws IOException {
super.queue(batchRequest, GoogleJsonErrorContainer.class, callback);
}
@Override
@Deprecated
protected GoogleJsonResponseException newExceptionOnError(HttpResponse response) {
return GoogleJsonResponseException.from(getAbstractGoogleClient().getJsonFactory(), response);
}
/**
* Subscribes to parsed JSON notifications.
*
* <p>
* Overriding is only supported for the purpose of changing visibility to public, but nothing
* else.
* </p>
*
* @param notificationDeliveryMethod notification delivery method
* @throws IOException
*
* @since 1.14
*/
@Override
protected JsonSubscribeRequest subscribe(String notificationDeliveryMethod) throws IOException {
return new JsonSubscribeRequest(
buildHttpRequest(), notificationDeliveryMethod, getAbstractGoogleClient().getJsonFactory());
}
/** Returns POJO that can be serialized into JSON content or {@code null} for none. */
public Object getJsonContent() {
return jsonContent;
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services.json;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.googleapis.services.AbstractGoogleClient;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
/**
* Thread-safe Google JSON client.
*
* @since 1.12
* @author Yaniv Inbar
*/
public abstract class AbstractGoogleJsonClient extends AbstractGoogleClient {
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param rootUrl root URL of the service
* @param servicePath service path
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param legacyDataWrapper whether using the legacy data wrapper in responses
*/
protected AbstractGoogleJsonClient(HttpTransport transport, JsonFactory jsonFactory,
String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer,
boolean legacyDataWrapper) {
super(transport, httpRequestInitializer, rootUrl, servicePath, newObjectParser(
jsonFactory, legacyDataWrapper));
}
/**
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param jsonObjectParser JSON object parser
* @param googleClientRequestInitializer Google request initializer or {@code null} for none
* @param applicationName application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @param suppressPatternChecks whether discovery pattern checks should be suppressed on required
* parameters
*/
protected AbstractGoogleJsonClient(HttpTransport transport,
HttpRequestInitializer httpRequestInitializer, String rootUrl, String servicePath,
JsonObjectParser jsonObjectParser,
GoogleClientRequestInitializer googleClientRequestInitializer, String applicationName,
boolean suppressPatternChecks) {
super(transport, httpRequestInitializer, rootUrl, servicePath, jsonObjectParser,
googleClientRequestInitializer, applicationName, suppressPatternChecks);
}
@Override
public JsonObjectParser getObjectParser() {
return (JsonObjectParser) super.getObjectParser();
}
/** Returns the JSON Factory. */
public final JsonFactory getJsonFactory() {
return getObjectParser().getJsonFactory();
}
/**
* @param jsonFactory JSON factory
* @param legacyDataWrapper whether using the legacy data wrapper in responses
*/
static JsonObjectParser newObjectParser(JsonFactory jsonFactory, boolean legacyDataWrapper) {
return legacyDataWrapper ? new JsonCParser(jsonFactory) : new JsonObjectParser(jsonFactory);
}
/**
* Builder for {@link AbstractGoogleJsonClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
public abstract static class Builder extends AbstractGoogleClient.Builder {
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param rootUrl root URL of the service
* @param servicePath service path
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param legacyDataWrapper whether using the legacy data wrapper in responses
*/
protected Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl,
String servicePath, HttpRequestInitializer httpRequestInitializer,
boolean legacyDataWrapper) {
super(transport, rootUrl, servicePath, newObjectParser(jsonFactory, legacyDataWrapper),
httpRequestInitializer);
}
@Override
public final JsonObjectParser getObjectParser() {
return (JsonObjectParser) super.getObjectParser();
}
/** Returns the JSON Factory. */
public final JsonFactory getJsonFactory() {
return getObjectParser().getJsonFactory();
}
@Override
public abstract AbstractGoogleJsonClient build();
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setGoogleClientRequestInitializer(
GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
@Override
public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Contains the basis for the generated service-specific libraries based on the JSON format.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.services.json;
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services.json;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer;
import java.io.IOException;
/**
* Google JSON client request initializer implementation for setting properties like key and userIp.
*
* <p>
* The simplest usage is to use it to set the key parameter:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer KEY_INITIALIZER =
new CommonGoogleJsonClientRequestInitializer(KEY);
* </pre>
*
* <p>
* There is also a constructor to set both the key and userIp parameters:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer INITIALIZER =
new CommonGoogleJsonClientRequestInitializer(KEY, USER_IP);
* </pre>
*
* <p>
* If you want to implement custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer extends CommonGoogleJsonClientRequestInitializer {
{@literal @}Override
public void initialize(AbstractGoogleJsonClientRequest{@literal <}?{@literal >} request)
throws IOException {
// custom logic
}
}
* </pre>
*
* <p>
* Finally, to set the key and userIp parameters and insert custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer2 extends CommonGoogleJsonClientRequestInitializer {
public MyKeyRequestInitializer() {
super(KEY, USER_IP);
}
{@literal @}Override
public void initializeJsonRequest(AbstractGoogleJsonClientRequest{
@literal <}?{@literal >} request) throws IOException {
// custom logic
}
}
* </pre>
*
* <p>
* Subclasses should be thread-safe.
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
public class CommonGoogleJsonClientRequestInitializer extends CommonGoogleClientRequestInitializer {
public CommonGoogleJsonClientRequestInitializer() {
super();
}
/**
* @param key API key or {@code null} to leave it unchanged
*/
public CommonGoogleJsonClientRequestInitializer(String key) {
super(key);
}
/**
* @param key API key or {@code null} to leave it unchanged
* @param userIp user IP or {@code null} to leave it unchanged
*/
public CommonGoogleJsonClientRequestInitializer(String key, String userIp) {
super(key, userIp);
}
@Override
public final void initialize(AbstractGoogleClientRequest<?> request) throws IOException {
super.initialize(request);
initializeJsonRequest((AbstractGoogleJsonClientRequest<?>) request);
}
/**
* Initializes a Google JSON client request.
*
* <p>
* Default implementation does nothing. Called from
* {@link #initialize(AbstractGoogleClientRequest)}.
* </p>
*
* @throws IOException I/O exception
*/
protected void initializeJsonRequest(AbstractGoogleJsonClientRequest<?> request)
throws IOException {
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.
*/
/**
* Contains the basis for the generated service-specific libraries.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.6
* @author Ravi Mistry
*/
package com.google.api.client.googleapis.services;
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import java.io.IOException;
/**
* Google client request initializer.
*
* <p>
* For example, this might be used to set a key URL query parameter on all requests:
* </p>
*
* <pre>
public class KeyRequestInitializer implements GoogleClientRequestInitializer {
public void initialize(GoogleClientRequest<?> request) {
request.put("key", KEY);
}
}
* </pre>
*
* <p>
* Implementations should be thread-safe.
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
public interface GoogleClientRequestInitializer {
/** Initializes a Google client request. */
void initialize(AbstractGoogleClientRequest<?> request) throws IOException;
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.services;
import com.google.api.client.googleapis.MethodOverride;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpMethod;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpClient;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import java.io.IOException;
import java.util.Arrays;
/**
* Google API client.
*
* @since 1.6
* @author Ravi Mistry
* @deprecated (scheduled to be removed in 1.14) Use {@code
* com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient} instead.
*/
@Deprecated
public class GoogleClient extends JsonHttpClient {
/** Whether discovery pattern checks should be suppressed on required parameters. */
private boolean suppressPatternChecks;
/**
* Constructor with required parameters.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport The transport to use for requests
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param baseUrl The base URL of the service. Must end with a "/"
*/
public GoogleClient(HttpTransport transport, JsonFactory jsonFactory, String baseUrl) {
super(transport, jsonFactory, baseUrl);
}
/**
* Constructor with required parameters.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport The transport to use for requests
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param rootUrl The root URL of the service. Must end with a "/"
* @param servicePath The service path of the service. Must end with a "/" and not begin with a
* "/". It is allowed to be an empty string {@code ""}
* @param httpRequestInitializer The HTTP request initializer or {@code null} for none
* @since 1.10
*/
public GoogleClient(HttpTransport transport, JsonFactory jsonFactory, String rootUrl,
String servicePath, HttpRequestInitializer httpRequestInitializer) {
super(transport, jsonFactory, rootUrl, servicePath, httpRequestInitializer);
}
/**
* Construct the {@link GoogleClient}.
*
* @param transport The transport to use for requests
* @param jsonHttpRequestInitializer The initializer to use when creating an
* {@link JsonHttpRequest} or {@code null} for none
* @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or
* {@code null} for none
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param jsonObjectParser JSON parser to use or {@code null} if unused
* @param baseUrl The base URL of the service. Must end with a "/"
* @param applicationName The application name to be sent in the User-Agent header of requests or
* {@code null} for none
*/
protected GoogleClient(HttpTransport transport,
JsonHttpRequestInitializer jsonHttpRequestInitializer,
HttpRequestInitializer httpRequestInitializer, JsonFactory jsonFactory,
JsonObjectParser jsonObjectParser, String baseUrl, String applicationName) {
super(transport, jsonHttpRequestInitializer, httpRequestInitializer, jsonFactory,
jsonObjectParser, baseUrl, applicationName);
}
/**
* Construct the {@link GoogleClient}.
*
* @param transport The transport to use for requests
* @param jsonHttpRequestInitializer The initializer to use when creating an
* {@link JsonHttpRequest} or {@code null} for none
* @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or
* {@code null} for none
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param jsonObjectParser JSON parser to use or {@code null} if unused
* @param rootUrl The root URL of the service. Must end with a "/"
* @param servicePath The service path of the service. Must end with a "/" and not begin with a
* "/". It is allowed to be an empty string {@code ""}
* @param applicationName The application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @since 1.10
*/
protected GoogleClient(HttpTransport transport,
JsonHttpRequestInitializer jsonHttpRequestInitializer,
HttpRequestInitializer httpRequestInitializer, JsonFactory jsonFactory,
JsonObjectParser jsonObjectParser, String rootUrl, String servicePath,
String applicationName) {
super(transport, jsonHttpRequestInitializer, httpRequestInitializer, jsonFactory,
jsonObjectParser, rootUrl, servicePath, applicationName);
}
/**
* Construct the {@link GoogleClient}.
*
* @param transport The transport to use for requests
* @param jsonHttpRequestInitializer The initializer to use when creating an
* {@link JsonHttpRequest} or {@code null} for none
* @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or
* {@code null} for none
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param jsonObjectParser JSON parser to use or {@code null} if unused
* @param rootUrl The root URL of the service. Must end with a "/"
* @param servicePath The service path of the service. Must end with a "/" and not begin with a
* "/". It is allowed to be an empty string {@code ""}
* @param applicationName The application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @since 1.11
*/
protected GoogleClient(HttpTransport transport,
JsonHttpRequestInitializer jsonHttpRequestInitializer,
HttpRequestInitializer httpRequestInitializer, JsonFactory jsonFactory,
JsonObjectParser jsonObjectParser, String rootUrl, String servicePath, String applicationName,
boolean suppressPatternChecks) {
super(transport, jsonHttpRequestInitializer, httpRequestInitializer, jsonFactory,
jsonObjectParser, rootUrl, servicePath, applicationName);
this.suppressPatternChecks = suppressPatternChecks;
}
/**
* Create an {@link HttpRequest} suitable for use against this service.
*
* @param method HTTP Method type
* @param url The complete URL of the service where requests should be sent. It includes the base
* path along with the URI template
* @param body A POJO that can be serialized into JSON or {@code null} for none
* @return newly created {@link HttpRequest}
*/
@Override
protected HttpRequest buildHttpRequest(HttpMethod method, GenericUrl url, Object body)
throws IOException {
HttpRequest httpRequest = super.buildHttpRequest(method, url, body);
new MethodOverride().intercept(httpRequest);
// custom methods may use POST with no content but require a Content-Length header
if (body == null && method.equals(HttpMethod.POST)) {
httpRequest.setContent(new EmptyContent());
}
return httpRequest;
}
/**
* Create an {@link BatchRequest} object from this Google API client instance.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
client.batch()
.queue(...)
.queue(...)
.execute();
* </pre>
*
* @return newly created Batch request
*/
public BatchRequest batch() {
return batch(null);
}
/**
* Create an {@link BatchRequest} object from this Google API client instance.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
client.batch(httpRequestInitializer)
.queue(...)
.queue(...)
.execute();
* </pre>
*
* @param httpRequestInitializer The initializer to use when creating the top-level batch HTTP
* request or {@code null} for none
* @return newly created Batch request
*/
public BatchRequest batch(HttpRequestInitializer httpRequestInitializer) {
BatchRequest batch =
new BatchRequest(getRequestFactory().getTransport(), httpRequestInitializer);
GenericUrl baseUrl;
if (isBaseUrlUsed()) {
baseUrl = new GenericUrl(getBaseUrl());
baseUrl.setPathParts(Arrays.asList("", "batch"));
} else {
baseUrl = new GenericUrl(getRootUrl() + "batch");
}
batch.setBatchUrl(baseUrl);
return batch;
}
@Override
protected HttpResponse executeUnparsed(HttpMethod method, GenericUrl url, Object body)
throws IOException {
HttpRequest request = buildHttpRequest(method, url, body);
return executeUnparsed(request);
}
@Override
protected HttpResponse executeUnparsed(HttpRequest request) throws IOException {
return GoogleJsonResponseException.execute(getJsonFactory(), request);
}
/**
* Returns whether discovery pattern checks should be suppressed on required parameters.
*
* @since 1.11
*/
public final boolean getSuppressPatternChecks() {
return suppressPatternChecks;
}
/**
* Builder for {@link GoogleClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.6
* @deprecated (scheduled to be removed in 1.14) Use
* {@link com.google.api.client.googleapis.services.AbstractGoogleClient.Builder}
* instead.
*/
@Deprecated
public static class Builder extends JsonHttpClient.Builder {
/** Whether discovery pattern checks should be suppressed on required parameters. */
private boolean suppressPatternChecks;
/**
* Returns whether discovery pattern checks should be suppressed on required parameters.
*
* @since 1.11
*/
public final boolean getSuppressPatternChecks() {
return suppressPatternChecks;
}
/**
* Sets whether discovery pattern checks should be suppressed on required parameters.
*
* <p>
* Default value is {@code false}.
* </p>
*
* @since 1.11
*/
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
this.suppressPatternChecks = suppressPatternChecks;
return this;
}
/**
* Returns an instance of a new builder.
*
* @param transport The transport to use for requests
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param baseUrl The base URL of the service. Must end with a "/"
*/
protected Builder(HttpTransport transport, JsonFactory jsonFactory, GenericUrl baseUrl) {
super(transport, jsonFactory, baseUrl);
}
/**
* Returns an instance of a new builder.
*
* @param transport The transport to use for requests
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param rootUrl The root URL of the service. Must end with a "/"
* @param servicePath The service path of the service. Must end with a "/" and not begin with a
* "/". It is allowed to be an empty string {@code ""}
* @param httpRequestInitializer The HTTP request initializer or {@code null} for none
* @since 1.10
*/
public Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl,
String servicePath, HttpRequestInitializer httpRequestInitializer) {
super(transport, jsonFactory, rootUrl, servicePath, httpRequestInitializer);
}
/** Builds a new instance of {@link GoogleClient}. */
@Override
public GoogleClient build() {
if (isBaseUrlUsed()) {
return new GoogleClient(getTransport(), getJsonHttpRequestInitializer(),
getHttpRequestInitializer(), getJsonFactory(), getObjectParser(), getBaseUrl().build(),
getApplicationName());
}
return new GoogleClient(getTransport(), getJsonHttpRequestInitializer(),
getHttpRequestInitializer(), getJsonFactory(), getObjectParser(), getRootUrl(),
getServicePath(), getApplicationName(), getSuppressPatternChecks());
}
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import com.google.api.client.googleapis.MethodOverride;
import com.google.api.client.googleapis.batch.BatchCallback;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.media.MediaHttpDownloader;
import com.google.api.client.googleapis.media.MediaHttpUploader;
import com.google.api.client.googleapis.subscriptions.SubscribeRequest;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpMethods;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpResponseInterceptor;
import com.google.api.client.http.UriTemplate;
import com.google.api.client.util.GenericData;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Abstract Google client request for a {@link AbstractGoogleClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @param <T> type of the response
*
* @since 1.12
* @author Yaniv Inbar
*/
public abstract class AbstractGoogleClientRequest<T> extends GenericData {
/** Google client. */
private final AbstractGoogleClient abstractGoogleClient;
/** HTTP method. */
private final String requestMethod;
/** URI template for the path relative to the base URL. */
private final String uriTemplate;
/** HTTP content or {@code null} for none. */
private final HttpContent httpContent;
/** HTTP headers used for the Google client request. */
private HttpHeaders requestHeaders = new HttpHeaders();
/** HTTP headers of the last response or {@code null} before request has been executed. */
private HttpHeaders lastResponseHeaders;
/** Status code of the last response or {@code -1} before request has been executed. */
private int lastStatusCode = -1;
/** Status message of the last response or {@code null} before request has been executed. */
private String lastStatusMessage;
/** Whether to disable GZip compression of HTTP content. */
private boolean disableGZipContent;
/** Response class to parse into. */
private Class<T> responseClass;
/** Media HTTP uploader or {@code null} for none. */
private MediaHttpUploader uploader;
/** Media HTTP downloader or {@code null} for none. */
private MediaHttpDownloader downloader;
/**
* @param abstractGoogleClient Google client
* @param requestMethod HTTP Method
* @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/"
* the base path from the base URL will be stripped out. The URI template can also be a
* full URL. URI template expansion is done using
* {@link UriTemplate#expand(String, String, Object, boolean)}
* @param httpContent HTTP content or {@code null} for none
* @param responseClass response class to parse into
*/
protected AbstractGoogleClientRequest(AbstractGoogleClient abstractGoogleClient,
String requestMethod, String uriTemplate, HttpContent httpContent, Class<T> responseClass) {
this.responseClass = Preconditions.checkNotNull(responseClass);
this.abstractGoogleClient = Preconditions.checkNotNull(abstractGoogleClient);
this.requestMethod = Preconditions.checkNotNull(requestMethod);
this.uriTemplate = Preconditions.checkNotNull(uriTemplate);
this.httpContent = httpContent;
// application name
String applicationName = abstractGoogleClient.getApplicationName();
if (applicationName != null) {
requestHeaders.setUserAgent(applicationName);
}
}
/** Returns whether to disable GZip compression of HTTP content. */
public final boolean getDisableGZipContent() {
return disableGZipContent;
}
/**
* Sets whether to disable GZip compression of HTTP content.
*
* <p>
* By default it is {@code false}.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractGoogleClientRequest<T> setDisableGZipContent(boolean disableGZipContent) {
this.disableGZipContent = disableGZipContent;
return this;
}
/** Returns the HTTP method. */
public final String getRequestMethod() {
return requestMethod;
}
/** Returns the URI template for the path relative to the base URL. */
public final String getUriTemplate() {
return uriTemplate;
}
/** Returns the HTTP content or {@code null} for none. */
public final HttpContent getHttpContent() {
return httpContent;
}
/**
* Returns the Google client.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractGoogleClient getAbstractGoogleClient() {
return abstractGoogleClient;
}
/** Returns the HTTP headers used for the Google client request. */
public final HttpHeaders getRequestHeaders() {
return requestHeaders;
}
/**
* Sets the HTTP headers used for the Google client request.
*
* <p>
* These headers are set on the request after {@link #buildHttpRequest} is called, this means that
* {@link HttpRequestInitializer#initialize} is called first.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractGoogleClientRequest<T> setRequestHeaders(HttpHeaders headers) {
this.requestHeaders = headers;
return this;
}
/**
* Returns the HTTP headers of the last response or {@code null} before request has been executed.
*/
public final HttpHeaders getLastResponseHeaders() {
return lastResponseHeaders;
}
/**
* Returns the status code of the last response or {@code -1} before request has been executed.
*/
public final int getLastStatusCode() {
return lastStatusCode;
}
/**
* Returns the status message of the last response or {@code null} before request has been
* executed.
*/
public final String getLastStatusMessage() {
return lastStatusMessage;
}
/** Returns the response class to parse into. */
public final Class<T> getResponseClass() {
return responseClass;
}
/**
* Subscribes to notifications for a resource or collection.
*
* <p>
* Overriding is only supported for the purpose of changing visibility to public, but nothing
* else.
* </p>
*
* @param notificationDeliveryMethod notification delivery method
* @throws IOException
*
* @since 1.14
*/
protected SubscribeRequest subscribe(String notificationDeliveryMethod) throws IOException {
return new SubscribeRequest(buildHttpRequest(), notificationDeliveryMethod);
}
/** Returns the media HTTP Uploader or {@code null} for none. */
public final MediaHttpUploader getMediaHttpUploader() {
return uploader;
}
/**
* Initializes the media HTTP uploader based on the media content.
*
* @param mediaContent media content
*/
protected final void initializeMediaUpload(AbstractInputStreamContent mediaContent) {
HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory();
this.uploader = new MediaHttpUploader(
mediaContent, requestFactory.getTransport(), requestFactory.getInitializer());
this.uploader.setInitiationRequestMethod(requestMethod);
if (httpContent != null) {
this.uploader.setMetadata(httpContent);
}
}
/** Returns the media HTTP downloader or {@code null} for none. */
public final MediaHttpDownloader getMediaHttpDownloader() {
return downloader;
}
/** Initializes the media HTTP downloader. */
protected final void initializeMediaDownload() {
HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory();
this.downloader =
new MediaHttpDownloader(requestFactory.getTransport(), requestFactory.getInitializer());
}
/**
* Creates a new instance of {@link GenericUrl} suitable for use against this service.
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return newly created {@link GenericUrl}
*/
public GenericUrl buildHttpRequestUrl() {
return new GenericUrl(
UriTemplate.expand(abstractGoogleClient.getBaseUrl(), uriTemplate, this, true));
}
/**
* Create a request suitable for use against this service.
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*/
public HttpRequest buildHttpRequest() throws IOException {
return buildHttpRequest(false);
}
/**
* Create a request suitable for use against this service, but using HEAD instead of GET.
*
* <p>
* Only supported when the original request method is GET.
* </p>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*/
protected HttpRequest buildHttpRequestUsingHead() throws IOException {
return buildHttpRequest(true);
}
/** Create a request suitable for use against this service. */
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException {
Preconditions.checkArgument(uploader == null);
Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET));
String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod;
final HttpRequest httpRequest = getAbstractGoogleClient()
.getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent);
new MethodOverride().intercept(httpRequest);
httpRequest.setParser(getAbstractGoogleClient().getObjectParser());
// custom methods may use POST with no content but require a Content-Length header
if (httpContent == null && (requestMethod.equals(HttpMethods.POST)
|| requestMethod.equals(HttpMethods.PUT) || requestMethod.equals("PATCH"))) {
httpRequest.setContent(new EmptyContent());
}
httpRequest.getHeaders().putAll(requestHeaders);
httpRequest.setEnableGZipContent(!disableGZipContent);
final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor();
httpRequest.setResponseInterceptor(new HttpResponseInterceptor() {
public void interceptResponse(HttpResponse response) throws IOException {
if (responseInterceptor != null) {
responseInterceptor.interceptResponse(response);
}
if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) {
throw newExceptionOnError(response);
}
}
});
return httpRequest;
}
/**
* Sends the metadata request to the server and returns the raw metadata {@link HttpResponse}.
*
* <p>
* Callers are responsible for disconnecting the HTTP response by calling
* {@link HttpResponse#disconnect}. Example usage:
* </p>
*
* <pre>
HttpResponse response = request.executeUnparsed();
try {
// process response..
} finally {
response.disconnect();
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return the {@link HttpResponse}
*/
public HttpResponse executeUnparsed() throws IOException {
return executeUnparsed(false);
}
/**
* Sends the media request to the server and returns the raw media {@link HttpResponse}.
*
* <p>
* Callers are responsible for disconnecting the HTTP response by calling
* {@link HttpResponse#disconnect}. Example usage:
* </p>
*
* <pre>
HttpResponse response = request.executeMedia();
try {
// process response..
} finally {
response.disconnect();
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return the {@link HttpResponse}
*/
protected HttpResponse executeMedia() throws IOException {
set("alt", "media");
return executeUnparsed();
}
/**
* Sends the metadata request using HEAD to the server and returns the raw metadata
* {@link HttpResponse} for the response headers.
*
* <p>
* Only supported when the original request method is GET. The response content is assumed to be
* empty and ignored. Calls {@link HttpResponse#ignore()} so there is no need to disconnect the
* response. Example usage:
* </p>
*
* <pre>
HttpResponse response = request.executeUsingHead();
// look at response.getHeaders()
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return the {@link HttpResponse}
*/
protected HttpResponse executeUsingHead() throws IOException {
Preconditions.checkArgument(uploader == null);
HttpResponse response = executeUnparsed(true);
response.ignore();
return response;
}
/**
* Sends the metadata request using the given request method to the server and returns the raw
* metadata {@link HttpResponse}.
*/
private HttpResponse executeUnparsed(boolean usingHead) throws IOException {
HttpResponse response;
if (uploader == null) {
// normal request (not upload)
response = buildHttpRequest(usingHead).execute();
} else {
// upload request
GenericUrl httpRequestUrl = buildHttpRequestUrl();
HttpRequest httpRequest = getAbstractGoogleClient()
.getRequestFactory().buildRequest(requestMethod, httpRequestUrl, httpContent);
boolean throwExceptionOnExecuteError = httpRequest.getThrowExceptionOnExecuteError();
response = uploader.setInitiationHeaders(requestHeaders)
.setDisableGZipContent(disableGZipContent)
.upload(httpRequestUrl);
response.getRequest().setParser(getAbstractGoogleClient().getObjectParser());
// process any error
if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) {
throw newExceptionOnError(response);
}
}
// process response
lastResponseHeaders = response.getHeaders();
lastStatusCode = response.getStatusCode();
lastStatusMessage = response.getStatusMessage();
return response;
}
/**
* Returns the exception to throw on an HTTP error response as defined by
* {@link HttpResponse#isSuccessStatusCode()}.
*
* <p>
* It is guaranteed that {@link HttpResponse#isSuccessStatusCode()} is {@code false}. Default
* implementation is to call {@link HttpResponseException#HttpResponseException(HttpResponse)},
* but subclasses may override.
* </p>
*
* @param response HTTP response
* @return exception to throw
*/
protected IOException newExceptionOnError(HttpResponse response) {
return new HttpResponseException(response);
}
/**
* Sends the metadata request to the server and returns the parsed metadata response.
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return parsed HTTP response
*/
public T execute() throws IOException {
HttpResponse response = executeUnparsed();
// TODO(yanivi): remove workaround when feature is implemented
// workaround for http://code.google.com/p/google-http-java-client/issues/detail?id=110
if (Void.class.equals(responseClass)) {
response.ignore();
return null;
}
return response.parseAs(responseClass);
}
/**
* Sends the metadata request to the server and returns the metadata content input stream of
* {@link HttpResponse}.
*
* <p>
* Callers are responsible for closing the input stream after it is processed. Example sample:
* </p>
*
* <pre>
InputStream is = request.executeAsInputStream();
try {
// Process input stream..
} finally {
is.close();
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return input stream of the response content
*/
public InputStream executeAsInputStream() throws IOException {
return executeUnparsed().getContent();
}
/**
* Sends the media request to the server and returns the media content input stream of
* {@link HttpResponse}.
*
* <p>
* Callers are responsible for closing the input stream after it is processed. Example sample:
* </p>
*
* <pre>
InputStream is = request.executeMediaAsInputStream();
try {
// Process input stream..
} finally {
is.close();
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return input stream of the response content
*/
protected InputStream executeMediaAsInputStream() throws IOException {
return executeMedia().getContent();
}
/**
* Sends the metadata request to the server and writes the metadata content input stream of
* {@link HttpResponse} into the given destination output stream.
*
* <p>
* This method closes the content of the HTTP response from {@link HttpResponse#getContent()}.
* </p>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @param outputStream destination output stream
*/
public void executeAndDownloadTo(OutputStream outputStream) throws IOException {
executeUnparsed().download(outputStream);
}
/**
* Sends the media request to the server and writes the media content input stream of
* {@link HttpResponse} into the given destination output stream.
*
* <p>
* This method closes the content of the HTTP response from {@link HttpResponse#getContent()}.
* </p>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @param outputStream destination output stream
*/
protected void executeMediaAndDownloadTo(OutputStream outputStream) throws IOException {
if (downloader == null) {
executeMedia().download(outputStream);
} else {
downloader.download(buildHttpRequestUrl(), requestHeaders, outputStream);
}
}
/**
* Queues the request into the specified batch request container using the specified error class.
*
* <p>
* Batched requests are then executed when {@link BatchRequest#execute()} is called.
* </p>
*
* @param batchRequest batch request container
* @param errorClass data class the unsuccessful response will be parsed into or
* {@code Void.class} to ignore the content
* @param callback batch callback
*/
public final <E> void queue(
BatchRequest batchRequest, Class<E> errorClass, BatchCallback<T, E> callback)
throws IOException {
Preconditions.checkArgument(uploader == null, "Batching media requests is not supported");
batchRequest.queue(buildHttpRequest(), getResponseClass(), errorClass, callback);
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import java.io.IOException;
/**
* Google common client request initializer implementation for setting properties like key and
* userIp.
*
* <p>
* The simplest usage is to use it to set the key parameter:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer KEY_INITIALIZER =
new CommonGoogleClientRequestInitializer(KEY);
* </pre>
*
* <p>
* There is also a constructor to set both the key and userIp parameters:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer INITIALIZER =
new CommonGoogleClientRequestInitializer(KEY, USER_IP);
* </pre>
*
* <p>
* If you want to implement custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer extends CommonGoogleClientRequestInitializer {
{@literal @}Override
public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request)
throws IOException {
// custom logic
}
}
* </pre>
*
* <p>
* Finally, to set the key and userIp parameters and insert custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer2 extends CommonGoogleClientRequestInitializer {
public MyRequestInitializer2() {
super(KEY, USER_IP);
}
{@literal @}Override
public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request)
throws IOException {
super.initialize(request); // must be called to set the key and userIp parameters
// insert some additional logic
}
}
* </pre>
*
* <p>
* Subclasses should be thread-safe.
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
public class CommonGoogleClientRequestInitializer implements GoogleClientRequestInitializer {
/** API key or {@code null} to leave it unchanged. */
private final String key;
/** User IP or {@code null} to leave it unchanged. */
private final String userIp;
public CommonGoogleClientRequestInitializer() {
this(null);
}
/**
* @param key API key or {@code null} to leave it unchanged
*/
public CommonGoogleClientRequestInitializer(String key) {
this(key, null);
}
/**
* @param key API key or {@code null} to leave it unchanged
* @param userIp user IP or {@code null} to leave it unchanged
*/
public CommonGoogleClientRequestInitializer(String key, String userIp) {
this.key = key;
this.userIp = userIp;
}
/**
* Subclasses should call super implementation in order to set the key and userIp.
*
* @throws IOException I/O exception
*/
public void initialize(AbstractGoogleClientRequest<?> request) throws IOException {
if (key != null) {
request.put("key", key);
}
if (userIp != null) {
request.put("userIp", userIp);
}
}
/** Returns the API key or {@code null} to leave it unchanged. */
public final String getKey() {
return key;
}
/** Returns the user IP or {@code null} to leave it unchanged. */
public final String getUserIp() {
return userIp;
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.services;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
/**
* Google client request initializer that specifies a Google API key for all requests.
*
* <p>
* This is needed when doing unauthenticated access to Google APIs. Otherwise, you will only be able
* to make a small number of queries. When you exceed this limit, you will receive a "403 Forbidden"
* error with the message "Daily Limit Exceeded. Please sign up". See <a
* href="http://code.google.com/p/google-api-java-client/wiki/OAuth2#Unauthenticated_access"
* >Unauthenticated access</a> for more details.
* </p>
*
* <p>
* Note that this is not needed when doing authenticated access with an OAuth 2.0 access token,
* because the OAuth 2.0 client ID is already associated with the same project as the API key.
* </p>
*
* @since 1.8
* @author Yaniv Inbar
* @deprecated (scheduled to be removed in 1.14) Instead use either
* {@link CommonGoogleClientRequestInitializer} or a subclass of it.
*/
@Deprecated
public class GoogleKeyInitializer
implements
JsonHttpRequestInitializer,
GoogleClientRequestInitializer {
/** API key. */
private final String key;
/**
* @param key API key
*/
public GoogleKeyInitializer(String key) {
this.key = key;
}
public void initialize(JsonHttpRequest request) {
request.put("key", key);
}
public void initialize(AbstractGoogleClientRequest<?> request) {
request.put("key", key);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpMethods;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.UrlEncodedContent;
import java.io.IOException;
/**
* Thread-safe HTTP request execute interceptor for Google API's that wraps HTTP requests inside of
* a POST request and uses {@link #HEADER} header to specify the actual HTTP method.
*
* <p>
* Use this for example for an HTTP transport that doesn't support PATCH like
* {@code NetHttpTransport} or {@code UrlFetchTransport}. By default, only the methods not supported
* by the transport will be overridden. When running behind a firewall that does not support certain
* verbs like PATCH, use the {@link MethodOverride.Builder#setOverrideAllMethods(boolean)}
* constructor instead to specify to override all methods. POST is never overridden.
* </p>
*
* <p>
* This class also allows GET requests with a long URL (> 2048 chars) to be instead sent using
* method override as a POST request.
* </p>
*
* <p>
* Sample usage, taking advantage that this class implements {@link HttpRequestInitializer}:
* </p>
*
* <pre>
public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
return transport.createRequestFactory(new MethodOverride());
}
* </pre>
*
* <p>
* If you have a custom request initializer, take a look at the sample usage for
* {@link HttpExecuteInterceptor}, which this class also implements.
* </p>
*
* @since 1.4
* @author Yaniv Inbar
*/
@SuppressWarnings("deprecation")
public final class MethodOverride implements HttpExecuteInterceptor, HttpRequestInitializer {
/**
* Name of the method override header.
*
* @since 1.13
*/
public static final String HEADER = "X-HTTP-Method-Override";
/** Maximum supported URL length. */
static final int MAX_URL_LENGTH = 2048;
/**
* Whether to allow all methods (except GET and POST) to be overridden regardless of whether the
* transport supports them.
*/
private final boolean overrideAllMethods;
/** Only overrides HTTP methods that the HTTP transport does not support. */
public MethodOverride() {
this(false);
}
MethodOverride(boolean overrideAllMethods) {
this.overrideAllMethods = overrideAllMethods;
}
public void initialize(HttpRequest request) {
request.setInterceptor(this);
}
public void intercept(HttpRequest request) throws IOException {
if (overrideThisMethod(request)) {
String requestMethod = request.getRequestMethod();
request.setRequestMethod(HttpMethods.POST);
request.getHeaders().set(HEADER, requestMethod);
if (requestMethod.equals(HttpMethods.GET)) {
// take the URI query part and put it into the HTTP body
request.setContent(new UrlEncodedContent(request.getUrl()));
} else if (request.getContent() == null) {
// Google servers will fail to process a POST unless the Content-Length header is specified
request.setContent(new EmptyContent());
}
}
}
private boolean overrideThisMethod(HttpRequest request) throws IOException {
String requestMethod = request.getRequestMethod();
if (requestMethod.equals(HttpMethods.POST)) {
return false;
}
if (requestMethod.equals(HttpMethods.GET)
? request.getUrl().build().length() > MAX_URL_LENGTH : overrideAllMethods) {
return true;
}
return !request.getTransport().supportsMethod(requestMethod);
}
/**
* Builder for {@link MethodOverride}.
*
* @since 1.12
* @author Yaniv Inbar
*/
public static final class Builder {
/**
* Whether to allow all methods (except GET and POST) to be overridden regardless of whether the
* transport supports them.
*/
private boolean overrideAllMethods;
/** Builds the {@link MethodOverride}. */
public MethodOverride build() {
return new MethodOverride(overrideAllMethods);
}
/**
* Returns whether to allow all methods (except GET and POST) to be overridden regardless of
* whether the transport supports them.
*/
public boolean getOverrideAllMethods() {
return overrideAllMethods;
}
/**
* Sets whether to allow all methods (except GET and POST) to be overridden regardless of
* whether the transport supports them.
*
* <p>
* Default is {@code false}.
* </p>
*/
public Builder setOverrideAllMethods(boolean overrideAllMethods) {
this.overrideAllMethods = overrideAllMethods;
return this;
}
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
import java.util.Collection;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* {@link SubscriptionStore} which stores all subscription information in memory.
*
* <p>
* Thread-safe implementation.
* </p>
*
* <b>Example usage:</b>
* <pre>
service.setSubscriptionStore(new MemorySubscriptionStore());
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public class MemorySubscriptionStore implements SubscriptionStore {
/** Lock on the token response information. */
private final Lock lock = new ReentrantLock();
/** Map of all stored subscriptions. */
private final SortedMap<String, Subscription> storedSubscriptions =
new TreeMap<String, Subscription>();
public void storeSubscription(Subscription subscription) {
lock.lock();
try {
storedSubscriptions.put(subscription.getSubscriptionId(), subscription);
} finally {
lock.unlock();
}
}
public void removeSubscription(Subscription subscription) {
lock.lock();
try {
storedSubscriptions.remove(subscription.getSubscriptionId());
} finally {
lock.unlock();
}
}
public Collection<Subscription> listSubscriptions() {
lock.lock();
try {
return Collections.unmodifiableCollection(storedSubscriptions.values());
} finally {
lock.unlock();
}
}
public Subscription getSubscription(String subscriptionId) {
lock.lock();
try {
return storedSubscriptions.get(subscriptionId);
} finally {
lock.unlock();
}
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
/**
* Typed notification sent to this client about a subscribed resource.
*
* <p>
* Thread-safe implementation.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
void handleNotification(
Subscription subscription, TypedNotification<ItemList> notification) {
for (Item item : notification.getContent().getItems()) {
System.out.println(item.getId());
}
}
* </pre>
*
* @param <T> Data content from the underlying response stored within this notification
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class TypedNotification<T> extends Notification {
/** Typed content or {@code null} for none. */
private final T content;
/** Returns the typed content or {@code null} for none. */
public final T getContent() {
return content;
}
/**
* @param notification notification whose information is copied
* @param content typed content or {@code null} for none
*/
public TypedNotification(Notification notification, T content) {
super(notification);
this.content = content;
}
/**
* @param subscriptionId subscription UUID
* @param topicId opaque ID for the subscribed resource that is stable across API versions
* @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that
* is sensitive to the API version
* @param clientToken client token (an opaque string) or {@code null} for none
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param eventType event type (see {@link EventTypes})
* @param changeType type of change performed on the resource or {@code null} for none
* @param content typed content or {@code null} for none
*/
public TypedNotification(String subscriptionId, String topicId, String topicURI,
String clientToken, long messageNumber, String eventType, String changeType, T content) {
super(subscriptionId, topicId, topicURI, clientToken, messageNumber, eventType, changeType);
this.content = content;
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.subscriptions;
import com.google.api.client.http.HttpResponse;
import com.google.common.base.Preconditions;
/**
* Subscribe response.
*
* @author Yaniv Inbar
* @since 1.14
*/
public class SubscribeResponse {
/** HTTP response. */
private final HttpResponse response;
/** Subscription or {@code null} for none. */
private final Subscription subscription;
/**
* @param response HTTP response
* @param subscription subscription or {@code null} for none
*/
public SubscribeResponse(HttpResponse response, Subscription subscription) {
this.response = Preconditions.checkNotNull(response);
this.subscription = subscription;
}
/** Returns the opaque ID for the subscribed resource that is stable across API versions. */
public final String getTopicId() {
return SubscriptionHeaders.getTopicId(response.getHeaders());
}
/**
* Returns the opaque ID (in the form of a canonicalized URI) for the subscribed resource that is
* sensitive to the API version.
*/
public final String getTopicUri() {
return SubscriptionHeaders.getTopicUri(response.getHeaders());
}
/** Returns the subscription UUID. */
public final String getSubscriptionId() {
return SubscriptionHeaders.getSubscriptionId(response.getHeaders());
}
/**
* Returns the HTTP Date indicating the time at which the subscription will expire returned in the
* subscribe response or {@code null} for an infinite TTL.
*/
public final String getSubscriptionExpires() {
return SubscriptionHeaders.getSubscriptionExpires(response.getHeaders());
}
/**
* Returns the client token (an opaque string) provided by the client or {@code null} for none.
*/
public final String getClientToken() {
return SubscriptionHeaders.getClientToken(response.getHeaders());
}
/** Returns the HTTP response. */
public final HttpResponse getHttpResponse() {
return response;
}
/** Returns the subscription or {@code null} for none. */
public final Subscription getSubscription() {
return subscription;
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.
*/
/**
* JSON-based notification handling for subscriptions.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.subscriptions.json;
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions.json;
import com.google.api.client.googleapis.subscriptions.TypedNotificationCallback;
import com.google.api.client.googleapis.subscriptions.UnparsedNotification;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.ObjectParser;
import java.io.IOException;
/**
* A {@link TypedNotificationCallback} which uses an JSON content encoding.
*
* <p>
* Must not be implemented in form of an anonymous class as this will break serialization.
* </p>
*
* <p>
* Implementation should be thread-safe.
* </p>
*
* <p>
* State will only be persisted once when a subscription is created. All state changes occurring
* during the {@code .handleNotification(..)} call will be lost.
* </p>
*
* <b>Example usage:</b>
* <pre>
class MyJsonNotificationCallback extends JsonNotificationCallback<ItemList> {
void handleNotification(
Subscription subscription, TypedNotification<ItemList> notification) {
for (Item item in notification.getContent().getItems()) {
System.out.println(item.getId());
}
}
}
JsonFactory createJsonFactory() {
return new JacksonFactory();
}
...
service.items.list("someID").subscribe(new MyJsonNotificationCallback()).execute()
* </pre>
*
* @param <T> Type of the data contained within a notification
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@SuppressWarnings("serial")
public abstract class JsonNotificationCallback<T> extends TypedNotificationCallback<T> {
/** JSON factory used to deserialize notifications. {@code null} until first used. */
private transient JsonFactory jsonFactory;
/**
* Returns the JSON-factory used by this handler.
*/
public final JsonFactory getJsonFactory() throws IOException {
if (jsonFactory == null) {
jsonFactory = createJsonFactory();
}
return jsonFactory;
}
// TODO(mlinder): Don't have the user supply the JsonFactory, but serialize it instead.
/**
* Creates a new JSON factory which is used to deserialize notifications.
*/
protected abstract JsonFactory createJsonFactory() throws IOException;
@Override
protected final ObjectParser getParser(UnparsedNotification notification) throws IOException {
return new JsonObjectParser(getJsonFactory());
}
@Override
public JsonNotificationCallback<T> setDataType(Class<T> dataClass) {
return (JsonNotificationCallback<T>) super.setDataType(dataClass);
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.subscriptions.json;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.googleapis.subscriptions.NotificationCallback;
import com.google.api.client.googleapis.subscriptions.SubscribeRequest;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
import com.google.api.client.googleapis.subscriptions.TypedNotificationCallback;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.json.JsonFactory;
import com.google.common.base.Preconditions;
import java.io.IOException;
/**
* Subscribe JSON request.
*
* @author Yaniv Inbar
* @since 1.14
*/
public class JsonSubscribeRequest extends SubscribeRequest {
/** JSON factory. */
private final JsonFactory jsonFactory;
/**
* @param request HTTP GET request
* @param notificationDeliveryMethod notification delivery method
* @param jsonFactory JSON factory
*/
public JsonSubscribeRequest(
HttpRequest request, String notificationDeliveryMethod, JsonFactory jsonFactory) {
super(request, notificationDeliveryMethod);
this.jsonFactory = Preconditions.checkNotNull(jsonFactory);
}
@Override
public JsonSubscribeRequest withNotificationCallback(
SubscriptionStore subscriptionStore, NotificationCallback notificationCallback) {
return (JsonSubscribeRequest) super.withNotificationCallback(
subscriptionStore, notificationCallback);
}
@Override
public <N> JsonSubscribeRequest withTypedNotificationCallback(SubscriptionStore subscriptionStore,
Class<N> notificationCallbackClass, TypedNotificationCallback<N> typedNotificationCallback) {
return (JsonSubscribeRequest) super.withTypedNotificationCallback(
subscriptionStore, notificationCallbackClass, typedNotificationCallback);
}
@Override
public JsonSubscribeRequest setNotificationDeliveryMethod(String notificationDeliveryMethod) {
return (JsonSubscribeRequest) super.setNotificationDeliveryMethod(notificationDeliveryMethod);
}
@Override
public JsonSubscribeRequest setClientToken(String clientToken) {
return (JsonSubscribeRequest) super.setClientToken(clientToken);
}
@Override
public JsonSubscribeRequest setSubscriptionId(String subscriptionId) {
return (JsonSubscribeRequest) super.setSubscriptionId(subscriptionId);
}
/**
* Sets the subscription store and JSON notification callback associated with this subscription.
*
* @param subscriptionStore subscription store
* @param notificationCallbackClass data class the successful notification will be parsed into or
* {@code Void.class} to ignore the content
* @param jsonNotificationCallback JSON notification callback
*/
public <N> JsonSubscribeRequest withJsonNotificationCallback(SubscriptionStore subscriptionStore,
Class<N> notificationCallbackClass, JsonNotificationCallback<N> jsonNotificationCallback) {
return withTypedNotificationCallback(
subscriptionStore, notificationCallbackClass, jsonNotificationCallback);
}
/** Returns the JSON factory. */
public final JsonFactory getJsonFactory() {
return jsonFactory;
}
/**
* Queues the subscribe JSON request into the specified batch request container.
*
* <p>
* Batched requests are then executed when {@link BatchRequest#execute()} is called.
* </p>
*
* <p>
* Example usage:
* </p>
*
* <pre>
request.queue(batchRequest, new JsonBatchCallback<Void>() {
public void onSuccess(Void ignored, HttpHeaders responseHeaders) {
log("Success");
}
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
log(e.getMessage());
}
});
* </pre>
*
*
* @param batchRequest batch request container
* @param callback batch callback
*/
public final void queue(BatchRequest batchRequest, JsonBatchCallback<Void> callback)
throws IOException {
super.queue(batchRequest, GoogleJsonErrorContainer.class, callback);
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.
*/
/**
* Support for creating subscriptions and receiving notifications for Google APIs.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.subscriptions;
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
/**
* Standard event-types used by notifications.
*
* <b>Example usage:</b>
*
* <pre>
void handleNotification(Subscription subscription, UnparsedNotification notification) {
if (notification.getEventType().equals(EventTypes.UPDATED)) {
// add items in the notification to the local client state ...
}
}
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class EventTypes {
/** Notification that the subscription is alive (comes with no payload). */
public static final String SYNC = "sync";
/** Resource was modified. */
public static final String UPDATED = "updated";
/** Resource was deleted. */
public static final String DELETED = "deleted";
/** Private constructor to prevent instantiation. */
private EventTypes() {
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
import com.google.common.base.Preconditions;
/**
* Notification sent to this client about a subscribed resource.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public abstract class Notification {
/** Subscription UUID. */
private final String subscriptionId;
/** Opaque ID for the subscribed resource that is stable across API versions. */
private final String topicId;
/**
* Opaque ID (in the form of a canonicalized URI) for the subscribed resource that is sensitive to
* the API version.
*/
private final String topicURI;
/** Client token (an opaque string) or {@code null} for none. */
private final String clientToken;
/** Message number (a monotonically increasing value starting with 1). */
private final long messageNumber;
/** Event type (see {@link EventTypes}). */
private final String eventType;
/** Type of change performed on the resource or {@code null} for none. */
private final String changeType;
/**
* @param subscriptionId subscription UUID
* @param topicId opaque ID for the subscribed resource that is stable across API versions
* @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that
* is sensitive to the API version
* @param clientToken client token (an opaque string) or {@code null} for none
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param eventType event type (see {@link EventTypes})
* @param changeType type of change performed on the resource or {@code null} for none
*/
protected Notification(String subscriptionId, String topicId, String topicURI, String clientToken,
long messageNumber, String eventType, String changeType) {
this.subscriptionId = Preconditions.checkNotNull(subscriptionId);
this.topicId = Preconditions.checkNotNull(topicId);
this.topicURI = Preconditions.checkNotNull(topicURI);
this.eventType = Preconditions.checkNotNull(eventType);
this.clientToken = clientToken;
Preconditions.checkArgument(messageNumber >= 1);
this.messageNumber = messageNumber;
this.changeType = changeType;
}
/**
* Creates a new notification by copying all information specified in the source notification.
*
* @param source notification whose information is copied
*/
protected Notification(Notification source) {
this(source.getSubscriptionId(), source.getTopicId(), source.getTopicURI(), source
.getClientToken(), source.getMessageNumber(), source.getEventType(), source
.getChangeType());
}
/** Returns the subscription UUID. */
public final String getSubscriptionId() {
return subscriptionId;
}
/** Returns the opaque ID for the subscribed resource that is stable across API versions. */
public final String getTopicId() {
return topicId;
}
/** Returns the client token (an opaque string) or {@code null} for none. */
public final String getClientToken() {
return clientToken;
}
/** Returns the event type (see {@link EventTypes}). */
public final String getEventType() {
return eventType;
}
/**
* Returns the opaque ID (in the form of a canonicalized URI) for the subscribed resource that is
* sensitive to the API version.
*/
public final String getTopicURI() {
return topicURI;
}
/** Returns the message number (a monotonically increasing value starting with 1). */
public final long getMessageNumber() {
return messageNumber;
}
/** Returns the type of change performed on the resource or {@code null} for none. */
public final String getChangeType() {
return changeType;
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
import java.io.IOException;
import java.util.Collection;
/**
* Stores and manages registered subscriptions and their handlers.
*
* <p>
* Implementation should be thread-safe.
* </p>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public interface SubscriptionStore {
/**
* Returns all known/registered subscriptions.
*/
Collection<Subscription> listSubscriptions() throws IOException;
/**
* Retrieves a known subscription or {@code null} if not found.
*
* @param subscriptionId ID of the subscription to retrieve
*/
Subscription getSubscription(String subscriptionId) throws IOException;
/**
* Stores the subscription in the applications data store, replacing any existing subscription
* with the same id.
*
* @param subscription New or existing {@link Subscription} to store/update
*/
void storeSubscription(Subscription subscription) throws IOException;
/**
* Removes a registered subscription from the store.
*
* @param subscription {@link Subscription} to remove or {@code null} to ignore
*/
void removeSubscription(Subscription subscription) throws IOException;
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.util.ObjectParser;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* Callback which is used to receive typed {@link Notification}s after subscribing to a topic.
*
* <p>
* Must not be implemented in form of an anonymous class as this will break serialization.
* </p>
*
* <p>
* Implementation should be thread-safe.
* </p>
*
* <p>
* State will only be persisted once when a subscription is created. All state changes occurring
* during the {@code .handleNotification(..)} call will be lost.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
class MyTypedNotificationCallback extends TypedNotificationCallback<ItemList> {
void handleNotification(
Subscription subscription, TypedNotification<ItemList> notification) {
for (Item item in notification.getContent().getItems()) {
System.out.println(item.getId());
}
}
}
ObjectParser getParser(UnparsedNotification notification) {
return new JacksonFactory().createJsonObjectParser();
}
...
service.items.list("someID").subscribe(new MyTypedNotificationCallback()).execute()
* </pre>
*
* @param <T> Type of the data contained within a notification
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@SuppressWarnings("serial")
public abstract class TypedNotificationCallback<T> implements NotificationCallback {
/**
* Data type which this handler can parse or {@code Void.class} if no data type is expected.
*/
private Class<T> dataClass;
/**
* Returns the data type which this handler can parse or {@code Void.class} if no data type is
* expected.
*/
public final Class<T> getDataClass() {
return dataClass;
}
/**
* Sets the data type which this handler can parse or {@code Void.class} if no data type is
* expected.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public TypedNotificationCallback<T> setDataType(Class<T> dataClass) {
this.dataClass = Preconditions.checkNotNull(dataClass);
return this;
}
/**
* Handles a received push notification.
*
* @param subscription Subscription to which this notification belongs
* @param notification Typed notification which was delivered to this application
*/
protected abstract void handleNotification(
Subscription subscription, TypedNotification<T> notification) throws IOException;
/**
* Returns an {@link ObjectParser} which can be used to parse this notification.
*
* @param notification Notification which should be parsable by the returned parser
*/
protected abstract ObjectParser getParser(UnparsedNotification notification) throws IOException;
/** Parses the specified content and closes the InputStream of the notification. */
private Object parseContent(ObjectParser parser, UnparsedNotification notification)
throws IOException {
// Return null if no content is expected
if (notification.getContentType() == null || Void.class.equals(dataClass)) {
return null;
}
// Parse the response otherwise
Charset charset = notification.getContentType() == null ? null : new HttpMediaType(
notification.getContentType()).getCharsetParameter();
return parser.parseAndClose(notification.getContent(), charset, dataClass);
}
public void handleNotification(Subscription subscription, UnparsedNotification notification)
throws IOException {
ObjectParser parser = getParser(notification);
@SuppressWarnings("unchecked")
T content = (T) parseContent(parser, notification);
handleNotification(subscription, new TypedNotification<T>(notification, content));
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
import com.google.api.client.http.HttpHeaders;
/**
* Headers for subscribe request and response.
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class SubscriptionHeaders {
/**
* Name of header for the client token (an opaque string) provided by the client in the subscribe
* request and returned in the subscribe response.
*/
public static final String CLIENT_TOKEN = "X-Goog-Client-Token";
/**
* Name of header for the notifications delivery method in the subscribe request.
*/
public static final String SUBSCRIBE = "X-Goog-Subscribe";
/**
* Name of header for the HTTP Date indicating the time at which the subscription will expire
* returned in the subscribe response or if not returned for an infinite TTL.
*/
public static final String SUBSCRIPTION_EXPIRES = "X-Goog-Subscription-Expires";
/**
* Name of header for the subscription UUID provided by the client in the subscribe request and
* returned in the subscribe response.
*/
public static final String SUBSCRIPTION_ID = "X-Goog-Subscription-ID";
/**
* Name of header for the opaque ID for the subscribed resource that is stable across API versions
* returned in the subscribe response.
*/
public static final String TOPIC_ID = "X-Goog-Topic-ID";
/**
* Name of header for the opaque ID (in the form of a canonicalized URI) for the subscribed
* resource that is sensitive to the API version returned in the subscribe response.
*/
public static final String TOPIC_URI = "X-Goog-Topic-URI";
/**
* Returns the client token (an opaque string) provided by the client in the subscribe request and
* returned in the subscribe response or {@code null} for none.
*/
public static String getClientToken(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(CLIENT_TOKEN);
}
/**
* Sets the client token (an opaque string) provided by the client in the subscribe request and
* returned in the subscribe response or {@code null} for none.
*/
public static void setClientToken(HttpHeaders headers, String clienToken) {
headers.set(CLIENT_TOKEN, clienToken);
}
/**
* Returns the notifications delivery method in the subscribe request or {@code null} for none.
*
* @param headers HTTP headers
*/
public static String getSubscribe(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(SUBSCRIBE);
}
/**
* Sets the notifications delivery method in the subscribe request or {@code null} for none.
*/
public static void setSubscribe(HttpHeaders headers, String subscribe) {
headers.set(SUBSCRIBE, subscribe);
}
/**
* Returns the HTTP Date indicating the time at which the subscription will expire returned in the
* subscribe response or {@code null} for an infinite TTL.
*/
public static String getSubscriptionExpires(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(SUBSCRIPTION_EXPIRES);
}
/**
* Sets the HTTP Date indicating the time at which the subscription will expire returned in the
* subscribe response or {@code null} for an infinite TTL.
*/
public static void setSubscriptionExpires(HttpHeaders headers, String subscriptionExpires) {
headers.set(SUBSCRIPTION_EXPIRES, subscriptionExpires);
}
/**
* Returns the subscription UUID provided by the client in the subscribe request and returned in
* the subscribe response or {@code null} for none.
*/
public static String getSubscriptionId(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(SUBSCRIPTION_ID);
}
/**
* Sets the subscription UUID provided by the client in the subscribe request and returned in the
* subscribe response or {@code null} for none.
*/
public static void setSubscriptionId(HttpHeaders headers, String subscriptionId) {
headers.set(SUBSCRIPTION_ID, subscriptionId);
}
/**
* Returns the opaque ID for the subscribed resource that is stable across API versions returned
* in the subscribe response or {@code null} for none.
*/
public static String getTopicId(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(TOPIC_ID);
}
/**
* Sets the opaque ID for the subscribed resource that is stable across API versions returned in
* the subscribe response or {@code null} for none.
*/
public static void setTopicId(HttpHeaders headers, String topicId) {
headers.set(TOPIC_ID, topicId);
}
/**
* Returns the opaque ID (in the form of a canonicalized URI) for the subscribed resource that is
* sensitive to the API version returned in the subscribe response or {@code null} for none.
*/
public static String getTopicUri(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(TOPIC_URI);
}
/**
* Sets the opaque ID (in the form of a canonicalized URI) for the subscribed resource that is
* sensitive to the API version returned in the subscribe response or {@code null} for none.
*/
public static void setTopicUri(HttpHeaders headers, String topicUri) {
headers.set(TOPIC_URI, topicUri);
}
private SubscriptionHeaders() {
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.io.IOException;
import java.io.InputStream;
/**
* A notification whose content has not been parsed yet.
*
* <p>
* Thread-safe implementation.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
void handleNotification(Subscription subscription, UnparsedNotification notification)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(notification.getContent()));
System.out.println(reader.readLine());
reader.close();
}
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class UnparsedNotification extends Notification {
/** The input stream containing the content. */
private final InputStream content;
/** The content-type of the stream or {@code null} if not specified. */
private final String contentType;
/**
* Creates a {@link Notification} whose content has not yet been read and parsed.
*
* @param subscriptionId subscription UUID
* @param topicId opaque ID for the subscribed resource that is stable across API versions
* @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that
* is sensitive to the API version
* @param clientToken client token (an opaque string) or {@code null} for none
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param eventType event type (see {@link EventTypes})
* @param changeType type of change performed on the resource or {@code null} for none
* @param unparsedStream Unparsed content in form of a {@link InputStream}. Caller has the
* responsibility of closing the stream.
*/
public UnparsedNotification(String subscriptionId, String topicId, String topicURI,
String clientToken, long messageNumber, String eventType, String changeType,
String contentType, InputStream unparsedStream) {
super(subscriptionId, topicId, topicURI, clientToken, messageNumber, eventType, changeType);
this.contentType = contentType;
this.content = Preconditions.checkNotNull(unparsedStream);
}
/**
* Returns the Content-Type of the Content of this notification.
*/
public final String getContentType() {
return contentType;
}
/**
* Returns the content stream of this notification.
*/
public final InputStream getContent() {
return content;
}
/**
* Handles a newly received notification, and delegates it to the registered handler.
*
* @param subscriptionStore subscription store
* @return {@code true} if the notification was delivered successfully, or {@code false} if this
* notification could not be delivered and the subscription should be cancelled.
* @throws IllegalArgumentException if there is a client-token mismatch
*/
public boolean deliverNotification(SubscriptionStore subscriptionStore) throws IOException {
// Find out the handler to whom this notification should go.
Subscription subscription =
subscriptionStore.getSubscription(Preconditions.checkNotNull(getSubscriptionId()));
if (subscription == null) {
return false;
}
// Validate the notification.
String expectedToken = subscription.getClientToken();
Preconditions.checkArgument(
Strings.isNullOrEmpty(expectedToken) || expectedToken.equals(getClientToken()),
"Token mismatch for subscription with id=%s -- got=%s expected=%s", getSubscriptionId(),
getClientToken(), expectedToken);
// Invoke the handler associated with this subscription.
NotificationCallback h = subscription.getNotificationCallback();
h.handleNotification(subscription, this);
return true;
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.subscriptions;
/**
* Headers for notifications.
*
* @author Kyle Marvin (kmarvin)
* @since 1.14
*/
public final class NotificationHeaders {
/** Name of header for the event type (see {@link EventTypes}). */
public static final String EVENT_TYPE_HEADER = "X-Goog-Event-Type";
/**
* Name of header for the type of change performed on the resource.
*/
public static final String CHANGED_HEADER = "X-Goog-Changed";
/**
* Name of header for the message number (a monotonically increasing value starting with 1).
*/
public static final String MESSAGE_NUMBER_HEADER = "X-Goog-Message-Number";
private NotificationHeaders() {
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.subscriptions;
import com.google.api.client.googleapis.batch.BatchCallback;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpMethods;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseInterceptor;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.UUID;
/**
* Subscribe request.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @author Yaniv Inbar
* @since 1.14
*/
public class SubscribeRequest {
/** HTTP request. */
private final HttpRequest request;
/** Notification callback or {@code null} for none. */
private NotificationCallback notificationCallback;
/** Subscription store or {@code null} for none. */
private SubscriptionStore subscriptionStore;
/** Stored subscription. */
Subscription subscription;
/**
* @param request HTTP GET request
* @param notificationDeliveryMethod notification delivery method
*/
public SubscribeRequest(HttpRequest request, String notificationDeliveryMethod) {
this.request = Preconditions.checkNotNull(request);
Preconditions.checkArgument(HttpMethods.GET.equals(request.getRequestMethod()));
request.setRequestMethod(HttpMethods.POST);
request.setContent(new EmptyContent());
setNotificationDeliveryMethod(notificationDeliveryMethod);
setSubscriptionId(UUID.randomUUID().toString());
}
/**
* Sets the subscription store and notification callback associated with this subscription.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param subscriptionStore subscription store
* @param notificationCallback notification callback
*/
public SubscribeRequest withNotificationCallback(
final SubscriptionStore subscriptionStore, final NotificationCallback notificationCallback) {
Preconditions.checkArgument(this.notificationCallback == null);
this.subscriptionStore = Preconditions.checkNotNull(subscriptionStore);
this.notificationCallback = Preconditions.checkNotNull(notificationCallback);
// execute interceptor
final HttpExecuteInterceptor executeInterceptor = request.getInterceptor();
request.setInterceptor(new HttpExecuteInterceptor() {
public void intercept(HttpRequest request) throws IOException {
if (subscription == null) {
subscription =
new Subscription(notificationCallback, getClientToken(), getSubscriptionId());
subscriptionStore.storeSubscription(subscription);
}
if (executeInterceptor != null) {
executeInterceptor.intercept(request);
}
}
});
// response interceptor
final HttpResponseInterceptor responseInterceptor = request.getResponseInterceptor();
request.setResponseInterceptor(new HttpResponseInterceptor() {
public void interceptResponse(HttpResponse response) throws IOException {
HttpHeaders headers = response.getHeaders();
Preconditions.checkArgument(
SubscriptionHeaders.getSubscriptionId(headers).equals(getSubscriptionId()));
if (response.isSuccessStatusCode()) {
subscription.processResponse(SubscriptionHeaders.getSubscriptionExpires(headers),
SubscriptionHeaders.getTopicId(headers));
subscriptionStore.storeSubscription(subscription);
} else {
subscriptionStore.removeSubscription(subscription);
}
if (responseInterceptor != null) {
responseInterceptor.interceptResponse(response);
}
}
});
return this;
}
/**
* Sets the subscription store and typed notification callback associated with this subscription.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param subscriptionStore subscription store
* @param notificationCallbackClass data class the successful notification will be parsed into or
* {@code Void.class} to ignore the content
* @param typedNotificationCallback typed notification callback
*/
public <N> SubscribeRequest withTypedNotificationCallback(SubscriptionStore subscriptionStore,
Class<N> notificationCallbackClass, TypedNotificationCallback<N> typedNotificationCallback) {
withNotificationCallback(subscriptionStore, typedNotificationCallback);
typedNotificationCallback.setDataType(notificationCallbackClass);
return this;
}
/** Returns the subscribe HTTP request. */
public final HttpRequest getRequest() {
return request;
}
/** Returns the notifications delivery method. */
public final String getNotificationDeliveryMethod() {
return SubscriptionHeaders.getSubscribe(request.getHeaders());
}
/**
* Sets the notifications delivery method.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public SubscribeRequest setNotificationDeliveryMethod(String notificationDeliveryMethod) {
SubscriptionHeaders.setSubscribe(
request.getHeaders(), Preconditions.checkNotNull(notificationDeliveryMethod));
return this;
}
/** Returns the notification callback or {@code null} for none. */
public final NotificationCallback getNotificationCallback() {
return notificationCallback;
}
/** Returns the subscription store or {@code null} for none. */
public final SubscriptionStore getSubscriptionStore() {
return subscriptionStore;
}
/**
* Returns the client token (an opaque string) provided by the client or {@code null} for none.
*/
public String getClientToken() {
return SubscriptionHeaders.getClientToken(request.getHeaders());
}
/**
* Sets the client token (an opaque string) provided by the client or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public SubscribeRequest setClientToken(String clientToken) {
SubscriptionHeaders.setClientToken(request.getHeaders(), clientToken);
return this;
}
/** Returns the subscription UUID provided by the client. */
public String getSubscriptionId() {
return SubscriptionHeaders.getSubscriptionId(request.getHeaders());
}
/**
* Sets the subscription UUID provided by the client.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public SubscribeRequest setSubscriptionId(String subscriptionId) {
SubscriptionHeaders.setSubscriptionId(
request.getHeaders(), Preconditions.checkNotNull(subscriptionId));
return this;
}
/**
* Executes the subscribe request.
*
* @return subscribe response
*/
public SubscribeResponse execute() throws IOException {
HttpResponse response = request.execute();
return new SubscribeResponse(response, subscription);
}
/**
* Queues the subscribe request into the specified batch request container.
*
* <p>
* Batched requests are then executed when {@link BatchRequest#execute()} is called.
* </p>
*
* @param batchRequest batch request container
* @param errorClass data class the unsuccessful response will be parsed into or
* {@code Void.class} to ignore the content
* @param callback batch callback
*/
public final <E> void queue(
BatchRequest batchRequest, Class<E> errorClass, BatchCallback<Void, E> callback)
throws IOException {
batchRequest.queue(request, Void.class, errorClass, callback);
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
import java.io.IOException;
import java.io.Serializable;
/**
* Callback which is used to receive {@link UnparsedNotification}s after subscribing to a topic.
*
* <p>
* Must not be implemented in form of an anonymous class as this will break serialization.
* </p>
*
* <p>
* Should be thread-safe as several notifications might be processed at the same time.
* </p>
*
* <p>
* State will only be persisted once when a subscription is created. All state changes occurring
* during the {@code .handleNotification(..)} call will be lost.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
class MyNotificationCallback extends NotificationCallback {
void handleNotification(
Subscription subscription, UnparsedNotification notification) {
if (notification.getEventType().equals(EventTypes.UPDATED)) {
// add items in the notification to the local client state ...
}
}
}
...
myRequest.subscribe(new MyNotificationCallback()).execute();
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public interface NotificationCallback extends Serializable {
/**
* Handles a received push notification.
*
* @param subscription Subscription to which this notification belongs
* @param notification Notification which was delivered to this application
*/
void handleNotification(Subscription subscription, UnparsedNotification notification)
throws IOException;
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.subscriptions;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import java.io.Serializable;
/**
* Client subscription information after the subscription has been created.
*
* <p>
* Should be stored in a {@link SubscriptionStore}. Implementation is thread safe.
* </p>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class Subscription implements Serializable {
private static final long serialVersionUID = 1L;
/** Notification callback called when a notification is received for this subscription. */
private final NotificationCallback notificationCallback;
/**
* Opaque string provided by the client or {@code null} for none.
*/
private final String clientToken;
/**
* HTTP Date indicating the time at which the subscription will expire or {@code null} for an
* infinite TTL.
*/
private String subscriptionExpires;
/** Subscription UUID. */
private final String subscriptionId;
/** Opaque ID for the subscribed resource that is stable across API versions. */
private String topicId;
/**
* Constructor to be called before making the subscribe request.
*
* @param handler notification handler called when a notification is received for this
* subscription
* @param clientToken opaque string provided by the client or {@code null} for none
* @param subscriptionId subscription UUID
*/
public Subscription(NotificationCallback handler, String clientToken, String subscriptionId) {
this.notificationCallback = Preconditions.checkNotNull(handler);
this.clientToken = clientToken;
this.subscriptionId = Preconditions.checkNotNull(subscriptionId);
}
/**
* Process subscribe response.
*
* @param subscriptionExpires HTTP Date indicating the time at which the subscription will expire
* or {@code null} for an infinite TTL
* @param topicId opaque ID for the subscribed resource that is stable across API versions
*/
public Subscription processResponse(String subscriptionExpires, String topicId) {
this.subscriptionExpires = subscriptionExpires;
this.topicId = Preconditions.checkNotNull(topicId);
return this;
}
/**
* Returns the notification callback called when a notification is received for this subscription.
*/
public NotificationCallback getNotificationCallback() {
return notificationCallback;
}
/**
* Returns the Opaque string provided by the client or {@code null} for none.
*/
public String getClientToken() {
return clientToken;
}
/**
* Returns the HTTP Date indicating the time at which the subscription will expire or {@code null}
* for an infinite TTL.
*/
public String getSubscriptionExpires() {
return subscriptionExpires;
}
/** Returns the subscription UUID. */
public String getSubscriptionId() {
return subscriptionId;
}
/** Returns the opaque ID for the subscribed resource that is stable across API versions. */
public String getTopicId() {
return topicId;
}
@Override
public String toString() {
return Objects.toStringHelper(Subscription.class)
.add("notificationCallback", notificationCallback).add("clientToken", clientToken)
.add("subscriptionExpires", subscriptionExpires).add("subscriptionID", subscriptionId)
.add("topicID", topicId).toString();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Subscription)) {
return false;
}
Subscription o = (Subscription) other;
return subscriptionId.equals(o.subscriptionId);
}
@Override
public int hashCode() {
return subscriptionId.hashCode();
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis.xml.atom;
import com.google.api.client.util.ArrayMap;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.Data;
import com.google.api.client.util.FieldInfo;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Types;
import java.util.Collection;
import java.util.Map;
import java.util.TreeSet;
/**
* Utilities for working with the Atom XML of Google Data APIs.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class GoogleAtom {
/**
* GData namespace.
*
* @since 1.0
*/
public static final String GD_NAMESPACE = "http://schemas.google.com/g/2005";
/**
* Content type used on an error formatted in XML.
*
* @since 1.5
*/
public static final String ERROR_CONTENT_TYPE = "application/vnd.google.gdata.error+xml";
// TODO(yanivi): require XmlNamespaceDictory and include xmlns declarations since there is no
// guarantee that there is a match between Google's mapping and the one used by client
/**
* Returns the fields mask to use for the given data class of key/value pairs. It cannot be a
* {@link Map}, {@link GenericData} or a {@link Collection}.
*
* @param dataClass data class of key/value pairs
*/
public static String getFieldsFor(Class<?> dataClass) {
StringBuilder fieldsBuf = new StringBuilder();
appendFieldsFor(fieldsBuf, dataClass, new int[1]);
return fieldsBuf.toString();
}
/**
* Returns the fields mask to use for the given data class of key/value pairs for the feed class
* and for the entry class. This should only be used if the feed class does not contain the entry
* class as a field. The data classes cannot be a {@link Map}, {@link GenericData} or a
* {@link Collection}.
*
* @param feedClass feed data class
* @param entryClass entry data class
*/
public static String getFeedFields(Class<?> feedClass, Class<?> entryClass) {
StringBuilder fieldsBuf = new StringBuilder();
appendFeedFields(fieldsBuf, feedClass, entryClass);
return fieldsBuf.toString();
}
private static void appendFieldsFor(
StringBuilder fieldsBuf, Class<?> dataClass, int[] numFields) {
if (Map.class.isAssignableFrom(dataClass) || Collection.class.isAssignableFrom(dataClass)) {
throw new IllegalArgumentException(
"cannot specify field mask for a Map or Collection class: " + dataClass);
}
ClassInfo classInfo = ClassInfo.of(dataClass);
for (String name : new TreeSet<String>(classInfo.getNames())) {
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo.isFinal()) {
continue;
}
if (++numFields[0] != 1) {
fieldsBuf.append(',');
}
fieldsBuf.append(name);
// TODO(yanivi): handle Java arrays?
Class<?> fieldClass = fieldInfo.getType();
if (Collection.class.isAssignableFrom(fieldClass)) {
// TODO(yanivi): handle Java collection of Java collection or Java map?
fieldClass = (Class<?>) Types.getIterableParameter(fieldInfo.getField().getGenericType());
}
// TODO(yanivi): implement support for map when server implements support for *:*
if (fieldClass != null) {
if (fieldInfo.isPrimitive()) {
if (name.charAt(0) != '@' && !name.equals("text()")) {
// TODO(yanivi): wait for bug fix from server to support text() -- already fixed???
// buf.append("/text()");
}
} else if (!Collection.class.isAssignableFrom(fieldClass)
&& !Map.class.isAssignableFrom(fieldClass)) {
int[] subNumFields = new int[1];
int openParenIndex = fieldsBuf.length();
fieldsBuf.append('(');
// TODO(yanivi): abort if found cycle to avoid infinite loop
appendFieldsFor(fieldsBuf, fieldClass, subNumFields);
updateFieldsBasedOnNumFields(fieldsBuf, openParenIndex, subNumFields[0]);
}
}
}
}
private static void appendFeedFields(
StringBuilder fieldsBuf, Class<?> feedClass, Class<?> entryClass) {
int[] numFields = new int[1];
appendFieldsFor(fieldsBuf, feedClass, numFields);
if (numFields[0] != 0) {
fieldsBuf.append(",");
}
fieldsBuf.append("entry(");
int openParenIndex = fieldsBuf.length() - 1;
numFields[0] = 0;
appendFieldsFor(fieldsBuf, entryClass, numFields);
updateFieldsBasedOnNumFields(fieldsBuf, openParenIndex, numFields[0]);
}
private static void updateFieldsBasedOnNumFields(
StringBuilder fieldsBuf, int openParenIndex, int numFields) {
switch (numFields) {
case 0:
fieldsBuf.deleteCharAt(openParenIndex);
break;
case 1:
fieldsBuf.setCharAt(openParenIndex, '/');
break;
default:
fieldsBuf.append(')');
}
}
/**
* Compute the patch object of key/value pairs from the given original and patched objects, adding
* a {@code @gd:fields} key for the fields mask.
*
* @param patched patched object
* @param original original object
* @return patch object of key/value pairs
*/
public static Map<String, Object> computePatch(Object patched, Object original) {
FieldsMask fieldsMask = new FieldsMask();
ArrayMap<String, Object> result = computePatchInternal(fieldsMask, patched, original);
if (fieldsMask.numDifferences != 0) {
result.put("@gd:fields", fieldsMask.buf.toString());
}
return result;
}
private static ArrayMap<String, Object> computePatchInternal(
FieldsMask fieldsMask, Object patchedObject, Object originalObject) {
ArrayMap<String, Object> result = ArrayMap.create();
Map<String, Object> patchedMap = Data.mapOf(patchedObject);
Map<String, Object> originalMap = Data.mapOf(originalObject);
TreeSet<String> fieldNames = new TreeSet<String>();
fieldNames.addAll(patchedMap.keySet());
fieldNames.addAll(originalMap.keySet());
for (String name : fieldNames) {
Object originalValue = originalMap.get(name);
Object patchedValue = patchedMap.get(name);
if (originalValue == patchedValue) {
continue;
}
Class<?> type = originalValue == null ? patchedValue.getClass() : originalValue.getClass();
if (Data.isPrimitive(type)) {
if (originalValue != null && originalValue.equals(patchedValue)) {
continue;
}
fieldsMask.append(name);
// TODO(yanivi): wait for bug fix from server
// if (!name.equals("text()") && name.charAt(0) != '@') {
// fieldsMask.buf.append("/text()");
// }
if (patchedValue != null) {
result.add(name, patchedValue);
}
} else if (Collection.class.isAssignableFrom(type)) {
if (originalValue != null && patchedValue != null) {
@SuppressWarnings("unchecked")
Collection<Object> originalCollection = (Collection<Object>) originalValue;
@SuppressWarnings("unchecked")
Collection<Object> patchedCollection = (Collection<Object>) patchedValue;
int size = originalCollection.size();
if (size == patchedCollection.size()) {
int i;
for (i = 0; i < size; i++) {
FieldsMask subFieldsMask = new FieldsMask();
computePatchInternal(subFieldsMask, patchedValue, originalValue);
if (subFieldsMask.numDifferences != 0) {
break;
}
}
if (i == size) {
continue;
}
}
}
// TODO(yanivi): implement
throw new UnsupportedOperationException(
"not yet implemented: support for patching collections");
} else {
if (originalValue == null) { // TODO(yanivi): test
fieldsMask.append(name);
result.add(name, Data.mapOf(patchedValue));
} else if (patchedValue == null) { // TODO(yanivi): test
fieldsMask.append(name);
} else {
FieldsMask subFieldsMask = new FieldsMask();
ArrayMap<String, Object> patch =
computePatchInternal(subFieldsMask, patchedValue, originalValue);
int numDifferences = subFieldsMask.numDifferences;
if (numDifferences != 0) {
fieldsMask.append(name, subFieldsMask);
result.add(name, patch);
}
}
}
}
return result;
}
static class FieldsMask {
int numDifferences;
StringBuilder buf = new StringBuilder();
void append(String name) {
StringBuilder buf = this.buf;
if (++numDifferences != 1) {
buf.append(',');
}
buf.append(name);
}
void append(String name, FieldsMask subFields) {
append(name);
StringBuilder buf = this.buf;
boolean isSingle = subFields.numDifferences == 1;
if (isSingle) {
buf.append('/');
} else {
buf.append('(');
}
buf.append(subFields.buf);
if (!isSingle) {
buf.append(')');
}
}
}
private GoogleAtom() {
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.
*/
/**
* Utilities for Google's Atom XML implementation (see detailed package specification).
*
* <h2>Package Specification</h2>
*
* <p>
* User-defined Partial XML data models allow you to defined Plain Old Java Objects (POJO's) to
* define how the library should parse/serialize XML. Each field that should be included must have
* an @{@link com.google.api.client.util.Key} annotation. The field can be of any visibility
* (private, package private, protected, or public) and must not be static.
* </p>
*
* <p>
* The optional value parameter of this @{@link com.google.api.client.util.Key} annotation specifies
* the XPath name to use to represent the field. For example, an XML attribute <code>a</code> has an
* XPath name of <code>@a</code>, an XML element <code><a></code> has an XPath name of <code>
* a</code>, and an XML text content has an XPath name of <code>text()</code>. These are named based
* on their usage with the <a
* href="http://code.google.com/apis/gdata/docs/2.0/reference.html#PartialResponse">partial
* response/update syntax</a> for Google API's. If the @{@link com.google.api.client.util.Key}
* annotation is missing, the default is to use the Atom XML namespace and the Java field's name as
* the local XML name. By default, the field name is used as the JSON key. Any unrecognized XML is
* normally simply ignored and not stored. If the ability to store unknown keys is important, use
* {@link com.google.api.client.xml.GenericXml}.
* </p>
*
* <p>
* Let's take a look at a typical partial Atom XML album feed from the Picasa Web Albums Data API:
* </p>
*
* <pre><code>
<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/'
xmlns:gphoto='http://schemas.google.com/photos/2007'>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://picasaweb.google.com/data/feed/api/user/liz' />
<author>
<name>Liz</name>
</author>
<openSearch:totalResults>1</openSearch:totalResults>
<entry gd:etag='"RXY8fjVSLyp7ImA9WxVVGE8KQAE."'>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/photos/2007#album' />
<title>lolcats</title>
<summary>Hilarious Felines</summary>
<gphoto:access>public</gphoto:access>
</entry>
</feed>
</code></pre>
*
* <p>
* Here's one possible way to design the Java data classes for this (each class in its own Java
* file):
* </p>
*
* <pre><code>
import com.google.api.client.util.*;
import java.util.List;
public class Link {
@Key("@href")
public String href;
@Key("@rel")
public String rel;
public static String find(List<Link> links, String rel) {
if (links != null) {
for (Link link : links) {
if (rel.equals(link.rel)) {
return link.href;
}
}
}
return null;
}
}
public class Category {
@Key("@scheme")
public String scheme;
@Key("@term")
public String term;
public static Category newKind(String kind) {
Category category = new Category();
category.scheme = "http://schemas.google.com/g/2005#kind";
category.term = "http://schemas.google.com/photos/2007#" + kind;
return category;
}
}
public class AlbumEntry {
@Key
public String summary;
@Key
public String title;
@Key("gphoto:access")
public String access;
public Category category = newKind("album");
private String getEditLink() {
return Link.find(links, "edit");
}
}
public class Author {
@Key
public String name;
}
public class AlbumFeed {
@Key
public Author author;
@Key("openSearch:totalResults")
public int totalResults;
@Key("entry")
public List<AlbumEntry> photos;
@Key("link")
public List<Link> links;
private String getPostLink() {
return Link.find(links, "http://schemas.google.com/g/2005#post");
}
}
</code></pre>
*
* <p>
* You can also use the @{@link com.google.api.client.util.Key} annotation to defined query
* parameters for a URL. For example:
* </p>
*
* <pre><code>
public class PicasaUrl extends GoogleUrl {
@Key("max-results")
public Integer maxResults;
@Key
public String kinds;
public PicasaUrl(String url) {
super(url);
}
public static PicasaUrl fromRelativePath(String relativePath) {
PicasaUrl result = new PicasaUrl(PicasaWebAlbums.ROOT_URL);
result.path += relativePath;
return result;
}
}
</code></pre>
*
* <p>
* To work with a Google API, you first need to set up the
* {@link com.google.api.client.http.HttpTransport}. For example:
* </p>
*
* <pre><code>
private static HttpTransport setUpTransport() throws IOException {
HttpTransport result = new NetHttpTransport();
GoogleUtils.useMethodOverride(result);
HttpHeaders headers = new HttpHeaders();
headers.setApplicationName("Google-PicasaSample/1.0");
headers.gdataVersion = "2";
AtomParser parser = new AtomParser();
parser.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY;
transport.addParser(parser);
// insert authentication code...
return transport;
}
</code></pre>
*
* <p>
* Now that we have a transport, we can execute a partial GET request to the Picasa Web Albums API
* and parse the result:
* </p>
*
* <pre><code>
public static AlbumFeed executeGet(HttpTransport transport, PicasaUrl url)
throws IOException {
url.fields = GoogleAtom.getFieldsFor(AlbumFeed.class);
url.kinds = "photo";
url.maxResults = 5;
HttpRequest request = transport.buildGetRequest();
request.url = url;
return request.execute().parseAs(AlbumFeed.class);
}
</code></pre>
*
* <p>
* If the server responds with an error the {@link com.google.api.client.http.HttpRequest#execute}
* method will throw an {@link com.google.api.client.http.HttpResponseException}, which has an
* {@link com.google.api.client.http.HttpResponse} field which can be parsed the same way as a
* success response inside of a catch block. For example:
* </p>
*
* <pre><code>
try {
...
} catch (HttpResponseException e) {
if (e.response.getParser() != null) {
Error error = e.response.parseAs(Error.class);
// process error response
} else {
String errorContentString = e.response.parseAsString();
// process error response as string
}
throw e;
}
</code></pre>
*
* <p>
* To update an album, we use the transport to execute an efficient partial update request using the
* PATCH method to the Picasa Web Albums API:
* </p>
*
* <pre><code>
public AlbumEntry executePatchRelativeToOriginal(HttpTransport transport,
AlbumEntry original) throws IOException {
HttpRequest request = transport.buildPatchRequest();
request.setUrl(getEditLink());
request.headers.ifMatch = etag;
AtomPatchRelativeToOriginalContent content =
new AtomPatchRelativeToOriginalContent();
content.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY;
content.originalEntry = original;
content.patchedEntry = this;
request.content = content;
return request.execute().parseAs(AlbumEntry.class);
}
private static AlbumEntry updateTitle(HttpTransport transport,
AlbumEntry album) throws IOException {
AlbumEntry patched = album.clone();
patched.title = "An alternate title";
return patched.executePatchRelativeToOriginal(transport, album);
}
</code></pre>
*
* <p>
* To insert an album, we use the transport to execute a POST request to the Picasa Web Albums API:
* </p>
*
* <pre><code>
public AlbumEntry insertAlbum(HttpTransport transport, AlbumEntry entry)
throws IOException {
HttpRequest request = transport.buildPostRequest();
request.setUrl(getPostLink());
AtomContent content = new AtomContent();
content.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY;
content.entry = entry;
request.content = content;
return request.execute().parseAs(AlbumEntry.class);
}
</code></pre>
*
* <p>
* To delete an album, we use the transport to execute a DELETE request to the Picasa Web Albums
* API:
* </p>
*
* <pre><code>
public void executeDelete(HttpTransport transport) throws IOException {
HttpRequest request = transport.buildDeleteRequest();
request.setUrl(getEditLink());
request.headers.ifMatch = etag;
request.execute().ignore();
}
</code></pre>
*
* <p>
* NOTE: As you might guess, the library uses reflection to populate the user-defined data model.
* It's not quite as fast as writing the wire format parsing code yourself can potentially be, but
* it's a lot easier.
* </p>
*
* <p>
* NOTE: If you prefer to use your favorite XML parsing library instead (there are many of them),
* that's supported as well. Just call {@link com.google.api.client.http.HttpRequest#execute()} and
* parse the returned byte stream.
* </p>
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.xml.atom;
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis.xml.atom;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.xml.AbstractXmlHttpContent;
import com.google.api.client.xml.XmlNamespaceDictionary;
import com.google.api.client.xml.atom.Atom;
import com.google.common.base.Preconditions;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.util.Map;
/**
* Serializes an optimal Atom XML PATCH HTTP content based on the data key/value mapping object for
* an Atom entry, by comparing the original value to the patched value.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
* <code>
static void setContent(HttpRequest request, XmlNamespaceDictionary namespaceDictionary,
Object originalEntry, Object patchedEntry) {
request.setContent(
new AtomPatchRelativeToOriginalContent(namespaceDictionary, originalEntry, patchedEntry));
}
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AtomPatchRelativeToOriginalContent extends AbstractXmlHttpContent {
/** Key/value pair data for the updated/patched Atom entry. */
private final Object patchedEntry;
/** Key/value pair data for the original unmodified Atom entry. */
private final Object originalEntry;
/**
* @param namespaceDictionary XML namespace dictionary
* @since 1.5
*/
public AtomPatchRelativeToOriginalContent(
XmlNamespaceDictionary namespaceDictionary, Object originalEntry, Object patchedEntry) {
super(namespaceDictionary);
this.originalEntry = Preconditions.checkNotNull(originalEntry);
this.patchedEntry = Preconditions.checkNotNull(patchedEntry);
}
@Override
protected void writeTo(XmlSerializer serializer) throws IOException {
Map<String, Object> patch = GoogleAtom.computePatch(patchedEntry, originalEntry);
getNamespaceDictionary().serialize(serializer, Atom.ATOM_NAMESPACE, "entry", patch);
}
@Override
public AtomPatchRelativeToOriginalContent setMediaType(HttpMediaType mediaType) {
super.setMediaType(mediaType);
return this;
}
/**
* Returns the data key name/value pairs for the updated/patched Atom entry.
*
* @since 1.5
*/
public final Object getPatchedEntry() {
return patchedEntry;
}
/**
* Returns the data key name/value pairs for the original unmodified Atom entry.
*
* @since 1.5
*/
public final Object getOriginalEntry() {
return originalEntry;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis.xml.atom;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.xml.atom.AtomContent;
import com.google.api.client.xml.Xml;
import com.google.api.client.xml.XmlNamespaceDictionary;
/**
* Serializes Atom XML PATCH HTTP content based on the data key/value mapping object for an Atom
* entry.
*
* <p>
* Default value for {@link #getType()} is {@link Xml#MEDIA_TYPE}.
* </p>
*
* <p>
* Sample usage:
* </p>
*
* <pre>
*<code>
static void setContent(
HttpRequest request, XmlNamespaceDictionary namespaceDictionary, Object patchEntry) {
request.setContent(new AtomPatchContent(namespaceDictionary, patchEntry));
}
* </code>
* </pre>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AtomPatchContent extends AtomContent {
/**
* @param namespaceDictionary XML namespace dictionary
* @param patchEntry key/value pair data for the Atom PATCH entry
* @since 1.5
*/
public AtomPatchContent(XmlNamespaceDictionary namespaceDictionary, Object patchEntry) {
super(namespaceDictionary, patchEntry, true);
setMediaType(new HttpMediaType(Xml.MEDIA_TYPE));
}
@Override
public AtomPatchContent setMediaType(HttpMediaType mediaType) {
super.setMediaType(mediaType);
return this;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis.xml.atom;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.FieldInfo;
import com.google.api.client.util.Types;
import com.google.api.client.xml.Xml;
import com.google.api.client.xml.XmlNamespaceDictionary;
import com.google.api.client.xml.atom.AbstractAtomFeedParser;
import com.google.api.client.xml.atom.Atom;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
/**
* GData Atom feed pull parser when the entry class can be computed from the kind.
*
* @param <T> feed type
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class MultiKindFeedParser<T> extends AbstractAtomFeedParser<T> {
private final HashMap<String, Class<?>> kindToEntryClassMap = new HashMap<String, Class<?>>();
/**
* @param namespaceDictionary XML namespace dictionary
* @param parser XML pull parser to use
* @param inputStream input stream to read
* @param feedClass feed class to parse
*/
MultiKindFeedParser(XmlNamespaceDictionary namespaceDictionary, XmlPullParser parser,
InputStream inputStream, Class<T> feedClass) {
super(namespaceDictionary, parser, inputStream, feedClass);
}
/** Sets the entry classes to use when parsing. */
public void setEntryClasses(Class<?>... entryClasses) {
int numEntries = entryClasses.length;
HashMap<String, Class<?>> kindToEntryClassMap = this.kindToEntryClassMap;
for (int i = 0; i < numEntries; i++) {
Class<?> entryClass = entryClasses[i];
ClassInfo typeInfo = ClassInfo.of(entryClass);
Field field = typeInfo.getField("@gd:kind");
if (field == null) {
throw new IllegalArgumentException("missing @gd:kind field for " + entryClass.getName());
}
Object entry = Types.newInstance(entryClass);
String kind = (String) FieldInfo.getFieldValue(field, entry);
if (kind == null) {
throw new IllegalArgumentException(
"missing value for @gd:kind field in " + entryClass.getName());
}
kindToEntryClassMap.put(kind, entryClass);
}
}
@Override
protected Object parseEntryInternal() throws IOException, XmlPullParserException {
XmlPullParser parser = getParser();
String kind = parser.getAttributeValue(GoogleAtom.GD_NAMESPACE, "kind");
Class<?> entryClass = this.kindToEntryClassMap.get(kind);
if (entryClass == null) {
throw new IllegalArgumentException("unrecognized kind: " + kind);
}
Object result = Types.newInstance(entryClass);
Xml.parseElement(parser, result, getNamespaceDictionary(), null);
return result;
}
/**
* Parses the given HTTP response using the given feed class and entry classes.
*
* @param <T> feed type
* @param <E> entry type
* @param response HTTP response
* @param namespaceDictionary XML namespace dictionary
* @param feedClass feed class
* @param entryClasses entry class
* @return Atom multi-kind feed pull parser
* @throws IOException I/O exception
* @throws XmlPullParserException XML pull parser exception
*/
public static <T, E> MultiKindFeedParser<T> create(HttpResponse response,
XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<E>... entryClasses)
throws IOException, XmlPullParserException {
InputStream content = response.getContent();
try {
Atom.checkContentType(response.getContentType());
XmlPullParser parser = Xml.createParser();
parser.setInput(content, null);
MultiKindFeedParser<T> result =
new MultiKindFeedParser<T>(namespaceDictionary, parser, content, feedClass);
result.setEntryClasses(entryClasses);
return result;
} finally {
content.close();
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.
*/
/**
* Media for Google API's.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.9
* @author Ravi Mistry
*/
package com.google.api.client.googleapis.media;
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.media;
import com.google.api.client.googleapis.MethodOverride;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpMethods;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.http.MultipartRelatedContent;
import com.google.common.base.Preconditions;
import com.google.common.io.LimitInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Media HTTP Uploader, with support for both direct and resumable media uploads. Documentation is
* available <a href='http://code.google.com/p/google-api-java-client/wiki/MediaUpload'>here</a>.
*
* <p>
* For resumable uploads, when the media content length is known, if the provided
* {@link InputStream} has {@link InputStream#markSupported} as {@code false} then it is wrapped in
* an {@link BufferedInputStream} to support the {@link InputStream#mark} and
* {@link InputStream#reset} methods required for handling server errors. If the media content
* length is unknown then each chunk is stored temporarily in memory. This is required to determine
* when the last chunk is reached.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.9
*
* @author rmistry@google.com (Ravi Mistry)
*/
@SuppressWarnings("deprecation")
public final class MediaHttpUploader {
/**
* Upload content type header.
*
* @since 1.13
*/
public static final String CONTENT_LENGTH_HEADER = "X-Upload-Content-Length";
/**
* Upload content length header.
*
* @since 1.13
*/
public static final String CONTENT_TYPE_HEADER = "X-Upload-Content-Type";
/**
* Upload state associated with the Media HTTP uploader.
*/
public enum UploadState {
/** The upload process has not started yet. */
NOT_STARTED,
/** Set before the initiation request is sent. */
INITIATION_STARTED,
/** Set after the initiation request completes. */
INITIATION_COMPLETE,
/** Set after a media file chunk is uploaded. */
MEDIA_IN_PROGRESS,
/** Set after the complete media file is successfully uploaded. */
MEDIA_COMPLETE
}
/** The current state of the uploader. */
private UploadState uploadState = UploadState.NOT_STARTED;
static final int MB = 0x100000;
private static final int KB = 0x400;
/**
* Minimum number of bytes that can be uploaded to the server (set to 256KB).
*/
public static final int MINIMUM_CHUNK_SIZE = 256 * KB;
/**
* Default maximum number of bytes that will be uploaded to the server in any single HTTP request
* (set to 10 MB).
*/
public static final int DEFAULT_CHUNK_SIZE = 10 * MB;
/** The HTTP content of the media to be uploaded. */
private final AbstractInputStreamContent mediaContent;
/** The request factory for connections to the server. */
private final HttpRequestFactory requestFactory;
/** The transport to use for requests. */
private final HttpTransport transport;
/** HTTP content metadata of the media to be uploaded or {@code null} for none. */
private HttpContent metadata;
/**
* The length of the HTTP media content.
*
* <p>
* {@code 0} before it is lazily initialized in {@link #getMediaContentLength()} after which it
* could still be {@code 0} for empty media content. Will be {@code < 0} if the media content
* length has not been specified.
* </p>
*/
private long mediaContentLength;
/**
* Determines if media content length has been calculated yet in {@link #getMediaContentLength()}.
*/
private boolean isMediaContentLengthCalculated;
/**
* The HTTP method used for the initiation request.
*
* <p>
* Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media
* update). The default value is {@link HttpMethods#POST}.
* </p>
*/
private String initiationRequestMethod = HttpMethods.POST;
/** The HTTP headers used in the initiation request. */
private HttpHeaders initiationHeaders = new HttpHeaders();
/**
* The HTTP request object that is currently used to send upload requests or {@code null} before
* {@link #upload}.
*/
private HttpRequest currentRequest;
/** An Input stream of the HTTP media content or {@code null} before {@link #upload}. */
private InputStream contentInputStream;
/**
* Determines whether the back off policy is enabled or disabled. If value is set to {@code false}
* then server errors are not handled and the upload process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
private boolean backOffPolicyEnabled = true;
/**
* Determines whether direct media upload is enabled or disabled. If value is set to {@code true}
* then a direct upload will be done where the whole media content is uploaded in a single request
* If value is set to {@code false} then the upload uses the resumable media upload protocol to
* upload in data chunks. Defaults to {@code false}.
*/
private boolean directUploadEnabled;
/**
* Progress listener to send progress notifications to or {@code null} for none.
*/
private MediaHttpUploaderProgressListener progressListener;
/**
* The total number of bytes uploaded by this uploader. This value will not be calculated for
* direct uploads when the content length is not known in advance.
*/
// TODO(rmistry): Figure out a way to compute the content length using CountingInputStream.
private long bytesUploaded;
/**
* Maximum size of individual chunks that will get uploaded by single HTTP requests. The default
* value is {@link #DEFAULT_CHUNK_SIZE}.
*/
private int chunkSize = DEFAULT_CHUNK_SIZE;
/**
* Used to cache a single byte when the media content length is unknown or {@code null} for none.
*/
private Byte cachedByte;
/**
* The content buffer of the current request or {@code null} for none. It is used for resumable
* media upload when the media content length is not specified. It is instantiated for every
* request in {@link #setContentAndHeadersOnCurrentRequest} and is set to {@code null} when the
* request is completed in {@link #upload}.
*/
private byte currentRequestContentBuffer[];
/**
* Whether to disable GZip compression of HTTP content.
*
* <p>
* The default value is {@code false}.
* </p>
*/
private boolean disableGZipContent;
/**
* Construct the {@link MediaHttpUploader}.
*
* <p>
* The input stream received by calling {@link AbstractInputStreamContent#getInputStream} is
* closed when the upload process is successfully completed. For resumable uploads, when the
* media content length is known, if the input stream has {@link InputStream#markSupported} as
* {@code false} then it is wrapped in an {@link BufferedInputStream} to support the
* {@link InputStream#mark} and {@link InputStream#reset} methods required for handling server
* errors. If the media content length is unknown then each chunk is stored temporarily in memory.
* This is required to determine when the last chunk is reached.
* </p>
*
* @param mediaContent The Input stream content of the media to be uploaded
* @param transport The transport to use for requests
* @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or
* {@code null} for none
*/
public MediaHttpUploader(AbstractInputStreamContent mediaContent, HttpTransport transport,
HttpRequestInitializer httpRequestInitializer) {
this.mediaContent = Preconditions.checkNotNull(mediaContent);
this.transport = Preconditions.checkNotNull(transport);
this.requestFactory = httpRequestInitializer == null
? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer);
}
/**
* Executes a direct media upload or resumable media upload conforming to the specifications
* listed <a href='http://code.google.com/apis/gdata/docs/resumable_upload.html'>here.</a>
*
* <p>
* This method is not reentrant. A new instance of {@link MediaHttpUploader} must be instantiated
* before upload called be called again.
* </p>
*
* <p>
* If an error is encountered during the request execution the caller is responsible for parsing
* the response correctly. For example for JSON errors:
*
* <pre>
if (!response.isSuccessStatusCode()) {
throw GoogleJsonResponseException.from(jsonFactory, response);
}
* </pre>
* </p>
*
* <p>
* Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is
* no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the
* response stream is properly closed. Example usage:
* </p>
*
* <pre>
HttpResponse response = batch.upload(initiationRequestUrl);
try {
// process the HTTP response object
} finally {
response.disconnect();
}
* </pre>
*
* @param initiationRequestUrl The request URL where the initiation request will be sent
* @return HTTP response
*/
public HttpResponse upload(GenericUrl initiationRequestUrl) throws IOException {
Preconditions.checkArgument(uploadState == UploadState.NOT_STARTED);
if (directUploadEnabled) {
updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS);
HttpContent content = mediaContent;
if (metadata != null) {
content = new MultipartRelatedContent(metadata, mediaContent);
initiationRequestUrl.put("uploadType", "multipart");
} else {
initiationRequestUrl.put("uploadType", "media");
}
HttpRequest request =
requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content);
request.getHeaders().putAll(initiationHeaders);
request.setThrowExceptionOnExecuteError(false);
request.setEnableGZipContent(!disableGZipContent);
addMethodOverride(request);
// We do not have to do anything special here if media content length is unspecified because
// direct media upload works even when the media content length == -1.
HttpResponse response = request.execute();
boolean responseProcessed = false;
try {
if (getMediaContentLength() >= 0) {
bytesUploaded = getMediaContentLength();
}
updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE);
responseProcessed = true;
} finally {
if (!responseProcessed) {
response.disconnect();
}
}
return response;
}
// Make initial request to get the unique upload URL.
HttpResponse initialResponse = executeUploadInitiation(initiationRequestUrl);
if (!initialResponse.isSuccessStatusCode()) {
// If the initiation request is not successful return it immediately.
return initialResponse;
}
GenericUrl uploadUrl;
try {
uploadUrl = new GenericUrl(initialResponse.getHeaders().getLocation());
} finally {
initialResponse.disconnect();
}
// Convert media content into a byte stream to upload in chunks.
contentInputStream = mediaContent.getInputStream();
if (!contentInputStream.markSupported() && getMediaContentLength() >= 0) {
// If we know the media content length then wrap the stream into a Buffered input stream to
// support the {@link InputStream#mark} and {@link InputStream#reset} methods required for
// handling server errors.
contentInputStream = new BufferedInputStream(contentInputStream);
}
HttpResponse response;
// Upload the media content in chunks.
while (true) {
currentRequest = requestFactory.buildPutRequest(uploadUrl, null);
addMethodOverride(currentRequest); // needed for PUT
setContentAndHeadersOnCurrentRequest(bytesUploaded);
if (backOffPolicyEnabled) {
// Set MediaExponentialBackOffPolicy as the BackOffPolicy of the HTTP Request which will
// callback to this instance if there is a server error.
currentRequest.setBackOffPolicy(new MediaUploadExponentialBackOffPolicy(this));
}
currentRequest.setThrowExceptionOnExecuteError(false);
currentRequest.setRetryOnExecuteIOException(true);
currentRequest.setEnableGZipContent(!disableGZipContent);
response = currentRequest.execute();
boolean returningResponse = false;
try {
if (response.isSuccessStatusCode()) {
bytesUploaded = getMediaContentLength();
contentInputStream.close();
updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE);
returningResponse = true;
return response;
}
if (response.getStatusCode() != 308) {
returningResponse = true;
return response;
}
// Check to see if the upload URL has changed on the server.
String updatedUploadUrl = response.getHeaders().getLocation();
if (updatedUploadUrl != null) {
uploadUrl = new GenericUrl(updatedUploadUrl);
}
bytesUploaded = getNextByteIndex(response.getHeaders().getRange());
currentRequestContentBuffer = null;
updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS);
} finally {
if (!returningResponse) {
response.disconnect();
}
}
}
}
/**
* Uses lazy initialization to compute the media content length.
*
* <p>
* This is done to avoid throwing an {@link IOException} in the constructor.
* </p>
*/
private long getMediaContentLength() throws IOException {
if (!isMediaContentLengthCalculated) {
mediaContentLength = mediaContent.getLength();
isMediaContentLengthCalculated = true;
}
return mediaContentLength;
}
/**
* This method sends a POST request with empty content to get the unique upload URL.
*
* @param initiationRequestUrl The request URL where the initiation request will be sent
*/
private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException {
updateStateAndNotifyListener(UploadState.INITIATION_STARTED);
initiationRequestUrl.put("uploadType", "resumable");
HttpContent content = metadata == null ? new EmptyContent() : metadata;
HttpRequest request =
requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content);
addMethodOverride(request);
initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType());
if (getMediaContentLength() >= 0) {
initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength());
}
request.getHeaders().putAll(initiationHeaders);
request.setThrowExceptionOnExecuteError(false);
request.setRetryOnExecuteIOException(true);
request.setEnableGZipContent(!disableGZipContent);
HttpResponse response = request.execute();
boolean notificationCompleted = false;
try {
updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE);
notificationCompleted = true;
} finally {
if (!notificationCompleted) {
response.disconnect();
}
}
return response;
}
/**
* Wraps PUT HTTP requests inside of a POST request and uses {@link MethodOverride#HEADER} header
* to specify the actual HTTP method. This is done in case the HTTP transport does not support
* PUT.
*
* @param request HTTP request
*/
private void addMethodOverride(HttpRequest request) throws IOException {
new MethodOverride().intercept(request);
}
/**
* Sets the HTTP media content chunk and the required headers that should be used in the upload
* request.
*
* @param bytesWritten The number of bytes that have been successfully uploaded on the server
*/
private void setContentAndHeadersOnCurrentRequest(long bytesWritten) throws IOException {
int blockSize;
if (getMediaContentLength() >= 0) {
// We know exactly what the blockSize will be because we know the media content length.
blockSize = (int) Math.min(chunkSize, getMediaContentLength() - bytesWritten);
} else {
// Use the chunkSize as the blockSize because we do know what what it is yet.
blockSize = chunkSize;
}
AbstractInputStreamContent contentChunk;
int actualBlockSize = blockSize;
String mediaContentLengthStr;
if (getMediaContentLength() >= 0) {
// Mark the current position in case we need to retry the request.
contentInputStream.mark(blockSize);
// TODO(rmistry): Add tests for LimitInputStream.
InputStream limitInputStream = new LimitInputStream(contentInputStream, blockSize);
contentChunk = new InputStreamContent(mediaContent.getType(), limitInputStream)
.setRetrySupported(true)
.setLength(blockSize)
.setCloseInputStream(false);
mediaContentLengthStr = String.valueOf(getMediaContentLength());
} else {
// If the media content length is not known we implement a custom buffered input stream that
// enables us to detect the length of the media content when the last chunk is sent. We
// accomplish this by always trying to read an extra byte further than the end of the current
// chunk.
int actualBytesRead;
int bytesAllowedToRead;
int contentBufferStartIndex = 0;
if (currentRequestContentBuffer == null) {
bytesAllowedToRead = cachedByte == null ? blockSize + 1 : blockSize;
InputStream limitInputStream = new LimitInputStream(contentInputStream, bytesAllowedToRead);
currentRequestContentBuffer = new byte[blockSize + 1];
if (cachedByte != null) {
currentRequestContentBuffer[0] = cachedByte;
}
actualBytesRead = limitInputStream.read(currentRequestContentBuffer, blockSize + 1 -
bytesAllowedToRead, bytesAllowedToRead);
} else {
// currentRequestContentBuffer is not null that means this is a request to recover from a
// server error. The new request will be constructed from the previous request's byte
// buffer.
bytesAllowedToRead = (int) (chunkSize - (bytesWritten - bytesUploaded) + 1);
contentBufferStartIndex = (int) (bytesWritten - bytesUploaded);
actualBytesRead = bytesAllowedToRead;
}
if (actualBytesRead < bytesAllowedToRead) {
actualBlockSize = Math.max(0, actualBytesRead);
if (cachedByte != null) {
actualBlockSize++;
}
// At this point we know we reached the media content length because we either read less
// than the specified chunk size or there is no more data left to be read.
mediaContentLengthStr = String.valueOf(bytesWritten + actualBlockSize);
} else {
cachedByte = currentRequestContentBuffer[blockSize];
mediaContentLengthStr = "*";
}
contentChunk = new ByteArrayContent(
mediaContent.getType(), currentRequestContentBuffer, contentBufferStartIndex,
actualBlockSize);
}
currentRequest.setContent(contentChunk);
currentRequest.getHeaders().setContentRange("bytes " + bytesWritten + "-" +
(bytesWritten + actualBlockSize - 1) + "/" + mediaContentLengthStr);
}
/**
* The call back method that will be invoked by
* {@link MediaUploadExponentialBackOffPolicy#getNextBackOffMillis} if it encounters a server
* error. This method should only be used as a call back method after {@link #upload} is invoked.
*
* <p>
* This method will query the current status of the upload to find how many bytes were
* successfully uploaded before the server error occurred. It will then adjust the HTTP Request
* object used by the BackOffPolicy to contain the correct range header and media content chunk.
* </p>
*/
public void serverErrorCallback() throws IOException {
Preconditions.checkNotNull(currentRequest, "The current request should not be null");
// TODO(rmistry): Handle timeouts here similar to how server errors are handled.
// Query the current status of the upload by issuing an empty POST request on the upload URI.
HttpRequest request = requestFactory.buildPutRequest(currentRequest.getUrl(), null);
addMethodOverride(request); // needed for PUT
request.getHeaders().setContentRange("bytes */" + (
getMediaContentLength() >= 0 ? getMediaContentLength() : "*"));
request.setContent(new EmptyContent());
request.setThrowExceptionOnExecuteError(false);
request.setRetryOnExecuteIOException(true);
HttpResponse response = request.execute();
try {
long bytesWritten = getNextByteIndex(response.getHeaders().getRange());
// Check to see if the upload URL has changed on the server.
String updatedUploadUrl = response.getHeaders().getLocation();
if (updatedUploadUrl != null) {
currentRequest.setUrl(new GenericUrl(updatedUploadUrl));
}
if (getMediaContentLength() >= 0) {
// The current position of the input stream is likely incorrect because the upload was
// interrupted. Reset the position and skip ahead to the correct spot.
// We do not need to do this when the media content length is unknown because we store the
// last chunk in a byte buffer.
contentInputStream.reset();
long skipValue = bytesUploaded - bytesWritten;
long actualSkipValue = contentInputStream.skip(skipValue);
Preconditions.checkState(skipValue == actualSkipValue);
}
// Adjust the HTTP request that encountered the server error with the correct range header
// and media content chunk.
setContentAndHeadersOnCurrentRequest(bytesWritten);
} finally {
response.disconnect();
}
}
/**
* Returns the next byte index identifying data that the server has not yet received, obtained
* from the HTTP Range header (E.g a header of "Range: 0-55" would cause 56 to be returned).
* <code>null</code> or malformed headers cause 0 to be returned.
*
* @param rangeHeader in the HTTP response
* @return the byte index beginning where the server has yet to receive data
*/
private long getNextByteIndex(String rangeHeader) {
if (rangeHeader == null) {
return 0L;
}
return Long.parseLong(rangeHeader.substring(rangeHeader.indexOf('-') + 1)) + 1;
}
/** Returns HTTP content metadata for the media request or {@code null} for none. */
public HttpContent getMetadata() {
return metadata;
}
/** Sets HTTP content metadata for the media request or {@code null} for none. */
public MediaHttpUploader setMetadata(HttpContent metadata) {
this.metadata = metadata;
return this;
}
/** Returns the HTTP content of the media to be uploaded. */
public HttpContent getMediaContent() {
return mediaContent;
}
/** Returns the transport to use for requests. */
public HttpTransport getTransport() {
return transport;
}
/**
* Sets whether the back off policy is enabled or disabled. If value is set to {@code false} then
* server errors are not handled and the upload process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
public MediaHttpUploader setBackOffPolicyEnabled(boolean backOffPolicyEnabled) {
this.backOffPolicyEnabled = backOffPolicyEnabled;
return this;
}
/**
* Returns whether the back off policy is enabled or disabled. If value is set to {@code false}
* then server errors are not handled and the upload process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
public boolean isBackOffPolicyEnabled() {
return backOffPolicyEnabled;
}
/**
* Sets whether direct media upload is enabled or disabled. If value is set to {@code true} then a
* direct upload will be done where the whole media content is uploaded in a single request. If
* value is set to {@code false} then the upload uses the resumable media upload protocol to
* upload in data chunks. Defaults to {@code false}.
*
* @since 1.9
*/
public MediaHttpUploader setDirectUploadEnabled(boolean directUploadEnabled) {
this.directUploadEnabled = directUploadEnabled;
return this;
}
/**
* Returns whether direct media upload is enabled or disabled. If value is set to {@code true}
* then a direct upload will be done where the whole media content is uploaded in a single
* request. If value is set to {@code false} then the upload uses the resumable media upload
* protocol to upload in data chunks. Defaults to {@code false}.
*
* @since 1.9
*/
public boolean isDirectUploadEnabled() {
return directUploadEnabled;
}
/**
* Sets the progress listener to send progress notifications to or {@code null} for none.
*/
public MediaHttpUploader setProgressListener(MediaHttpUploaderProgressListener progressListener) {
this.progressListener = progressListener;
return this;
}
/**
* Returns the progress listener to send progress notifications to or {@code null} for none.
*/
public MediaHttpUploaderProgressListener getProgressListener() {
return progressListener;
}
/**
* Sets the maximum size of individual chunks that will get uploaded by single HTTP requests. The
* default value is {@link #DEFAULT_CHUNK_SIZE}.
*
* <p>
* The minimum allowable value is {@link #MINIMUM_CHUNK_SIZE} and the specified chunk size must
* be a multiple of {@link #MINIMUM_CHUNK_SIZE}.
* </p>
*
* <p>
* Upgrade warning: Prior to version 1.13.0-beta {@link #setChunkSize} accepted any chunk size
* above {@link #MINIMUM_CHUNK_SIZE}, it now accepts only multiples of
* {@link #MINIMUM_CHUNK_SIZE}.
* </p>
*/
public MediaHttpUploader setChunkSize(int chunkSize) {
Preconditions.checkArgument(chunkSize > 0 && chunkSize % MINIMUM_CHUNK_SIZE == 0);
this.chunkSize = chunkSize;
return this;
}
/**
* Returns the maximum size of individual chunks that will get uploaded by single HTTP requests.
* The default value is {@link #DEFAULT_CHUNK_SIZE}.
*/
public int getChunkSize() {
return chunkSize;
}
/**
* Returns whether to disable GZip compression of HTTP content.
*
* @since 1.13
*/
public boolean getDisableGZipContent() {
return disableGZipContent;
}
/**
* Sets whether to disable GZip compression of HTTP content.
*
* <p>
* By default it is {@code false}.
* </p>
*
* @since 1.13
*/
public MediaHttpUploader setDisableGZipContent(boolean disableGZipContent) {
this.disableGZipContent = disableGZipContent;
return this;
}
/**
* Returns the HTTP method used for the initiation request.
*
* <p>
* The default value is {@link HttpMethods#POST}.
* </p>
*
* @since 1.12
*/
public String getInitiationRequestMethod() {
return initiationRequestMethod;
}
/**
* Sets the HTTP method used for the initiation request.
*
* <p>
* Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media
* update). The default value is {@link HttpMethods#POST}.
* </p>
*
* @since 1.12
*/
public MediaHttpUploader setInitiationRequestMethod(String initiationRequestMethod) {
Preconditions.checkArgument(initiationRequestMethod.equals(HttpMethods.POST)
|| initiationRequestMethod.equals(HttpMethods.PUT));
this.initiationRequestMethod = initiationRequestMethod;
return this;
}
/**
* Sets the HTTP headers used for the initiation request.
*
* <p>
* Upgrade warning: in prior version 1.12 the initiation headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*/
public MediaHttpUploader setInitiationHeaders(HttpHeaders initiationHeaders) {
this.initiationHeaders = initiationHeaders;
return this;
}
/**
* Returns the HTTP headers used for the initiation request.
*
* <p>
* Upgrade warning: in prior version 1.12 the initiation headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*/
public HttpHeaders getInitiationHeaders() {
return initiationHeaders;
}
/**
* Gets the total number of bytes uploaded by this uploader or {@code 0} for direct uploads when
* the content length is not known.
*
* @return the number of bytes uploaded
*/
public long getNumBytesUploaded() {
return bytesUploaded;
}
/**
* Sets the upload state and notifies the progress listener.
*
* @param uploadState value to set to
*/
private void updateStateAndNotifyListener(UploadState uploadState) throws IOException {
this.uploadState = uploadState;
if (progressListener != null) {
progressListener.progressChanged(this);
}
}
/**
* Gets the current upload state of the uploader.
*
* @return the upload state
*/
public UploadState getUploadState() {
return uploadState;
}
/**
* Gets the upload progress denoting the percentage of bytes that have been uploaded, represented
* between 0.0 (0%) and 1.0 (100%).
*
* <p>
* Do not use if the specified {@link AbstractInputStreamContent} has no content length specified.
* Instead, consider using {@link #getNumBytesUploaded} to denote progress.
* </p>
*
* @throws IllegalArgumentException if the specified {@link AbstractInputStreamContent} has no
* content length
* @return the upload progress
*/
public double getProgress() throws IOException {
Preconditions.checkArgument(getMediaContentLength() >= 0, "Cannot call getProgress() if " +
"the specified AbstractInputStreamContent has no content length. Use " +
" getNumBytesUploaded() to denote progress instead.");
return getMediaContentLength() == 0 ? 0 : (double) bytesUploaded / getMediaContentLength();
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.media;
import java.io.IOException;
/**
* An interface for receiving progress notifications for uploads.
*
* <p>
* Sample usage (if media content length is provided, else consider using
* {@link MediaHttpUploader#getNumBytesUploaded} instead of {@link MediaHttpUploader#getProgress}:
* </p>
*
* <pre>
public static class MyUploadProgressListener implements MediaHttpUploaderProgressListener {
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
System.out.println("Initiation Started");
break;
case INITIATION_COMPLETE:
System.out.println("Initiation Completed");
break;
case MEDIA_IN_PROGRESS:
System.out.println("Upload in progress");
System.out.println("Upload percentage: " + uploader.getProgress());
break;
case MEDIA_COMPLETE:
System.out.println("Upload Completed!");
break;
}
}
}
* </pre>
*
* @since 1.9
* @author rmistry@google.com (Ravi Mistry)
*/
public interface MediaHttpUploaderProgressListener {
/**
* Called to notify that progress has been changed.
*
* <p>
* This method is called once before and after the initiation request. For media uploads it is
* called multiple times depending on how many chunks are uploaded. Once the upload completes it
* is called one final time.
* </p>
*
* <p>
* The upload state can be queried by calling {@link MediaHttpUploader#getUploadState} and the
* progress by calling {@link MediaHttpUploader#getProgress}.
* </p>
*
* @param uploader Media HTTP uploader
*/
public void progressChanged(MediaHttpUploader uploader) throws IOException;
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.media;
import com.google.api.client.http.ExponentialBackOffPolicy;
import java.io.IOException;
/**
* Extension of {@link ExponentialBackOffPolicy} that calls the Media HTTP Uploader call back method
* before backing off requests.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @author rmistry@google.com (Ravi Mistry)
*/
class MediaUploadExponentialBackOffPolicy extends ExponentialBackOffPolicy {
/** The uploader to callback on if there is a server error. */
private final MediaHttpUploader uploader;
MediaUploadExponentialBackOffPolicy(MediaHttpUploader uploader) {
super();
this.uploader = uploader;
}
/**
* Gets the number of milliseconds to wait before retrying an HTTP request. If {@link #STOP} is
* returned, no retries should be made. Calls the Media HTTP Uploader call back method before
* backing off requests.
*
* @return the number of milliseconds to wait when backing off requests, or {@link #STOP} if no
* more retries should be made
*/
@Override
public long getNextBackOffMillis() throws IOException {
// Call the Media HTTP Uploader to calculate how much data was uploaded before the error and
// then adjust the HTTP request before the retry.
uploader.serverErrorCallback();
return super.getNextBackOffMillis();
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.media;
import java.io.IOException;
/**
* An interface for receiving progress notifications for downloads.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
public static class MyDownloadProgressListener implements MediaHttpDownloaderProgressListener {
public void progressChanged(MediaHttpDownloader downloader) throws IOException {
switch (downloader.getDownloadState()) {
case MEDIA_IN_PROGRESS:
System.out.println("Download in progress");
System.out.println("Download percentage: " + downloader.getProgress());
break;
case MEDIA_COMPLETE:
System.out.println("Download Completed!");
break;
}
}
}
* </pre>
*
* @since 1.9
* @author rmistry@google.com (Ravi Mistry)
*/
public interface MediaHttpDownloaderProgressListener {
/**
* Called to notify that progress has been changed.
*
* <p>
* This method is called multiple times depending on how many chunks are downloaded. Once the
* download completes it is called one final time.
* </p>
*
* <p>
* The download state can be queried by calling {@link MediaHttpDownloader#getDownloadState} and
* the progress by calling {@link MediaHttpDownloader#getProgress}.
* </p>
*
* @param downloader Media HTTP downloader
*/
public void progressChanged(MediaHttpDownloader downloader) throws IOException;
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.media;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.http.ExponentialBackOffPolicy;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.OutputStream;
/**
* Media HTTP Downloader, with support for both direct and resumable media downloads. Documentation
* is available <a
* href='http://code.google.com/p/google-api-java-client/wiki/MediaDownload'>here</a>.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.9
*
* @author rmistry@google.com (Ravi Mistry)
*/
public final class MediaHttpDownloader {
/**
* Download state associated with the Media HTTP downloader.
*/
public enum DownloadState {
/** The download process has not started yet. */
NOT_STARTED,
/** Set after a media file chunk is downloaded. */
MEDIA_IN_PROGRESS,
/** Set after the complete media file is successfully downloaded. */
MEDIA_COMPLETE
}
/**
* Default maximum number of bytes that will be downloaded from the server in any single HTTP
* request. Set to 32MB because that is the maximum App Engine request size.
*/
public static final int MAXIMUM_CHUNK_SIZE = 32 * MediaHttpUploader.MB;
/** The request factory for connections to the server. */
private final HttpRequestFactory requestFactory;
/** The transport to use for requests. */
private final HttpTransport transport;
/**
* Determines whether the back off policy is enabled or disabled. If value is set to {@code false}
* then server errors are not handled and the download process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
private boolean backOffPolicyEnabled = true;
/**
* Determines whether direct media download is enabled or disabled. If value is set to
* {@code true} then a direct download will be done where the whole media content is downloaded in
* a single request. If value is set to {@code false} then the download uses the resumable media
* download protocol to download in data chunks. Defaults to {@code false}.
*/
private boolean directDownloadEnabled = false;
/**
* Progress listener to send progress notifications to or {@code null} for none.
*/
private MediaHttpDownloaderProgressListener progressListener;
/**
* Maximum size of individual chunks that will get downloaded by single HTTP requests. The default
* value is {@link #MAXIMUM_CHUNK_SIZE}.
*/
private int chunkSize = MAXIMUM_CHUNK_SIZE;
/**
* The length of the HTTP media content or {@code 0} before it is initialized in
* {@link #setMediaContentLength}.
*/
private long mediaContentLength;
/** The current state of the downloader. */
private DownloadState downloadState = DownloadState.NOT_STARTED;
/** The total number of bytes downloaded by this downloader. */
private long bytesDownloaded;
/**
* The last byte position of the media file we want to download, default value is {@code -1}.
*
* <p>
* If its value is {@code -1} it means there is no upper limit on the byte position.
* </p>
*/
private long lastBytePos = -1;
/**
* Construct the {@link MediaHttpDownloader}.
*
* @param transport The transport to use for requests
* @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or
* {@code null} for none
*/
public MediaHttpDownloader(HttpTransport transport,
HttpRequestInitializer httpRequestInitializer) {
this.transport = Preconditions.checkNotNull(transport);
this.requestFactory =
httpRequestInitializer == null ? transport.createRequestFactory() : transport
.createRequestFactory(httpRequestInitializer);
}
/**
* Executes a direct media download or a resumable media download.
*
* <p>
* This method does not close the given output stream.
* </p>
*
* <p>
* This method is not reentrant. A new instance of {@link MediaHttpDownloader} must be
* instantiated before download called be called again.
* </p>
*
* @param requestUrl The request URL where the download requests will be sent
* @param outputStream destination output stream
*/
public void download(GenericUrl requestUrl, OutputStream outputStream) throws IOException {
download(requestUrl, null, outputStream);
}
/**
* Executes a direct media download or a resumable media download.
*
* <p>
* This method does not close the given output stream.
* </p>
*
* <p>
* This method is not reentrant. A new instance of {@link MediaHttpDownloader} must be
* instantiated before download called be called again.
* </p>
*
* @param requestUrl The request URL where the download requests will be sent
* @param requestHeaders request headers or {@code null} to ignore
* @param outputStream destination output stream
* @since 1.12
*/
public void download(GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream)
throws IOException {
Preconditions.checkArgument(downloadState == DownloadState.NOT_STARTED);
requestUrl.put("alt", "media");
if (directDownloadEnabled) {
updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS);
HttpRequest request = requestFactory.buildGetRequest(requestUrl);
if (requestHeaders != null) {
request.getHeaders().putAll(requestHeaders);
}
if (bytesDownloaded != 0) {
StringBuilder rangeHeader = new StringBuilder();
rangeHeader.append("bytes=").append(bytesDownloaded).append("-");
if (lastBytePos != -1) {
rangeHeader.append(lastBytePos);
}
request.getHeaders().setRange(rangeHeader.toString());
}
HttpResponse response = request.execute();
try {
// All required bytes have been downloaded from the server.
mediaContentLength = response.getHeaders().getContentLength();
bytesDownloaded = mediaContentLength;
updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE);
AbstractInputStreamContent.copy(response.getContent(), outputStream);
} finally {
response.disconnect();
}
return;
}
// Download the media content in chunks.
while (true) {
HttpRequest request = requestFactory.buildGetRequest(requestUrl);
if (requestHeaders != null) {
request.getHeaders().putAll(requestHeaders);
}
long currentRequestLastBytePos = bytesDownloaded + chunkSize - 1;
if (lastBytePos != -1) {
// If last byte position has been specified use it iff it is smaller than the chunksize.
currentRequestLastBytePos = Math.min(lastBytePos, currentRequestLastBytePos);
}
request.getHeaders().setRange(
"bytes=" + bytesDownloaded + "-" + currentRequestLastBytePos);
if (backOffPolicyEnabled) {
// Set ExponentialBackOffPolicy as the BackOffPolicy of the HTTP Request which will
// retry the same request again if there is a server error.
request.setBackOffPolicy(new ExponentialBackOffPolicy());
}
HttpResponse response = request.execute();
AbstractInputStreamContent.copy(response.getContent(), outputStream);
String contentRange = response.getHeaders().getContentRange();
long nextByteIndex = getNextByteIndex(contentRange);
setMediaContentLength(contentRange);
if (mediaContentLength <= nextByteIndex) {
// All required bytes have been downloaded from the server.
bytesDownloaded = mediaContentLength;
updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE);
return;
}
bytesDownloaded = nextByteIndex;
updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS);
}
}
/**
* Returns the next byte index identifying data that the server has not yet sent out, obtained
* from the HTTP Content-Range header (E.g a header of "Content-Range: 0-55/1000" would cause 56
* to be returned). <code>null</code> headers cause 0 to be returned.
*
* @param rangeHeader in the HTTP response
* @return the byte index beginning where the server has yet to send out data
*/
private long getNextByteIndex(String rangeHeader) {
if (rangeHeader == null) {
return 0L;
}
return Long.parseLong(rangeHeader.substring(rangeHeader.indexOf('-') + 1,
rangeHeader.indexOf('/'))) + 1;
}
/**
* Sets the total number of bytes that have been downloaded of the media resource.
*
* <p>
* If a download was aborted mid-way due to a connection failure then users can resume the
* download from the point where it left off.
* </p>
*
* <p>
* Use {@link #setContentRange} if you need to specify both the bytes downloaded and the last byte
* position.
* </p>
*
* @param bytesDownloaded The total number of bytes downloaded
*/
public MediaHttpDownloader setBytesDownloaded(long bytesDownloaded) {
Preconditions.checkArgument(bytesDownloaded >= 0);
this.bytesDownloaded = bytesDownloaded;
return this;
}
/**
* Sets the content range of the next download request. Eg: bytes=firstBytePos-lastBytePos.
*
* <p>
* If a download was aborted mid-way due to a connection failure then users can resume the
* download from the point where it left off.
* </p>
*
* <p>
* Use {@link #setBytesDownloaded} if you only need to specify the first byte position.
* </p>
*
* @param firstBytePos The first byte position in the content range string
* @param lastBytePos The last byte position in the content range string.
* @since 1.13
*/
public MediaHttpDownloader setContentRange(long firstBytePos, int lastBytePos) {
Preconditions.checkArgument(lastBytePos >= firstBytePos);
setBytesDownloaded(firstBytePos);
this.lastBytePos = lastBytePos;
return this;
}
/**
* Sets the media content length from the HTTP Content-Range header (E.g a header of
* "Content-Range: 0-55/1000" would cause 1000 to be set. <code>null</code> headers do not set
* anything.
*
* @param rangeHeader in the HTTP response
*/
private void setMediaContentLength(String rangeHeader) {
if (rangeHeader == null) {
return;
}
if (mediaContentLength == 0) {
mediaContentLength = Long.parseLong(rangeHeader.substring(rangeHeader.indexOf('/') + 1));
}
}
/**
* Returns whether direct media download is enabled or disabled. If value is set to {@code true}
* then a direct download will be done where the whole media content is downloaded in a single
* request. If value is set to {@code false} then the download uses the resumable media download
* protocol to download in data chunks. Defaults to {@code false}.
*/
public boolean isDirectDownloadEnabled() {
return directDownloadEnabled;
}
/**
* Returns whether direct media download is enabled or disabled. If value is set to {@code true}
* then a direct download will be done where the whole media content is downloaded in a single
* request. If value is set to {@code false} then the download uses the resumable media download
* protocol to download in data chunks. Defaults to {@code false}.
*/
public MediaHttpDownloader setDirectDownloadEnabled(boolean directDownloadEnabled) {
this.directDownloadEnabled = directDownloadEnabled;
return this;
}
/**
* Sets the progress listener to send progress notifications to or {@code null} for none.
*/
public MediaHttpDownloader setProgressListener(
MediaHttpDownloaderProgressListener progressListener) {
this.progressListener = progressListener;
return this;
}
/**
* Returns the progress listener to send progress notifications to or {@code null} for none.
*/
public MediaHttpDownloaderProgressListener getProgressListener() {
return progressListener;
}
/**
* Sets whether the back off policy is enabled or disabled. If value is set to {@code false} then
* server errors are not handled and the download process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
public MediaHttpDownloader setBackOffPolicyEnabled(boolean backOffPolicyEnabled) {
this.backOffPolicyEnabled = backOffPolicyEnabled;
return this;
}
/**
* Returns whether the back off policy is enabled or disabled. If value is set to {@code false}
* then server errors are not handled and the download process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
public boolean isBackOffPolicyEnabled() {
return backOffPolicyEnabled;
}
/** Returns the transport to use for requests. */
public HttpTransport getTransport() {
return transport;
}
/**
* Sets the maximum size of individual chunks that will get downloaded by single HTTP requests.
* The default value is {@link #MAXIMUM_CHUNK_SIZE}.
*
* <p>
* The maximum allowable value is {@link #MAXIMUM_CHUNK_SIZE}.
* </p>
*/
public MediaHttpDownloader setChunkSize(int chunkSize) {
Preconditions.checkArgument(chunkSize > 0 && chunkSize <= MAXIMUM_CHUNK_SIZE);
this.chunkSize = chunkSize;
return this;
}
/**
* Returns the maximum size of individual chunks that will get downloaded by single HTTP requests.
* The default value is {@link #MAXIMUM_CHUNK_SIZE}.
*/
public int getChunkSize() {
return chunkSize;
}
/**
* Gets the total number of bytes downloaded by this downloader.
*
* @return the number of bytes downloaded
*/
public long getNumBytesDownloaded() {
return bytesDownloaded;
}
/**
* Gets the last byte position of the media file we want to download or {@code -1} if there is no
* upper limit on the byte position.
*
* @return the last byte position
* @since 1.13
*/
public long getLastBytePosition() {
return lastBytePos;
}
/**
* Sets the download state and notifies the progress listener.
*
* @param downloadState value to set to
*/
private void updateStateAndNotifyListener(DownloadState downloadState) throws IOException {
this.downloadState = downloadState;
if (progressListener != null) {
progressListener.progressChanged(this);
}
}
/**
* Gets the current download state of the downloader.
*
* @return the download state
*/
public DownloadState getDownloadState() {
return downloadState;
}
/**
* Gets the download progress denoting the percentage of bytes that have been downloaded,
* represented between 0.0 (0%) and 1.0 (100%).
*
* @return the download progress
*/
public double getProgress() {
return mediaContentLength == 0 ? 0 : (double) bytesDownloaded / mediaContentLength;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis.json;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.JsonParser;
import com.google.api.client.json.JsonToken;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashSet;
/**
* Parses JSON-C response content into an data class of key/value pairs, assuming the data is
* wrapped in a {@code "data"} envelope.
*
* <p>
* Warning: this should only be used by some older Google APIs that wrapped the response in a
* {@code "data"} envelope. All newer Google APIs don't use this envelope, and for those APIs
* {@link JsonObjectParser} should be used instead.
* </p>
*
* <p>
* Sample usage:
* </p>
*
* <pre>
* <code>
static void setParser(HttpRequest request) {
request.setParser(new JsonCParser(new JacksonFactory()));
}
* </code>
* </pre>
*
* <p>
* Implementation is thread-safe.
* </p>
*
* <p>
* Upgrade warning: this class now extends {@link JsonObjectParser}, whereas in prior version 1.11
* it extended {@link com.google.api.client.http.json.JsonHttpParser}.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
@SuppressWarnings("javadoc")
public final class JsonCParser extends JsonObjectParser {
private final JsonFactory jsonFactory;
/**
* Returns the JSON factory used for parsing.
*
* @since 1.10
*/
public final JsonFactory getFactory() {
return jsonFactory;
}
/**
* @param jsonFactory non-null JSON factory used for parsing
* @since 1.5
*/
public JsonCParser(JsonFactory jsonFactory) {
super(jsonFactory);
this.jsonFactory = Preconditions.checkNotNull(jsonFactory);
}
/**
* Initializes a JSON parser to use for parsing by skipping over the {@code "data"} or
* {@code "error"} envelope.
*
* <p>
* The parser will be closed if any throwable is thrown. The current token will be the value of
* the {@code "data"} or {@code "error} key.
* </p>
*
* @param parser the parser which should be initialized for normal parsing
* @throws IllegalArgumentException if content type is not {@link Json#MEDIA_TYPE} or if expected
* {@code "data"} or {@code "error"} key is not found
* @return the parser which was passed as a parameter
* @since 1.10
*/
public static JsonParser initializeParser(JsonParser parser) throws IOException {
// parse
boolean failed = true;
try {
String match = parser.skipToKey(new HashSet<String>(Arrays.asList("data", "error")));
if (match == null || parser.getCurrentToken() == JsonToken.END_OBJECT) {
throw new IllegalArgumentException("data key not found");
}
failed = false;
} finally {
if (failed) {
parser.close();
}
}
return parser;
}
@Override
public Object parseAndClose(InputStream in, Charset charset, Type dataType) throws IOException {
return initializeParser(jsonFactory.createJsonParser(in, charset)).parse(dataType, true, null);
}
@Override
public Object parseAndClose(Reader reader, Type dataType) throws IOException {
return initializeParser(jsonFactory.createJsonParser(reader)).parse(dataType, true, null);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.
*/
/**
* Google's JSON support (see detailed package specification).
*
* <h2>Package Specification</h2>
*
* <p>
* User-defined Partial JSON data models allow you to defined Plain Old Java Objects (POJO's) to
* define how the library should parse/serialize JSON. Each field that should be included must have
* an @{@link com.google.api.client.util.Key} annotation. The field can be of any visibility
* (private, package private, protected, or public) and must not be static. By default, the field
* name is used as the JSON key. To override this behavior, simply specify the JSON key use the
* optional value parameter of the annotation, for example {@code @Key("name")}. Any unrecognized
* keys from the JSON are normally simply ignored and not stored. If the ability to store unknown
* keys is important, use {@link com.google.api.client.json.GenericJson}.
* </p>
*
* <p>
* Let's take a look at a typical partial JSON-C video feed from the YouTube Data API (as specified
* in <a href="http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html">YouTube
* Developer's Guide: JSON-C / JavaScript</a>)
* </p>
*
* <pre><code>
"data":{
"updated":"2010-01-07T19:58:42.949Z",
"totalItems":800,
"startIndex":1,
"itemsPerPage":1,
"items":[
{"id":"hYB0mn5zh2c",
"updated":"2010-01-07T13:26:50.000Z",
"title":"Google Developers Day US - Maps API Introduction",
"description":"Google Maps API Introduction ...",
"tags":[
"GDD07","GDD07US","Maps"
],
"player":{
"default":"http://www.youtube.com/watch?v\u003dhYB0mn5zh2c"
},
...
}
]
}
</code></pre>
*
* <p>
* Here's one possible way to design the Java data classes for this (each class in its own Java
* file):
* </p>
*
* <pre><code>
import com.google.api.client.util.*;
import java.util.List;
public class VideoFeed {
@Key public int itemsPerPage;
@Key public int startIndex;
@Key public int totalItems;
@Key public DateTime updated;
@Key public List<Video> items;
}
public class Video {
@Key public String id;
@Key public String title;
@Key public DateTime updated;
@Key public String description;
@Key public List<String> tags;
@Key public Player player;
}
public class Player {
// "default" is a Java keyword, so need to specify the JSON key manually
@Key("default")
public String defaultUrl;
}
</code></pre>
*
* <p>
* You can also use the @{@link com.google.api.client.util.Key} annotation to defined query
* parameters for a URL. For example:
* </p>
*
* <pre><code>
public class YouTubeUrl extends GoogleUrl {
@Key
public String author;
@Key("max-results")
public Integer maxResults;
public YouTubeUrl(String encodedUrl) {
super(encodedUrl);
this.alt = "jsonc";
}
</code></pre>
*
* <p>
* To work with the YouTube API, you first need to set up the
* {@link com.google.api.client.http.HttpTransport}. For example:
* </p>
*
* <pre><code>
private static HttpTransport setUpTransport() throws IOException {
HttpTransport result = new NetHttpTransport();
GoogleUtils.useMethodOverride(result);
HttpHeaders headers = new HttpHeaders();
headers.setApplicationName("Google-YouTubeSample/1.0");
headers.gdataVersion = "2";
JsonCParser parser = new JsonCParser();
parser.jsonFactory = new JacksonFactory();
transport.addParser(parser);
// insert authentication code...
return transport;
}
</code></pre>
*
* <p>
* Now that we have a transport, we can execute a request to the YouTube API and parse the result:
* </p>
*
* <pre><code>
public static VideoFeed list(HttpTransport transport, YouTubeUrl url)
throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = url;
return request.execute().parseAs(VideoFeed.class);
}
</code></pre>
*
* <p>
* If the server responds with an error the {@link com.google.api.client.http.HttpRequest#execute}
* method will throw an {@link com.google.api.client.http.HttpResponseException}, which has an
* {@link com.google.api.client.http.HttpResponse} field which can be parsed the same way as a
* success response inside of a catch block. For example:
* </p>
*
* <pre><code>
try {
...
} catch (HttpResponseException e) {
if (e.response.getParser() != null) {
Error error = e.response.parseAs(Error.class);
// process error response
} else {
String errorContentString = e.response.parseAsString();
// process error response as string
}
throw e;
}
</code></pre>
*
* <p>
* NOTE: As you might guess, the library uses reflection to populate the user-defined data model.
* It's not quite as fast as writing the wire format parsing code yourself can potentially be, but
* it's a lot easier.
* </p>
*
* <p>
* NOTE: If you prefer to use your favorite JSON parsing library instead (there are many of them
* listed for example on <a href="http://json.org">json.org</a>), that's supported as well. Just
* call {@link com.google.api.client.http.HttpRequest#execute()} and parse the returned byte stream.
* </p>
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.json;
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis.json;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonGenerator;
import java.io.IOException;
import java.io.OutputStream;
/**
* Serializes JSON-C content based on the data key/value mapping object for an item, wrapped in a
* {@code "data"} envelope.
*
* <p>
* Warning: this should only be used by some older Google APIs that wrapped the response in a
* {@code "data"} envelope. All newer Google APIs don't use this envelope, and for those APIs
* {@link JsonHttpContent} should be used instead.
* </p>
*
* <p>
* Sample usage:
* </p>
*
* <pre>
static void setContent(HttpRequest request, Object data) {
JsonCContent content = new JsonCContent(new JacksonFactory(), data);
request.setContent(content);
}
* </pre>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class JsonCContent extends JsonHttpContent {
/**
* @param jsonFactory JSON factory to use
* @param data JSON key name/value data
* @since 1.5
*/
public JsonCContent(JsonFactory jsonFactory, Object data) {
super(jsonFactory, data);
}
@Override
public void writeTo(OutputStream out) throws IOException {
JsonGenerator generator = getJsonFactory().createJsonGenerator(out, getCharset());
generator.writeStartObject();
generator.writeFieldName("data");
generator.serialize(getData());
generator.writeEndObject();
generator.flush();
}
@Override
public JsonCContent setMediaType(HttpMediaType mediaType) {
super.setMediaType(mediaType);
return this;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis.json;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.CustomizeJsonParser;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonParser;
import com.google.api.client.json.rpc2.JsonRpcRequest;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* JSON-RPC 2.0 HTTP transport for RPC requests for Google API's, including both singleton and
* batched requests.
*
* <p>
* This implementation is thread-safe.
* </p>
*
* <p>
* Warning: this is based on an undocumented experimental Google functionality that may stop working
* or change in behavior at any time. Beware of this risk if running this in production code.
* </p>
*
* @since 1.3
* @author Yaniv Inbar
*/
public final class GoogleJsonRpcHttpTransport {
private static final String JSON_RPC_CONTENT_TYPE = "application/json-rpc";
/** Encoded RPC server URL. */
private final String rpcServerUrl;
/** (REQUIRED) HTTP transport required for building requests. */
private final HttpTransport transport;
/** (REQUIRED) JSON factory to use for building requests. */
private final JsonFactory jsonFactory;
/** Content type header to use for requests. By default this is {@code "application/json-rpc"}. */
private final String mimeType;
/** Accept header to use for requests. By default this is {@code "application/json-rpc"}. */
private final String accept;
/**
* Creates a new {@link GoogleJsonRpcHttpTransport} with default values for RPC server, and
* Content type and Accept headers.
*
* @param httpTransport HTTP transport required for building requests.
* @param jsonFactory JSON factory to use for building requests.
*
* @since 1.9
*/
public GoogleJsonRpcHttpTransport(HttpTransport httpTransport, JsonFactory jsonFactory) {
this(Preconditions.checkNotNull(httpTransport), Preconditions.checkNotNull(jsonFactory),
Builder.DEFAULT_SERVER_URL.build(), JSON_RPC_CONTENT_TYPE, JSON_RPC_CONTENT_TYPE);
}
/**
* Creates a new {@link GoogleJsonRpcHttpTransport}.
*
* @param httpTransport HTTP transport required for building requests.
* @param jsonFactory JSON factory to use for building requests.
* @param rpcServerUrl RPC server URL.
* @param mimeType Content type header to use for requests.
* @param accept Accept header to use for requests.
*
* @since 1.9
*/
protected GoogleJsonRpcHttpTransport(HttpTransport httpTransport, JsonFactory jsonFactory,
String rpcServerUrl, String mimeType, String accept) {
this.transport = httpTransport;
this.jsonFactory = jsonFactory;
this.rpcServerUrl = rpcServerUrl;
this.mimeType = mimeType;
this.accept = accept;
}
/**
* Returns the HTTP transport used for building requests.
*
* @since 1.9
*/
public final HttpTransport getHttpTransport() {
return transport;
}
/**
* Returns the JSON factory used for building requests.
*
* @since 1.9
*/
public final JsonFactory getJsonFactory() {
return jsonFactory;
}
/**
* Returns the RPC server URL.
*
* @since 1.9
*/
public final String getRpcServerUrl() {
return rpcServerUrl;
}
/**
* Returns the MIME type header used for requests.
*
* @since 1.10
*/
public final String getMimeType() {
return mimeType;
}
/**
* Returns the Accept header used for requests.
*
* @since 1.9
*/
public final String getAccept() {
return accept;
}
/**
* {@link GoogleJsonRpcHttpTransport} Builder.
*
* <p>
* Implementation is not thread safe.
* </p>
*
* @since 1.9
*/
public static class Builder {
/** Default RPC server URL. */
static final GenericUrl DEFAULT_SERVER_URL = new GenericUrl("https://www.googleapis.com");
/** HTTP transport required for building requests. */
private final HttpTransport httpTransport;
/** JSON factory to use for building requests. */
private final JsonFactory jsonFactory;
/** RPC server URL. */
private GenericUrl rpcServerUrl = DEFAULT_SERVER_URL;
/** MIME type to use for the Content type header for requests. */
private String mimeType = JSON_RPC_CONTENT_TYPE;
/** Accept header to use for requests. */
private String accept = mimeType;
/**
* @param httpTransport HTTP transport required for building requests.
* @param jsonFactory JSON factory to use for building requests.
*/
public Builder(HttpTransport httpTransport, JsonFactory jsonFactory) {
this.httpTransport = Preconditions.checkNotNull(httpTransport);
this.jsonFactory = Preconditions.checkNotNull(jsonFactory);
}
/**
* Sets the RPC server URL.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param rpcServerUrl RPC server URL.
*/
protected Builder setRpcServerUrl(GenericUrl rpcServerUrl) {
this.rpcServerUrl = Preconditions.checkNotNull(rpcServerUrl);
return this;
}
/**
* Sets the MIME type of the Content type header to use for requests. By default this is
* {@code "application/json-rpc"}.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param mimeType MIME type to use for requests.
* @since 1.10
*/
protected Builder setMimeType(String mimeType) {
this.mimeType = Preconditions.checkNotNull(mimeType);
return this;
}
/**
* Sets the Accept header to use for requests. By default this is {@code "application/json-rpc"}
* .
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param accept Accept header to use for requests.
*/
protected Builder setAccept(String accept) {
this.accept = Preconditions.checkNotNull(accept);
return this;
}
/**
* Returns a new {@link GoogleJsonRpcHttpTransport} instance.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
protected GoogleJsonRpcHttpTransport build() {
return new GoogleJsonRpcHttpTransport(
httpTransport, jsonFactory, rpcServerUrl.build(), mimeType, accept);
}
/**
* Returns the HTTP transport used for building requests.
*/
public final HttpTransport getHttpTransport() {
return httpTransport;
}
/**
* Returns the JSON factory used for building requests.
*/
public final JsonFactory getJsonFactory() {
return jsonFactory;
}
/**
* Returns the RPC server.
*/
public final GenericUrl getRpcServerUrl() {
return rpcServerUrl;
}
/**
* Returns the MIME type used for requests.
*
* @since 1.10
*/
public final String getMimeType() {
return mimeType;
}
/**
* Returns the Accept header used for requests.
*/
public final String getAccept() {
return accept;
}
}
/**
* Builds a POST HTTP request for the JSON-RPC requests objects specified in the given JSON-RPC
* request object.
* <p>
* You may use {@link JsonFactory#createJsonParser(java.io.InputStream)} to get the
* {@link JsonParser}, and {@link JsonParser#parseAndClose(Class, CustomizeJsonParser)}.
* </p>
*
* @param request JSON-RPC request object
* @return HTTP request
*/
public HttpRequest buildPostRequest(JsonRpcRequest request) throws IOException {
return internalExecute(request);
}
/**
* Builds a POST HTTP request for the JSON-RPC requests objects specified in the given JSON-RPC
* request objects.
* <p>
* Note that the request will always use batching -- i.e. JSON array of requests -- even if there
* is only one request. You may use {@link JsonFactory#createJsonParser(java.io.InputStream)} to
* get the {@link JsonParser}, and
* {@link JsonParser#parseArrayAndClose(Collection, Class, CustomizeJsonParser)} .
* </p>
*
* @param requests JSON-RPC request objects
* @return HTTP request
*/
public HttpRequest buildPostRequest(List<JsonRpcRequest> requests) throws IOException {
return internalExecute(requests);
}
private HttpRequest internalExecute(Object data) throws IOException {
JsonHttpContent content = new JsonHttpContent(jsonFactory, data);
content.setMediaType(new HttpMediaType(mimeType));
HttpRequest httpRequest;
httpRequest =
transport.createRequestFactory().buildPostRequest(new GenericUrl(rpcServerUrl), content);
httpRequest.getHeaders().setAccept(accept);
return httpRequest;
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.json;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.Data;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.List;
/**
* Data class representing the Google JSON error response content, as documented for example in <a
* href="https://code.google.com/apis/urlshortener/v1/getting_started.html#errors">Error
* responses</a>.
*
* @since 1.4
* @author Yaniv Inbar
*/
public class GoogleJsonError extends GenericJson {
/**
* Parses the given error HTTP response using the given JSON factory.
*
* @param jsonFactory JSON factory
* @param response HTTP response
* @return new instance of the Google JSON error information
* @throws IllegalArgumentException if content type is not {@link Json#MEDIA_TYPE} or if
* expected {@code "data"} or {@code "error"} key is not found
*/
public static GoogleJsonError parse(JsonFactory jsonFactory, HttpResponse response)
throws IOException {
return new JsonCParser(jsonFactory).parseAndClose(
response.getContent(), response.getContentCharset(), GoogleJsonError.class);
}
static {
// hack to force ProGuard to consider ErrorInfo used, since otherwise it would be stripped out
// see http://code.google.com/p/google-api-java-client/issues/detail?id=527
Data.nullOf(ErrorInfo.class);
}
/** Detailed error information. */
public static class ErrorInfo extends GenericJson {
/** Error classification or {@code null} for none. */
@Key
private String domain;
/** Error reason or {@code null} for none. */
@Key
private String reason;
/** Human readable explanation of the error or {@code null} for none. */
@Key
private String message;
/**
* Location in the request that caused the error or {@code null} for none or {@code null} for
* none.
*/
@Key
private String location;
/** Type of location in the request that caused the error or {@code null} for none. */
@Key
private String locationType;
/**
* Returns the error classification or {@code null} for none.
*
* @since 1.8
*/
public final String getDomain() {
return domain;
}
/**
* Sets the error classification or {@code null} for none.
*
* @since 1.8
*/
public final void setDomain(String domain) {
this.domain = domain;
}
/**
* Returns the error reason or {@code null} for none.
*
* @since 1.8
*/
public final String getReason() {
return reason;
}
/**
* Sets the error reason or {@code null} for none.
*
* @since 1.8
*/
public final void setReason(String reason) {
this.reason = reason;
}
/**
* Returns the human readable explanation of the error or {@code null} for none.
*
* @since 1.8
*/
public final String getMessage() {
return message;
}
/**
* Sets the human readable explanation of the error or {@code null} for none.
*
* @since 1.8
*/
public final void setMessage(String message) {
this.message = message;
}
/**
* Returns the location in the request that caused the error or {@code null} for none or
* {@code null} for none.
*
* @since 1.8
*/
public final String getLocation() {
return location;
}
/**
* Sets the location in the request that caused the error or {@code null} for none or
* {@code null} for none.
*
* @since 1.8
*/
public final void setLocation(String location) {
this.location = location;
}
/**
* Returns the type of location in the request that caused the error or {@code null} for none.
*
* @since 1.8
*/
public final String getLocationType() {
return locationType;
}
/**
* Sets the type of location in the request that caused the error or {@code null} for none.
*
* @since 1.8
*/
public final void setLocationType(String locationType) {
this.locationType = locationType;
}
}
/** List of detailed errors or {@code null} for none. */
@Key
private List<ErrorInfo> errors;
/** HTTP status code of this response or {@code null} for none. */
@Key
private int code;
/** Human-readable explanation of the error or {@code null} for none. */
@Key
private String message;
/**
* Returns the list of detailed errors or {@code null} for none.
*
* @since 1.8
*/
public final List<ErrorInfo> getErrors() {
return errors;
}
/**
* Sets the list of detailed errors or {@code null} for none.
*
* @since 1.8
*/
public final void setErrors(List<ErrorInfo> errors) {
this.errors = errors;
}
/**
* Returns the HTTP status code of this response or {@code null} for none.
*
* @since 1.8
*/
public final int getCode() {
return code;
}
/**
* Sets the HTTP status code of this response or {@code null} for none.
*
* @since 1.8
*/
public final void setCode(int code) {
this.code = code;
}
/**
* Returns the human-readable explanation of the error or {@code null} for none.
*
* @since 1.8
*/
public final String getMessage() {
return message;
}
/**
* Sets the human-readable explanation of the error or {@code null} for none.
*
* @since 1.8
*/
public final void setMessage(String message) {
this.message = message;
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.json;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonParser;
import com.google.api.client.json.JsonToken;
import com.google.api.client.util.StringUtils;
import com.google.common.base.Preconditions;
import java.io.IOException;
/**
* Exception thrown when an error status code is detected in an HTTP response to a Google API that
* uses the JSON format, using the format specified in <a
* href="http://code.google.com/apis/urlshortener/v1/getting_started.html#errors">Error
* Responses</a>.
*
* <p>
* To execute a request, call {@link #execute(JsonFactory, HttpRequest)}. This will throw a
* {@link GoogleJsonResponseException} on an error response. To get the structured details, use
* {@link #getDetails()}.
* </p>
*
* <pre>
static void executeShowingError(JsonFactory factory, HttpRequest request) throws IOException {
try {
GoogleJsonResponseException.execute(factory, request);
} catch (GoogleJsonResponseException e) {
System.err.println(e.getDetails());
}
}
* </pre>
*
* @since 1.6
* @author Yaniv Inbar
*/
public class GoogleJsonResponseException extends HttpResponseException {
private static final long serialVersionUID = 409811126989994864L;
/** Google JSON error details or {@code null} for none (for example if response is not JSON). */
private final transient GoogleJsonError details;
/**
* @param response HTTP response
* @param details Google JSON error details
* @param message message details
*/
private GoogleJsonResponseException(
HttpResponse response, GoogleJsonError details, String message) {
super(response, message);
this.details = details;
}
/**
* Returns the Google JSON error details or {@code null} for none (for example if response is not
* JSON).
*/
public final GoogleJsonError getDetails() {
return details;
}
/**
* Returns a new instance of {@link GoogleJsonResponseException}.
*
* <p>
* If there is a JSON error response, it is parsed using {@link GoogleJsonError}, which can be
* inspected using {@link #getDetails()}. Otherwise, the full response content is read and
* included in the exception message.
* </p>
*
* @param jsonFactory JSON factory
* @param response HTTP response
* @return new instance of {@link GoogleJsonResponseException}
*/
public static GoogleJsonResponseException from(JsonFactory jsonFactory, HttpResponse response) {
// details
Preconditions.checkNotNull(jsonFactory);
GoogleJsonError details = null;
String detailString = null;
try {
if (!response.isSuccessStatusCode()
&& HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, response.getContentType())
&& response.getContent() != null) {
JsonParser parser = null;
try {
parser = jsonFactory.createJsonParser(response.getContent());
JsonToken currentToken = parser.getCurrentToken();
// token is null at start, so get next token
if (currentToken == null) {
currentToken = parser.nextToken();
}
// check for empty content
if (currentToken != null) {
// make sure there is an "error" key
parser.skipToKey("error");
if (parser.getCurrentToken() != JsonToken.END_OBJECT) {
details = parser.parseAndClose(GoogleJsonError.class, null);
detailString = details.toPrettyString();
}
}
} catch (IOException exception) {
// it would be bad to throw an exception while throwing an exception
exception.printStackTrace();
} finally {
if (parser == null) {
response.ignore();
} else if (details == null) {
parser.close();
}
}
} else {
detailString = response.parseAsString();
}
} catch (IOException exception) {
// it would be bad to throw an exception while throwing an exception
exception.printStackTrace();
}
// message
StringBuilder message = HttpResponseException.computeMessageBuffer(response);
if (!com.google.common.base.Strings.isNullOrEmpty(detailString)) {
message.append(StringUtils.LINE_SEPARATOR).append(detailString);
}
// result
return new GoogleJsonResponseException(response, details, message.toString());
}
/**
* Executes an HTTP request using {@link HttpRequest#execute()}, but throws a
* {@link GoogleJsonResponseException} on error instead of {@link HttpResponseException}.
*
* <p>
* Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is
* no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the
* response stream is properly closed. Example usage:
* </p>
*
* <pre>
HttpResponse response = GoogleJsonResponseException.execute(jsonFactory, request);
try {
// process the HTTP response object
} finally {
response.disconnect();
}
* </pre>
*
* @param jsonFactory JSON factory
* @param request HTTP request
* @return HTTP response for an HTTP success code (or error code if
* {@link HttpRequest#getThrowExceptionOnExecuteError()})
* @throws GoogleJsonResponseException for an HTTP error code (only if not
* {@link HttpRequest#getThrowExceptionOnExecuteError()})
* @throws IOException some other kind of I/O exception
* @since 1.7
*/
public static HttpResponse execute(JsonFactory jsonFactory, HttpRequest request)
throws GoogleJsonResponseException, IOException {
Preconditions.checkNotNull(jsonFactory);
boolean originalThrowExceptionOnExecuteError = request.getThrowExceptionOnExecuteError();
if (originalThrowExceptionOnExecuteError) {
request.setThrowExceptionOnExecuteError(false);
}
HttpResponse response = request.execute();
request.setThrowExceptionOnExecuteError(originalThrowExceptionOnExecuteError);
if (!originalThrowExceptionOnExecuteError || response.isSuccessStatusCode()) {
return response;
}
throw GoogleJsonResponseException.from(jsonFactory, response);
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.json;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
/**
* Data class representing a container of {@link GoogleJsonError}.
*
* @since 1.9
* @author rmistry@google.com (Ravi Mistry)
*/
public class GoogleJsonErrorContainer extends GenericJson {
@Key
private GoogleJsonError error;
/** Returns the {@link GoogleJsonError}. */
public final GoogleJsonError getError() {
return error;
}
/** Sets the {@link GoogleJsonError}. */
public final void setError(GoogleJsonError error) {
this.error = error;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.
*/
/**
* Google API's.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis;
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.RefreshTokenRequest;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.auth.oauth2.TokenResponseException;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import java.io.IOException;
/**
* Google-specific implementation of the OAuth 2.0 request to refresh an access token using a
* refresh token as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-23#section-6">Refreshing an Access
* Token</a>.
*
* <p>
* Use {@link GoogleCredential} to access protected resources from the resource server using the
* {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw
* {@link TokenResponseException}.
* </p>
*
* <p>
* Sample usage:
* </p>
*
* <pre>
static void refreshAccessToken() throws IOException {
try {
TokenResponse response =
new GoogleRefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(),
"tGzv3JOkF0XG5Qx2TlKWIA", "s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw").execute();
System.out.println("Access token: " + response.getAccessToken());
} catch (TokenResponseException e) {
if (e.getDetails() != null) {
System.err.println("Error: " + e.getDetails().getError());
if (e.getDetails().getErrorDescription() != null) {
System.err.println(e.getDetails().getErrorDescription());
}
if (e.getDetails().getErrorUri() != null) {
System.err.println(e.getDetails().getErrorUri());
}
} else {
System.err.println(e.getMessage());
}
}
}
* </pre>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleRefreshTokenRequest extends RefreshTokenRequest {
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param refreshToken refresh token issued to the client
* @param clientId client identifier issued to the client during the registration process
* @param clientSecret client secret
*/
public GoogleRefreshTokenRequest(HttpTransport transport, JsonFactory jsonFactory,
String refreshToken, String clientId, String clientSecret) {
super(transport, jsonFactory, new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL),
refreshToken);
setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
}
@Override
public GoogleRefreshTokenRequest setRequestInitializer(
HttpRequestInitializer requestInitializer) {
return (GoogleRefreshTokenRequest) super.setRequestInitializer(requestInitializer);
}
@Override
public GoogleRefreshTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) {
return (GoogleRefreshTokenRequest) super.setTokenServerUrl(tokenServerUrl);
}
@Override
public GoogleRefreshTokenRequest setScopes(String... scopes) {
return (GoogleRefreshTokenRequest) super.setScopes(scopes);
}
@Override
public GoogleRefreshTokenRequest setScopes(Iterable<String> scopes) {
return (GoogleRefreshTokenRequest) super.setScopes(scopes);
}
@Override
public GoogleRefreshTokenRequest setGrantType(String grantType) {
return (GoogleRefreshTokenRequest) super.setGrantType(grantType);
}
@Override
public GoogleRefreshTokenRequest setClientAuthentication(
HttpExecuteInterceptor clientAuthentication) {
return (GoogleRefreshTokenRequest) super.setClientAuthentication(clientAuthentication);
}
@Override
public GoogleRefreshTokenRequest setRefreshToken(String refreshToken) {
return (GoogleRefreshTokenRequest) super.setRefreshToken(refreshToken);
}
@Override
public GoogleTokenResponse execute() throws IOException {
return executeUnparsed().parseAs(GoogleTokenResponse.class);
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.auth.oauth2.TokenResponseException;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.common.base.Preconditions;
import java.io.IOException;
/**
* Google-specific implementation of the OAuth 2.0 request for an access token based on an
* authorization code (as specified in <a
* href="http://code.google.com/apis/accounts/docs/OAuth2WebServer.html">Using OAuth 2.0 for Web
* Server Applications</a>).
*
* <p>
* Use {@link GoogleCredential} to access protected resources from the resource server using the
* {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw
* {@link TokenResponseException}.
* </p>
*
* <p>
* Sample usage:
* </p>
*
* <pre>
static void requestAccessToken() throws IOException {
try {
GoogleTokenResponse response =
new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
"812741506391.apps.googleusercontent.com", "{client_secret}",
"4/P7q7W91a-oMsCeLvIaQm6bTrgtp7", "https://oauth2-login-demo.appspot.com/code")
.execute();
System.out.println("Access token: " + response.getAccessToken());
} catch (TokenResponseException e) {
if (e.getDetails() != null) {
System.err.println("Error: " + e.getDetails().getError());
if (e.getDetails().getErrorDescription() != null) {
System.err.println(e.getDetails().getErrorDescription());
}
if (e.getDetails().getErrorUri() != null) {
System.err.println(e.getDetails().getErrorUri());
}
} else {
System.err.println(e.getMessage());
}
}
}
* </pre>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleAuthorizationCodeTokenRequest extends AuthorizationCodeTokenRequest {
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param clientId client identifier issued to the client during the registration process
* @param clientSecret client secret
* @param code authorization code generated by the authorization server
* @param redirectUri redirect URL parameter matching the redirect URL parameter in the
* authorization request (see {@link #setRedirectUri(String)}
*/
public GoogleAuthorizationCodeTokenRequest(HttpTransport transport,
JsonFactory jsonFactory,
String clientId,
String clientSecret,
String code,
String redirectUri) {
this(transport,
jsonFactory,
GoogleOAuthConstants.TOKEN_SERVER_URL,
clientId,
clientSecret,
code,
redirectUri);
}
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param tokenServerEncodedUrl token server encoded URL
* @param clientId client identifier issued to the client during the registration process
* @param clientSecret client secret
* @param code authorization code generated by the authorization server
* @param redirectUri redirect URL parameter matching the redirect URL parameter in the
* authorization request (see {@link #setRedirectUri(String)}
*
* @since 1.12
*/
public GoogleAuthorizationCodeTokenRequest(HttpTransport transport,
JsonFactory jsonFactory,
String tokenServerEncodedUrl,
String clientId,
String clientSecret,
String code,
String redirectUri) {
super(transport, jsonFactory, new GenericUrl(tokenServerEncodedUrl), code);
setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
setRedirectUri(redirectUri);
}
@Override
public GoogleAuthorizationCodeTokenRequest setRequestInitializer(
HttpRequestInitializer requestInitializer) {
return (GoogleAuthorizationCodeTokenRequest) super.setRequestInitializer(requestInitializer);
}
@Override
public GoogleAuthorizationCodeTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) {
return (GoogleAuthorizationCodeTokenRequest) super.setTokenServerUrl(tokenServerUrl);
}
@Override
public GoogleAuthorizationCodeTokenRequest setScopes(String... scopes) {
return (GoogleAuthorizationCodeTokenRequest) super.setScopes(scopes);
}
@Override
public GoogleAuthorizationCodeTokenRequest setScopes(Iterable<String> scopes) {
return (GoogleAuthorizationCodeTokenRequest) super.setScopes(scopes);
}
@Override
public GoogleAuthorizationCodeTokenRequest setGrantType(String grantType) {
return (GoogleAuthorizationCodeTokenRequest) super.setGrantType(grantType);
}
@Override
public GoogleAuthorizationCodeTokenRequest setClientAuthentication(
HttpExecuteInterceptor clientAuthentication) {
Preconditions.checkNotNull(clientAuthentication);
return (GoogleAuthorizationCodeTokenRequest) super.setClientAuthentication(
clientAuthentication);
}
@Override
public GoogleAuthorizationCodeTokenRequest setCode(String code) {
return (GoogleAuthorizationCodeTokenRequest) super.setCode(code);
}
@Override
public GoogleAuthorizationCodeTokenRequest setRedirectUri(String redirectUri) {
Preconditions.checkNotNull(redirectUri);
return (GoogleAuthorizationCodeTokenRequest) super.setRedirectUri(redirectUri);
}
@Override
public GoogleTokenResponse execute() throws IOException {
return executeUnparsed().parseAs(GoogleTokenResponse.class);
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.auth.openidconnect.IdTokenResponse;
import java.io.IOException;
import java.security.GeneralSecurityException;
/**
* Google OAuth 2.0 JSON model for a successful access token response as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-23#section-5.1">Successful Response</a>,
* including an ID token as specified in <a
* href="http://openid.net/specs/openid-connect-session-1_0.html">OpenID Connect Session Management
* 1.0</a>.
*
* <p>
* This response object is the result of {@link GoogleAuthorizationCodeTokenRequest#execute()} and
* {@link GoogleRefreshTokenRequest#execute()}. Use {@link #parseIdToken()} to parse the
* {@link GoogleIdToken} and then call {@link GoogleIdToken#verify(GoogleIdTokenVerifier)} to verify
* it (or just call {@link #verifyIdToken(GoogleIdTokenVerifier)}).
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleTokenResponse extends IdTokenResponse {
@Override
public GoogleTokenResponse setIdToken(String idToken) {
return (GoogleTokenResponse) super.setIdToken(idToken);
}
@Override
public GoogleTokenResponse setAccessToken(String accessToken) {
return (GoogleTokenResponse) super.setAccessToken(accessToken);
}
@Override
public GoogleTokenResponse setTokenType(String tokenType) {
return (GoogleTokenResponse) super.setTokenType(tokenType);
}
@Override
public GoogleTokenResponse setExpiresInSeconds(Long expiresIn) {
return (GoogleTokenResponse) super.setExpiresInSeconds(expiresIn);
}
@Override
public GoogleTokenResponse setRefreshToken(String refreshToken) {
return (GoogleTokenResponse) super.setRefreshToken(refreshToken);
}
@Override
public GoogleTokenResponse setScope(String scope) {
return (GoogleTokenResponse) super.setScope(scope);
}
@Override
public GoogleIdToken parseIdToken() throws IOException {
return GoogleIdToken.parse(getFactory(), getIdToken());
}
/**
* Verifies the ID token as specified in {@link GoogleIdTokenVerifier#verify} by passing it
* {@link #parseIdToken}.
*
* @param verifier Google ID token verifier
*/
public boolean verifyIdToken(GoogleIdTokenVerifier verifier)
throws GeneralSecurityException, IOException {
return verifier.verify(parseIdToken());
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.auth.jsontoken.JsonWebSignature;
import com.google.api.client.auth.jsontoken.JsonWebToken;
import com.google.api.client.auth.jsontoken.RsaSHA256Signer;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.CredentialRefreshListener;
import com.google.api.client.auth.oauth2.CredentialStore;
import com.google.api.client.auth.oauth2.TokenRequest;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.auth.security.PrivateKeys;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.Details;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.Clock;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.List;
/**
* Thread-safe Google-specific implementation of the OAuth 2.0 helper for accessing protected
* resources using an access token, as well as optionally refreshing the access token when it
* expires using a refresh token.
*
* <p>
* There are three modes supported: access token only, refresh token flow, and service account flow
* (with or without impersonating a user).
* </p>
*
* <p>
* If all you have is an access token, you simply pass the {@link TokenResponse} to the credential
* using {@link Builder#setFromTokenResponse(TokenResponse)}. Google credential uses
* {@link BearerToken#authorizationHeaderAccessMethod()} as the access method. Sample usage:
* </p>
*
* <pre>
public static GoogleCredential createCredentialWithAccessTokenOnly(
HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) {
return new GoogleCredential().setFromTokenResponse(tokenResponse);
}
* </pre>
*
* <p>
* If you have a refresh token, it is similar to the case of access token only, but you additionally
* need to pass the credential the client secrets using
* {@link Builder#setClientSecrets(GoogleClientSecrets)} or
* {@link Builder#setClientSecrets(String, String)}. Google credential uses
* {@link GoogleOAuthConstants#TOKEN_SERVER_URL} as the token server URL, and
* {@link ClientParametersAuthentication} with the client ID and secret as the client
* authentication. Sample usage:
* </p>
*
* <pre>
public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport,
JsonFactory jsonFactory, GoogleClientSecrets clientSecrets, TokenResponse tokenResponse) {
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(jsonFactory)
.setClientSecrets(clientSecrets)
.build()
.setFromTokenResponse(tokenResponse);
}
* </pre>
*
* <p>
* The <a href="https://developers.google.com/accounts/docs/OAuth2ServiceAccount">service account
* flow</a> is used when you want to access data owned by your client application. You download the
* private key in a {@code .p12} file from the Google APIs Console. Use
* {@link Builder#setServiceAccountId(String)},
* {@link Builder#setServiceAccountPrivateKeyFromP12File(File)}, and
* {@link Builder#setServiceAccountScopes(String...)}. Sample usage:
* </p>
*
* <pre>
public static GoogleCredential createCredentialForServiceAccount(
HttpTransport transport,
JsonFactory jsonFactory,
String serviceAccountId,
Iterable<String> serviceAccountScopes,
File p12File) throws GeneralSecurityException, IOException {
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountId)
.setServiceAccountScopes(serviceAccountScopes)
.setServiceAccountPrivateKeyFromP12File(p12File)
.build();
}
* </pre>
*
* <p>
* You can also use the service account flow to impersonate a user in a domain that you own. This is
* very similar to the service account flow above, but you additionally call
* {@link Builder#setServiceAccountUser(String)}. Sample usage:
* </p>
*
* <pre>
public static GoogleCredential createCredentialForServiceAccountImpersonateUser(
HttpTransport transport,
JsonFactory jsonFactory,
String serviceAccountId,
Iterable<String> serviceAccountScopes,
File p12File,
String serviceAccountUser) throws GeneralSecurityException, IOException {
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountId)
.setServiceAccountScopes(serviceAccountScopes)
.setServiceAccountPrivateKeyFromP12File(p12File)
.setServiceAccountUser(serviceAccountUser)
.build();
}
* </pre>
*
* <p>
* If you need to persist the access token in a data store, use {@link CredentialStore} and
* {@link Builder#addRefreshListener(CredentialRefreshListener)}.
* </p>
*
* <p>
* If you have a custom request initializer, request execute interceptor, or unsuccessful response
* handler, take a look at the sample usage for {@link HttpExecuteInterceptor} and
* {@link HttpUnsuccessfulResponseHandler}, which are interfaces that this class also implements.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleCredential extends Credential {
/**
* Service account ID (typically an e-mail address) or {@code null} if not using the service
* account flow.
*/
private String serviceAccountId;
/**
* Space-separated OAuth scopes to use with the the service account flow or {@code null} if not
* using the service account flow.
*/
private String serviceAccountScopes;
/**
* Private key to use with the the service account flow or {@code null} if not using the service
* account flow.
*/
private PrivateKey serviceAccountPrivateKey;
/**
* Email address of the user the application is trying to impersonate in the service account flow
* or {@code null} for none or if not using the service account flow.
*/
private String serviceAccountUser;
/**
* Constructor with the ability to access protected resources, but not refresh tokens.
*
* <p>
* To use with the ability to refresh tokens, use {@link Builder}.
* </p>
*/
public GoogleCredential() {
super(BearerToken.authorizationHeaderAccessMethod(), null, null,
GoogleOAuthConstants.TOKEN_SERVER_URL, null, null, null);
}
/**
* @param method method of presenting the access token to the resource server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport for executing refresh token request or {@code null} if not
* refreshing tokens
* @param jsonFactory JSON factory to use for parsing response for refresh token request or
* {@code null} if not refreshing tokens
* @param tokenServerEncodedUrl encoded token server URL or {@code null} if not refreshing tokens
* @param clientAuthentication client authentication or {@code null} for none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})
* @param requestInitializer HTTP request initializer for refresh token requests to the token
* server or {@code null} for none.
* @param refreshListeners listeners for refresh token results or {@code null} for none
* @param serviceAccountId service account ID (typically an e-mail address) or {@code null} if not
* using the service account flow
* @param serviceAccountScopes space-separated OAuth scopes to use with the the service account
* flow or {@code null} if not using the service account flow
* @param serviceAccountPrivateKey private key to use with the the service account flow or
* {@code null} if not using the service account flow
* @param serviceAccountUser email address of the user the application is trying to impersonate in
* the service account flow or {@code null} for none or if not using the service account
* flow
*/
protected GoogleCredential(AccessMethod method, HttpTransport transport, JsonFactory jsonFactory,
String tokenServerEncodedUrl, HttpExecuteInterceptor clientAuthentication,
HttpRequestInitializer requestInitializer, List<CredentialRefreshListener> refreshListeners,
String serviceAccountId, String serviceAccountScopes, PrivateKey serviceAccountPrivateKey,
String serviceAccountUser) {
this(method, transport, jsonFactory, tokenServerEncodedUrl, clientAuthentication,
requestInitializer, refreshListeners, serviceAccountId, serviceAccountScopes,
serviceAccountPrivateKey, serviceAccountUser, Clock.SYSTEM);
}
/**
* @param method method of presenting the access token to the resource server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport for executing refresh token request or {@code null} if not
* refreshing tokens
* @param jsonFactory JSON factory to use for parsing response for refresh token request or
* {@code null} if not refreshing tokens
* @param tokenServerEncodedUrl encoded token server URL or {@code null} if not refreshing tokens
* @param clientAuthentication client authentication or {@code null} for none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})
* @param requestInitializer HTTP request initializer for refresh token requests to the token
* server or {@code null} for none.
* @param refreshListeners listeners for refresh token results or {@code null} for none
* @param serviceAccountId service account ID (typically an e-mail address) or {@code null} if not
* using the service account flow
* @param serviceAccountScopes space-separated OAuth scopes to use with the the service account
* flow or {@code null} if not using the service account flow
* @param serviceAccountPrivateKey private key to use with the the service account flow or
* {@code null} if not using the service account flow
* @param serviceAccountUser email address of the user the application is trying to impersonate in
* the service account flow or {@code null} for none or if not using the service account
* flow
* @param clock The clock to use for expiration check
* @since 1.9
*/
protected GoogleCredential(AccessMethod method, HttpTransport transport, JsonFactory jsonFactory,
String tokenServerEncodedUrl, HttpExecuteInterceptor clientAuthentication,
HttpRequestInitializer requestInitializer, List<CredentialRefreshListener> refreshListeners,
String serviceAccountId, String serviceAccountScopes, PrivateKey serviceAccountPrivateKey,
String serviceAccountUser, Clock clock) {
super(method, transport, jsonFactory, tokenServerEncodedUrl, clientAuthentication,
requestInitializer, refreshListeners, clock);
if (serviceAccountPrivateKey == null) {
Preconditions.checkArgument(
serviceAccountId == null && serviceAccountScopes == null && serviceAccountUser == null);
} else {
this.serviceAccountId = Preconditions.checkNotNull(serviceAccountId);
this.serviceAccountScopes = Preconditions.checkNotNull(serviceAccountScopes);
this.serviceAccountPrivateKey = serviceAccountPrivateKey;
this.serviceAccountUser = serviceAccountUser;
}
}
@Override
public GoogleCredential setAccessToken(String accessToken) {
return (GoogleCredential) super.setAccessToken(accessToken);
}
@Override
public GoogleCredential setRefreshToken(String refreshToken) {
if (refreshToken != null) {
Preconditions.checkArgument(
getJsonFactory() != null && getTransport() != null && getClientAuthentication() != null,
"Please use the Builder and call setJsonFactory, setTransport and setClientSecrets");
}
return (GoogleCredential) super.setRefreshToken(refreshToken);
}
@Override
public GoogleCredential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds) {
return (GoogleCredential) super.setExpirationTimeMilliseconds(expirationTimeMilliseconds);
}
@Override
public GoogleCredential setExpiresInSeconds(Long expiresIn) {
return (GoogleCredential) super.setExpiresInSeconds(expiresIn);
}
@Override
public GoogleCredential setFromTokenResponse(TokenResponse tokenResponse) {
return (GoogleCredential) super.setFromTokenResponse(tokenResponse);
}
@Override
protected TokenResponse executeRefreshToken() throws IOException {
if (serviceAccountPrivateKey == null) {
return super.executeRefreshToken();
}
// service accounts
JsonWebSignature.Header header = new JsonWebSignature.Header();
header.setAlgorithm("RS256");
header.setType("JWT");
JsonWebToken.Payload payload = new JsonWebToken.Payload(getClock());
long currentTime = getClock().currentTimeMillis();
payload.setIssuer(serviceAccountId).setAudience(getTokenServerEncodedUrl())
.setIssuedAtTimeSeconds(currentTime / 1000)
.setExpirationTimeSeconds(currentTime / 1000 + 3600).setPrincipal(serviceAccountUser);
payload.put("scope", serviceAccountScopes);
try {
String assertion =
RsaSHA256Signer.sign(serviceAccountPrivateKey, getJsonFactory(), header, payload);
TokenRequest request = new TokenRequest(
getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()),
"assertion");
request.put("assertion_type", "http://oauth.net/grant_type/jwt/1.0/bearer");
request.put("assertion", assertion);
return request.execute();
} catch (GeneralSecurityException exception) {
IOException e = new IOException();
e.initCause(exception);
throw e;
}
}
/**
* Returns the service account ID (typically an e-mail address) or {@code null} if not using the
* service account flow.
*/
public final String getServiceAccountId() {
return serviceAccountId;
}
/**
* Returns the space-separated OAuth scopes to use with the the service account flow or
* {@code null} if not using the service account flow.
*/
public final String getServiceAccountScopes() {
return serviceAccountScopes;
}
/**
* Returns the private key to use with the the service account flow or {@code null} if not using
* the service account flow.
*/
public final PrivateKey getServiceAccountPrivateKey() {
return serviceAccountPrivateKey;
}
/**
* Returns the email address of the user the application is trying to impersonate in the service
* account flow or {@code null} for none or if not using the service account flow.
*/
public final String getServiceAccountUser() {
return serviceAccountUser;
}
/**
* Google credential builder.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
public static class Builder extends Credential.Builder {
/** Service account ID (typically an e-mail address) or {@code null} for none. */
private String serviceAccountId;
/**
* Space-separated OAuth scopes to use with the the service account flow or {@code null} for
* none.
*/
private String serviceAccountScopes;
/** Private key to use with the the service account flow or {@code null} for none. */
private PrivateKey serviceAccountPrivateKey;
/**
* Email address of the user the application is trying to impersonate in the service account
* flow or {@code null} for none.
*/
private String serviceAccountUser;
public Builder() {
super(BearerToken.authorizationHeaderAccessMethod());
setTokenServerEncodedUrl(GoogleOAuthConstants.TOKEN_SERVER_URL);
}
@Override
public GoogleCredential build() {
return new GoogleCredential(getMethod(), getTransport(), getJsonFactory(),
getTokenServerUrl() == null ? null : getTokenServerUrl().build(),
getClientAuthentication(), getRequestInitializer(), getRefreshListeners(),
serviceAccountId, serviceAccountScopes, serviceAccountPrivateKey, serviceAccountUser,
getClock());
}
@Override
public Builder setTransport(HttpTransport transport) {
return (Builder) super.setTransport(transport);
}
@Override
public Builder setJsonFactory(JsonFactory jsonFactory) {
return (Builder) super.setJsonFactory(jsonFactory);
}
/**
* @since 1.9
*/
@Override
public Builder setClock(Clock clock) {
return (Builder) super.setClock(clock);
}
/**
* Sets the client identifier and secret.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setClientSecrets(String clientId, String clientSecret) {
setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
return this;
}
/**
* Sets the client secrets.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setClientSecrets(GoogleClientSecrets clientSecrets) {
Details details = clientSecrets.getDetails();
setClientAuthentication(
new ClientParametersAuthentication(details.getClientId(), details.getClientSecret()));
return this;
}
/** Returns the service account ID (typically an e-mail address) or {@code null} for none. */
public final String getServiceAccountId() {
return serviceAccountId;
}
/**
* Sets the service account ID (typically an e-mail address) or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setServiceAccountId(String serviceAccountId) {
this.serviceAccountId = serviceAccountId;
return this;
}
/**
* Returns the space-separated OAuth scopes to use with the the service account flow or
* {@code null} for none.
*/
public final String getServiceAccountScopes() {
return serviceAccountScopes;
}
/**
* Sets the space-separated OAuth scopes to use with the the service account flow or
* {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param serviceAccountScopes list of scopes to be joined by a space separator (or a single
* value containing multiple space-separated scopes)
*/
public Builder setServiceAccountScopes(String... serviceAccountScopes) {
return setServiceAccountScopes(
serviceAccountScopes == null ? null : Arrays.asList(serviceAccountScopes));
}
/**
* Sets the space-separated OAuth scopes to use with the the service account flow or
* {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param serviceAccountScopes list of scopes to be joined by a space separator (or a single
* value containing multiple space-separated scopes)
*/
public Builder setServiceAccountScopes(Iterable<String> serviceAccountScopes) {
this.serviceAccountScopes =
serviceAccountScopes == null ? null : Joiner.on(' ').join(serviceAccountScopes);
return this;
}
/**
* Returns the private key to use with the the service account flow or {@code null} for none.
*/
public final PrivateKey getServiceAccountPrivateKey() {
return serviceAccountPrivateKey;
}
/**
* Sets the private key to use with the the service account flow or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setServiceAccountPrivateKey(PrivateKey serviceAccountPrivateKey) {
this.serviceAccountPrivateKey = serviceAccountPrivateKey;
return this;
}
/**
* Sets the private key to use with the the service account flow or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param p12File input stream to the p12 file (closed at the end of this method in a finally
* block)
*/
public Builder setServiceAccountPrivateKeyFromP12File(File p12File)
throws GeneralSecurityException, IOException {
serviceAccountPrivateKey =
PrivateKeys.loadFromP12File(p12File, "notasecret", "privatekey", "notasecret");
return this;
}
/**
* Sets the private key to use with the the service account flow or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param pemFile input stream to the PEM file (closed at the end of this method in a finally
* block)
* @since 1.13
*/
public Builder setServiceAccountPrivateKeyFromPemFile(File pemFile)
throws GeneralSecurityException, IOException {
serviceAccountPrivateKey =
PrivateKeys.loadFromPkcs8PemFile(pemFile);
return this;
}
/**
* Returns the email address of the user the application is trying to impersonate in the service
* account flow or {@code null} for none.
*/
public final String getServiceAccountUser() {
return serviceAccountUser;
}
/**
* Sets the email address of the user the application is trying to impersonate in the service
* account flow or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setServiceAccountUser(String serviceAccountUser) {
this.serviceAccountUser = serviceAccountUser;
return this;
}
@Override
public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) {
return (Builder) super.setRequestInitializer(requestInitializer);
}
@Override
public Builder addRefreshListener(CredentialRefreshListener refreshListener) {
return (Builder) super.addRefreshListener(refreshListener);
}
@Override
public Builder setRefreshListeners(List<CredentialRefreshListener> refreshListeners) {
return (Builder) super.setRefreshListeners(refreshListeners);
}
@Override
public Builder setTokenServerUrl(GenericUrl tokenServerUrl) {
return (Builder) super.setTokenServerUrl(tokenServerUrl);
}
@Override
public Builder setTokenServerEncodedUrl(String tokenServerEncodedUrl) {
return (Builder) super.setTokenServerEncodedUrl(tokenServerEncodedUrl);
}
@Override
public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {
return (Builder) super.setClientAuthentication(clientAuthentication);
}
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
/**
* Constants for Google's OAuth 2.0 implementation.
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleOAuthConstants {
/** Encoded URL of Google's end-user authorization server. */
public static final String AUTHORIZATION_SERVER_URL = "https://accounts.google.com/o/oauth2/auth";
/** Encoded URL of Google's token server. */
public static final String TOKEN_SERVER_URL = "https://accounts.google.com/o/oauth2/token";
/**
* Redirect URI to use for an installed application as specified in <a
* href="http://code.google.com/apis/accounts/docs/OAuth2InstalledApp.html">Using OAuth 2.0 for
* Installed Applications</a>.
*/
public static final String OOB_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
private GoogleOAuthConstants() {
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.
*/
/**
* Google's additions to OAuth 2.0 authorization as specified in <a
* href="http://code.google.com/apis/accounts/docs/OAuth2.html">Using OAuth 2.0 to Access Google
* APIs</a>.
*
* <p>
* Before using this library, you must register your application at the <a
* href="https://code.google.com/apis/console#access">APIs Console</a>. The result of this
* registration process is a set of values that are known to both Google and your application, such
* as the "Client ID", "Client Secret", and "Redirect URIs".
* </p>
*
* <p>
* These are the typical steps of the web server flow based on an authorization code, as specified
* in <a href="http://code.google.com/apis/accounts/docs/OAuth2WebServer.html">Using OAuth 2.0 for
* Web Server Applications</a>:
* <ul>
* <li>Redirect the end user in the browser to the authorization page using
* {@link com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl} to grant
* your application access to the end user's protected data.</li>
* <li>Process the authorization response using
* {@link com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl} to parse the authorization
* code.</li>
* <li>Request an access token and possibly a refresh token using
* {@link com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest}.</li>
* <li>Access protected resources using
* {@link com.google.api.client.googleapis.auth.oauth2.GoogleCredential}. Expired access tokens will
* automatically be refreshed using the refresh token (if applicable).</li>
* </ul>
* </p>
*
* <p>
* These are the typical steps of the the browser-based client flow specified in <a
* href="http://code.google.com/apis/accounts/docs/OAuth2UserAgent.html">Using OAuth 2.0 for
* Client-side Applications</a>:
* <ul>
* <li>Redirect the end user in the browser to the authorization page using
* {@link com.google.api.client.googleapis.auth.oauth2.GoogleBrowserClientRequestUrl} to grant your
* browser application access to the end user's protected data.</li>
* <li>Use the <a href="http://code.google.com/p/google-api-javascript-client/">Google API Client
* library for JavaScript</a> to process the access token found in the URL fragment at the redirect
* URI registered at the <a href="https://code.google.com/apis/console#access">APIs Console</a>.
* </li>
* </ul>
* </p>
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library.</b>
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.auth.oauth2;
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential.AccessMethod;
import com.google.api.client.auth.oauth2.CredentialStore;
import com.google.api.client.auth.oauth2.TokenRequest;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.Clock;
import com.google.common.base.Preconditions;
import java.util.Collections;
/**
* Thread-safe Google OAuth 2.0 authorization code flow that manages and persists end-user
* credentials.
*
* <p>
* This is designed to simplify the flow in which an end-user authorizes the application to access
* their protected data, and then the application has access to their data based on an access token
* and a refresh token to refresh that access token when it expires.
* </p>
*
* <p>
* The first step is to call {@link #loadCredential(String)} based on the known user ID to check if
* the end-user's credentials are already known. If not, call {@link #newAuthorizationUrl()} and
* direct the end-user's browser to an authorization page. The web browser will then redirect to the
* redirect URL with a {@code "code"} query parameter which can then be used to request an access
* token using {@link #newTokenRequest(String)}. Finally, use
* {@link #createAndStoreCredential(TokenResponse, String)} to store and obtain a credential for
* accessing protected resources.
* </p>
*
* <p>
* The default for the {@code approval_prompt} and {@code access_type} parameters is {@code null}.
* For web applications that means {@code "approval_prompt=auto&access_type=online"} and for
* installed applications that means {@code "approval_prompt=force&access_type=offline"}. To
* override the default, you need to explicitly call {@link Builder#setApprovalPrompt(String)} and
* {@link Builder#setAccessType(String)}.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleAuthorizationCodeFlow extends AuthorizationCodeFlow {
/**
* Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to
* force the approval UI to show) or {@code null} for the default behavior.
*/
private final String approvalPrompt;
/**
* Access type ({@code "online"} to request online access or {@code "offline"} to request offline
* access) or {@code null} for the default behavior.
*/
private final String accessType;
/**
* @param method method of presenting the access token to the resource server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param tokenServerUrl token server URL
* @param clientAuthentication client authentication or {@code null} for none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})
* @param clientId client identifier
* @param authorizationServerEncodedUrl authorization server encoded URL
* @param credentialStore credential persistence store or {@code null} for none
* @param requestInitializer HTTP request initializer or {@code null} for none
* @param scopes space-separated list of scopes or {@code null} for none
* @param accessType access type ({@code "online"} to request online access or {@code "offline"}
* to request offline access) or {@code null} for the default behavior
* @param approvalPrompt Prompt for consent behavior ({@code "auto"} to request auto-approval or
* {@code "force"} to force the approval UI to show) or {@code null} for the default
* behavior
*/
protected GoogleAuthorizationCodeFlow(AccessMethod method,
HttpTransport transport,
JsonFactory jsonFactory,
GenericUrl tokenServerUrl,
HttpExecuteInterceptor clientAuthentication,
String clientId,
String authorizationServerEncodedUrl,
CredentialStore credentialStore,
HttpRequestInitializer requestInitializer,
String scopes,
String accessType,
String approvalPrompt) {
super(method,
transport,
jsonFactory,
tokenServerUrl,
clientAuthentication,
clientId,
authorizationServerEncodedUrl,
credentialStore,
requestInitializer,
scopes);
this.accessType = accessType;
this.approvalPrompt = approvalPrompt;
}
@Override
public GoogleAuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
// don't need to specify clientId & clientSecret because specifying clientAuthentication
// don't want to specify redirectUri to give control of it to user of this class
return new GoogleAuthorizationCodeTokenRequest(getTransport(),
getJsonFactory(),
getTokenServerEncodedUrl(),
"",
"",
authorizationCode,
"").setClientAuthentication(getClientAuthentication())
.setRequestInitializer(getRequestInitializer()).setScopes(getScopes());
}
@Override
public GoogleAuthorizationCodeRequestUrl newAuthorizationUrl() {
// don't want to specify redirectUri to give control of it to user of this class
return new GoogleAuthorizationCodeRequestUrl(getAuthorizationServerEncodedUrl(),
getClientId(),
"",
Collections.singleton(getScopes()))
.setAccessType(accessType)
.setApprovalPrompt(approvalPrompt);
}
/**
* Returns the approval prompt behavior ({@code "auto"} to request auto-approval or
* {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of
* {@code "auto"}.
*/
public final String getApprovalPrompt() {
return approvalPrompt;
}
/**
* Returns the access type ({@code "online"} to request online access or {@code "offline"} to
* request offline access) or {@code null} for the default behavior of {@code "online"}.
*/
public final String getAccessType() {
return accessType;
}
/**
* Google authorization code flow builder.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
public static class Builder extends AuthorizationCodeFlow.Builder {
/**
* Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to
* force the approval UI to show) or {@code null} for the default behavior.
*/
private String approvalPrompt;
/**
* Access type ({@code "online"} to request online access or {@code "offline"} to request
* offline access) or {@code null} for the default behavior.
*/
private String accessType;
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param clientId client identifier
* @param clientSecret client secret
* @param scopes list of scopes to be joined by a space separator (or a single value containing
* multiple space-separated scopes)
*/
public Builder(HttpTransport transport, JsonFactory jsonFactory, String clientId,
String clientSecret, Iterable<String> scopes) {
super(BearerToken.authorizationHeaderAccessMethod(),
transport,
jsonFactory,
new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL),
new ClientParametersAuthentication(clientId, clientSecret),
clientId,
GoogleOAuthConstants.AUTHORIZATION_SERVER_URL);
setScopes(Preconditions.checkNotNull(scopes));
}
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param clientSecrets Google client secrets
* @param scopes list of scopes to be joined by a space separator (or a single value containing
* multiple space-separated scopes)
*/
public Builder(HttpTransport transport, JsonFactory jsonFactory,
GoogleClientSecrets clientSecrets, Iterable<String> scopes) {
super(BearerToken.authorizationHeaderAccessMethod(),
transport,
jsonFactory,
new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL),
new ClientParametersAuthentication(clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret()),
clientSecrets.getDetails().getClientId(),
GoogleOAuthConstants.AUTHORIZATION_SERVER_URL);
setScopes(Preconditions.checkNotNull(scopes));
}
@Override
public GoogleAuthorizationCodeFlow build() {
return new GoogleAuthorizationCodeFlow(getMethod(),
getTransport(),
getJsonFactory(),
getTokenServerUrl(),
getClientAuthentication(),
getClientId(),
getAuthorizationServerEncodedUrl(),
getCredentialStore(),
getRequestInitializer(),
getScopes(),
accessType,
approvalPrompt);
}
@Override
public Builder setCredentialStore(CredentialStore credentialStore) {
return (Builder) super.setCredentialStore(credentialStore);
}
@Override
public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) {
return (Builder) super.setRequestInitializer(requestInitializer);
}
@Override
public Builder setScopes(Iterable<String> scopes) {
return (Builder) super.setScopes(scopes);
}
@Override
public Builder setScopes(String... scopes) {
return (Builder) super.setScopes(scopes);
}
/**
* @since 1.11
*/
@Override
public Builder setMethod(AccessMethod method) {
return (Builder) super.setMethod(method);
}
/**
* @since 1.11
*/
@Override
public Builder setTransport(HttpTransport transport) {
return (Builder) super.setTransport(transport);
}
/**
* @since 1.11
*/
@Override
public Builder setJsonFactory(JsonFactory jsonFactory) {
return (Builder) super.setJsonFactory(jsonFactory);
}
/**
* @since 1.11
*/
@Override
public Builder setTokenServerUrl(GenericUrl tokenServerUrl) {
return (Builder) super.setTokenServerUrl(tokenServerUrl);
}
/**
* @since 1.11
*/
@Override
public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {
return (Builder) super.setClientAuthentication(clientAuthentication);
}
/**
* @since 1.11
*/
@Override
public Builder setClientId(String clientId) {
return (Builder) super.setClientId(clientId);
}
/**
* @since 1.11
*/
@Override
public Builder setAuthorizationServerEncodedUrl(String authorizationServerEncodedUrl) {
return (Builder) super.setAuthorizationServerEncodedUrl(authorizationServerEncodedUrl);
}
/**
* @since 1.11
*/
@Override
public Builder setClock(Clock clock) {
return (Builder) super.setClock(clock);
}
/**
* Sets the approval prompt behavior ({@code "auto"} to request auto-approval or {@code "force"}
* to force the approval UI to show) or {@code null} for the default behavior ({@code "auto"}
* for web applications and {@code "force"} for installed applications).
*
* <p>
* By default this has the value {@code null}.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setApprovalPrompt(String approvalPrompt) {
this.approvalPrompt = approvalPrompt;
return this;
}
/**
* Returns the approval prompt behavior ({@code "auto"} to request auto-approval or
* {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of
* {@code "auto"}.
*/
public final String getApprovalPrompt() {
return approvalPrompt;
}
/**
* Sets the access type ({@code "online"} to request online access or {@code "offline"} to
* request offline access) or {@code null} for the default behavior ({@code "online"} for web
* applications and {@code "offline"} for installed applications).
*
* <p>
* By default this has the value {@code null}.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setAccessType(String accessType) {
this.accessType = accessType;
return this;
}
/**
* Returns the access type ({@code "online"} to request online access or {@code "offline"} to
* request offline access) or {@code null} for the default behavior of {@code "online"}.
*/
public final String getAccessType() {
return accessType;
}
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.auth.jsontoken.JsonWebSignature;
import com.google.api.client.auth.jsontoken.JsonWebToken;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.security.GeneralSecurityException;
/**
* Google ID tokens.
*
* <p>
* Google ID tokens contain useful information such as the {@link Payload#getUserId() obfuscated
* Google user ID}. Google ID tokens are signed and the signature must be verified using
* {@link #verify(GoogleIdTokenVerifier)}, which also checks that your application's client ID is
* the intended audience.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleIdToken extends JsonWebSignature {
/**
* Parses the given ID token string and returns the parsed {@link GoogleIdToken}.
*
* @param jsonFactory JSON factory
* @param idTokenString ID token string
* @return parsed Google ID token
*/
public static GoogleIdToken parse(JsonFactory jsonFactory, String idTokenString)
throws IOException {
JsonWebSignature jws =
JsonWebSignature.parser(jsonFactory).setPayloadClass(Payload.class).parse(idTokenString);
return new GoogleIdToken(jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(),
jws.getSignedContentBytes());
}
/**
* @param header header
* @param payload payload
* @param signatureBytes bytes of the signature
* @param signedContentBytes bytes of the signature content
*/
public GoogleIdToken(
Header header, Payload payload, byte[] signatureBytes, byte[] signedContentBytes) {
super(header, payload, signatureBytes, signedContentBytes);
}
/**
* Verifies that this ID token is valid using {@link GoogleIdTokenVerifier#verify(GoogleIdToken)}.
*/
public boolean verify(GoogleIdTokenVerifier verifier)
throws GeneralSecurityException, IOException {
return verifier.verify(this);
}
@Override
public Payload getPayload() {
return (Payload) super.getPayload();
}
/** Google ID token payload. */
public static class Payload extends JsonWebToken.Payload {
/** Obfuscated Google user ID or {@code null} for none. */
@Key("id")
private String userId;
/** Client ID of issuee or {@code null} for none. */
@Key("cid")
private String issuee;
/** Hash of access token or {@code null} for none. */
@Key("token_hash")
private String accessTokenHash;
/** Hosted domain name if asserted user is a domain managed user or {@code null} for none. */
@Key("hd")
private String hostedDomain;
/** E-mail of the user or {@code null} if not requested. */
@Key("email")
private String email;
/** {@code true} if the email is verified. */
@Key("verified_email")
private boolean emailVerified;
/**
* Constructs a new Payload using default settings.
*/
public Payload() {
this(Clock.SYSTEM);
}
/**
* Constructs a new Payload and uses the specified {@link Clock}.
* @param clock Clock to use for expiration checks.
* @since 1.9
*/
public Payload(Clock clock) {
super(clock);
}
/** Returns the obfuscated Google user id or {@code null} for none. */
public String getUserId() {
return userId;
}
/** Sets the obfuscated Google user id or {@code null} for none. */
public Payload setUserId(String userId) {
this.userId = userId;
return this;
}
/** Returns the client ID of issuee or {@code null} for none. */
public String getIssuee() {
return issuee;
}
/** Sets the client ID of issuee or {@code null} for none. */
public Payload setIssuee(String issuee) {
this.issuee = issuee;
return this;
}
/** Returns the hash of access token or {@code null} for none. */
public String getAccessTokenHash() {
return accessTokenHash;
}
/** Sets the hash of access token or {@code null} for none. */
public Payload setAccessTokenHash(String accessTokenHash) {
this.accessTokenHash = accessTokenHash;
return this;
}
/**
* Returns the hosted domain name if asserted user is a domain managed user or {@code null} for
* none.
*/
public String getHostedDomain() {
return hostedDomain;
}
/**
* Sets the hosted domain name if asserted user is a domain managed user or {@code null} for
* none.
*/
public Payload setHostedDomain(String hostedDomain) {
this.hostedDomain = hostedDomain;
return this;
}
/**
* Returns the e-mail address of the user or {@code null} if it was not requested.
*
* <p>
* Requires the {@code "https://www.googleapis.com/auth/userinfo.email"} scope.
* </p>
*
* @since 1.10
*/
public String getEmail() {
return email;
}
/**
* Sets the e-mail address of the user or {@code null} if it was not requested.
*
* <p>
* Used in conjunction with the {@code "https://www.googleapis.com/auth/userinfo.email"} scope.
* </p>
*
* @since 1.10
*/
public Payload setEmail(String email) {
this.email = email;
return this;
}
/**
* Returns {@code true} if the users e-mail address has been verified by Google.
*
* <p>
* Requires the {@code "https://www.googleapis.com/auth/userinfo.email"} scope.
* </p>
*
* @since 1.10
*/
public boolean getEmailVerified() {
return emailVerified;
}
/**
* Sets whether the users e-mail address has been verified by Google or not.
*
* <p>
* Used in conjunction with the {@code "https://www.googleapis.com/auth/userinfo.email"} scope.
* </p>
*
* @since 1.10
*/
public Payload setEmailVerified(boolean emailVerified) {
this.emailVerified = emailVerified;
return this;
}
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.auth.oauth2.BrowserClientRequestUrl;
import com.google.api.client.util.Key;
import com.google.common.base.Preconditions;
/**
* Google-specific implementation of the OAuth 2.0 URL builder for an authorization web page to
* allow the end user to authorize the application to access their protected resources and that
* returns the access token to a browser client using a scripting language such as JavaScript, as
* specified in <a href="http://code.google.com/apis/accounts/docs/OAuth2UserAgent.html">Using OAuth
* 2.0 for Client-side Applications (Experimental)</a>.
*
* <p>
* The default for {@link #getResponseTypes()} is {@code "token"}.
* </p>
*
* <p>
* Sample usage for a web application:
* </p>
*
* <pre>
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String url = new GoogleBrowserClientRequestUrl("812741506391.apps.googleusercontent.com",
"https://oauth2-login-demo.appspot.com/oauthcallback", Arrays.asList(
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile")).setState("/profile").build();
response.sendRedirect(url);
}
* </pre>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleBrowserClientRequestUrl extends BrowserClientRequestUrl {
/**
* Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to
* force the approval UI to show) or {@code null} for the default behavior.
*/
@Key("approval_prompt")
private String approvalPrompt;
/**
* @param clientId client identifier
* @param redirectUri URI that the authorization server directs the resource owner's user-agent
* back to the client after a successful authorization grant
* @param scopes scopes (see {@link #setScopes(Iterable)})
*/
public GoogleBrowserClientRequestUrl(
String clientId, String redirectUri, Iterable<String> scopes) {
super(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId);
setRedirectUri(redirectUri);
setScopes(scopes);
}
/**
* @param clientSecrets OAuth 2.0 client secrets JSON model as specified in <a
* href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets">
* client_secrets.json file format</a>
* @param redirectUri URI that the authorization server directs the resource owner's user-agent
* back to the client after a successful authorization grant
* @param scopes scopes (see {@link #setScopes(Iterable)})
*/
public GoogleBrowserClientRequestUrl(
GoogleClientSecrets clientSecrets, String redirectUri, Iterable<String> scopes) {
this(clientSecrets.getDetails().getClientId(), redirectUri, scopes);
}
/**
* Returns the approval prompt behavior ({@code "auto"} to request auto-approval or
* {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of
* {@code "auto"}.
*/
public final String getApprovalPrompt() {
return approvalPrompt;
}
/**
* Sets the approval prompt behavior ({@code "auto"} to request auto-approval or {@code "force"}
* to force the approval UI to show) or {@code null} for the default behavior of {@code "auto"}.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public GoogleBrowserClientRequestUrl setApprovalPrompt(String approvalPrompt) {
this.approvalPrompt = approvalPrompt;
return this;
}
@Override
public GoogleBrowserClientRequestUrl setResponseTypes(String... responseTypes) {
return (GoogleBrowserClientRequestUrl) super.setResponseTypes(responseTypes);
}
@Override
public GoogleBrowserClientRequestUrl setResponseTypes(Iterable<String> responseTypes) {
return (GoogleBrowserClientRequestUrl) super.setResponseTypes(responseTypes);
}
@Override
public GoogleBrowserClientRequestUrl setRedirectUri(String redirectUri) {
return (GoogleBrowserClientRequestUrl) super.setRedirectUri(redirectUri);
}
@Override
public GoogleBrowserClientRequestUrl setScopes(String... scopes) {
Preconditions.checkArgument(scopes.length != 0);
return (GoogleBrowserClientRequestUrl) super.setScopes(scopes);
}
@Override
public GoogleBrowserClientRequestUrl setScopes(Iterable<String> scopes) {
Preconditions.checkArgument(scopes.iterator().hasNext());
return (GoogleBrowserClientRequestUrl) super.setScopes(scopes);
}
@Override
public GoogleBrowserClientRequestUrl setClientId(String clientId) {
return (GoogleBrowserClientRequestUrl) super.setClientId(clientId);
}
@Override
public GoogleBrowserClientRequestUrl setState(String state) {
return (GoogleBrowserClientRequestUrl) super.setState(state);
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl;
import com.google.api.client.util.Key;
import com.google.common.base.Preconditions;
/**
* Google-specific implementation of the OAuth 2.0 URL builder for an authorization web page to
* allow the end user to authorize the application to access their protected resources and that
* returns an authorization code, as specified in <a
* href="http://code.google.com/apis/accounts/docs/OAuth2WebServer.html">Using OAuth 2.0 for Web
* Server Applications (Experimental)</a>.
*
* <p>
* The default for {@link #getResponseTypes()} is {@code "code"}. Use
* {@link AuthorizationCodeResponseUrl} to parse the redirect response after the end user
* grants/denies the request. Using the authorization code in this response, use
* {@link GoogleAuthorizationCodeTokenRequest} to request the access token.
* </p>
*
* <p>
* Sample usage for a web application:
* </p>
*
* <pre>
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String url =
new GoogleAuthorizationCodeRequestUrl("812741506391.apps.googleusercontent.com",
"https://oauth2-login-demo.appspot.com/code", Arrays.asList(
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile")).setState("/profile").build();
response.sendRedirect(url);
}
* </pre>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleAuthorizationCodeRequestUrl extends AuthorizationCodeRequestUrl {
/**
* Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to
* force the approval UI to show) or {@code null} for the default behavior.
*/
@Key("approval_prompt")
private String approvalPrompt;
/**
* Access type ({@code "online"} to request online access or {@code "offline"} to request offline
* access) or {@code null} for the default behavior.
*/
@Key("access_type")
private String accessType;
/**
* @param clientId client identifier
* @param redirectUri URI that the authorization server directs the resource owner's user-agent
* back to the client after a successful authorization grant
* @param scopes scopes (see {@link #setScopes(Iterable)})
*/
public GoogleAuthorizationCodeRequestUrl(
String clientId, String redirectUri, Iterable<String> scopes) {
this(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId, redirectUri, scopes);
}
/**
* @param authorizationServerEncodedUrl authorization server encoded URL
* @param clientId client identifier
* @param redirectUri URI that the authorization server directs the resource owner's user-agent
* back to the client after a successful authorization grant
* @param scopes scopes (see {@link #setScopes(Iterable)})
*
* @since 1.12
*/
public GoogleAuthorizationCodeRequestUrl(String authorizationServerEncodedUrl,
String clientId, String redirectUri, Iterable<String> scopes) {
super(authorizationServerEncodedUrl, clientId);
setRedirectUri(redirectUri);
setScopes(scopes);
}
/**
* @param clientSecrets OAuth 2.0 client secrets JSON model as specified in <a
* href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets">
* client_secrets.json file format</a>
* @param redirectUri URI that the authorization server directs the resource owner's user-agent
* back to the client after a successful authorization grant
* @param scopes scopes (see {@link #setScopes(Iterable)})
*/
public GoogleAuthorizationCodeRequestUrl(
GoogleClientSecrets clientSecrets, String redirectUri, Iterable<String> scopes) {
this(clientSecrets.getDetails().getClientId(), redirectUri, scopes);
}
/**
* Returns the approval prompt behavior ({@code "auto"} to request auto-approval or
* {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of
* {@code "auto"}.
*/
public final String getApprovalPrompt() {
return approvalPrompt;
}
/**
* Sets the approval prompt behavior ({@code "auto"} to request auto-approval or {@code "force"}
* to force the approval UI to show) or {@code null} for the default behavior of {@code "auto"}.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public GoogleAuthorizationCodeRequestUrl setApprovalPrompt(String approvalPrompt) {
this.approvalPrompt = approvalPrompt;
return this;
}
/**
* Returns the access type ({@code "online"} to request online access or {@code "offline"} to
* request offline access) or {@code null} for the default behavior of {@code "online"}.
*/
public final String getAccessType() {
return accessType;
}
/**
* Sets the access type ({@code "online"} to request online access or {@code "offline"} to request
* offline access) or {@code null} for the default behavior of {@code "online"}.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public GoogleAuthorizationCodeRequestUrl setAccessType(String accessType) {
this.accessType = accessType;
return this;
}
@Override
public GoogleAuthorizationCodeRequestUrl setResponseTypes(String... responseTypes) {
return (GoogleAuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes);
}
@Override
public GoogleAuthorizationCodeRequestUrl setResponseTypes(Iterable<String> responseTypes) {
return (GoogleAuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes);
}
@Override
public GoogleAuthorizationCodeRequestUrl setRedirectUri(String redirectUri) {
Preconditions.checkNotNull(redirectUri);
return (GoogleAuthorizationCodeRequestUrl) super.setRedirectUri(redirectUri);
}
@Override
public GoogleAuthorizationCodeRequestUrl setScopes(String... scopes) {
Preconditions.checkArgument(scopes.length != 0);
return (GoogleAuthorizationCodeRequestUrl) super.setScopes(scopes);
}
@Override
public GoogleAuthorizationCodeRequestUrl setScopes(Iterable<String> scopes) {
Preconditions.checkArgument(scopes.iterator().hasNext());
return (GoogleAuthorizationCodeRequestUrl) super.setScopes(scopes);
}
@Override
public GoogleAuthorizationCodeRequestUrl setClientId(String clientId) {
return (GoogleAuthorizationCodeRequestUrl) super.setClientId(clientId);
}
@Override
public GoogleAuthorizationCodeRequestUrl setState(String state) {
return (GoogleAuthorizationCodeRequestUrl) super.setState(state);
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.auth.jsontoken.JsonWebSignature;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonParser;
import com.google.api.client.json.JsonToken;
import com.google.api.client.util.Clock;
import com.google.api.client.util.StringUtils;
import com.google.common.base.Preconditions;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Thread-safe Google ID token verifier.
*
* <p>
* The public keys are loaded Google's public certificate endpoint at
* {@code "https://www.googleapis.com/oauth2/v1/certs"}. The public keys are cached in this instance
* of {@link GoogleIdTokenVerifier}. Therefore, for maximum efficiency, applications should use a
* single globally-shared instance of the {@link GoogleIdTokenVerifier}. Use
* {@link #verify(GoogleIdToken)} or {@link GoogleIdToken#verify(GoogleIdTokenVerifier)} to verify a
* Google ID token.
* </p>
*
* <p>
* Samples usage:
* </p>
*
* <pre>
public static GoogleIdTokenVerifier verifier;
public static void initVerifier(
HttpTransport transport, JsonFactory jsonFactory, String clientId) {
verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
.setClientId(clientId)
.build();
}
public static boolean verifyToken(GoogleIdToken idToken)
throws GeneralSecurityException, IOException {
return verifier.verify(idToken);
}
* </pre>
* @since 1.7
*/
public class GoogleIdTokenVerifier {
/** Pattern for the max-age header element of Cache-Control. */
private static final Pattern MAX_AGE_PATTERN = Pattern.compile("\\s*max-age\\s*=\\s*(\\d+)\\s*");
/** JSON factory. */
private final JsonFactory jsonFactory;
/** Public keys or {@code null} for none. */
private List<PublicKey> publicKeys;
/**
* Expiration time in milliseconds to be used with {@link Clock#currentTimeMillis()} or {@code 0}
* for none.
*/
private long expirationTimeMilliseconds;
/** Set of Client IDs. */
private Set<String> clientIds;
/** HTTP transport. */
private final HttpTransport transport;
/** Lock on the public keys. */
private final Lock lock = new ReentrantLock();
/** Clock to use for expiration checks. */
private final Clock clock;
/**
* Constructor with required parameters.
*
* <p>
* Use {@link GoogleIdTokenVerifier.Builder} to specify client IDs.
* </p>
*
* @param transport HTTP transport
* @param jsonFactory JSON factory
*/
public GoogleIdTokenVerifier(HttpTransport transport, JsonFactory jsonFactory) {
this(null, transport, jsonFactory);
}
/**
* Construct the {@link GoogleIdTokenVerifier}.
*
* @param clientIds set of client IDs or {@code null} for none
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @since 1.9
*/
protected GoogleIdTokenVerifier(
Set<String> clientIds, HttpTransport transport, JsonFactory jsonFactory) {
this(clientIds, transport, jsonFactory, Clock.SYSTEM);
}
/**
* Construct the {@link GoogleIdTokenVerifier}.
*
* @param clientIds set of client IDs or {@code null} for none
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param clock Clock for expiration checks
* @since 1.9
*/
protected GoogleIdTokenVerifier(
Set<String> clientIds, HttpTransport transport, JsonFactory jsonFactory, Clock clock) {
this.clientIds =
clientIds == null ? Collections.<String>emptySet() : Collections.unmodifiableSet(clientIds);
this.transport = Preconditions.checkNotNull(transport);
this.jsonFactory = Preconditions.checkNotNull(jsonFactory);
this.clock = Preconditions.checkNotNull(clock);
}
/** Returns the JSON factory. */
public final JsonFactory getJsonFactory() {
return jsonFactory;
}
/**
* Returns the set of client IDs.
*
* @since 1.9
*/
public final Set<String> getClientIds() {
return clientIds;
}
/** Returns the public keys or {@code null} for none. */
public final List<PublicKey> getPublicKeys() {
return publicKeys;
}
/**
* Returns the expiration time in milliseconds to be used with {@link Clock#currentTimeMillis()}
* or {@code 0} for none.
*/
public final long getExpirationTimeMilliseconds() {
return expirationTimeMilliseconds;
}
/**
* Verifies that the given ID token is valid using {@link #verify(GoogleIdToken, String)} with the
* {@link #getClientIds()}.
*
* @param idToken Google ID token
* @return {@code true} if verified successfully or {@code false} if failed
*/
public boolean verify(GoogleIdToken idToken) throws GeneralSecurityException, IOException {
return verify(clientIds, idToken);
}
/**
* Returns a Google ID token if the given ID token string is valid using
* {@link #verify(GoogleIdToken, String)} with the {@link #getClientIds()}.
*
* @param idTokenString Google ID token string
* @return Google ID token if verified successfully or {@code null} if failed
* @since 1.9
*/
public GoogleIdToken verify(String idTokenString) throws GeneralSecurityException, IOException {
GoogleIdToken idToken = GoogleIdToken.parse(jsonFactory, idTokenString);
return verify(idToken) ? idToken : null;
}
/**
* Verifies that the given ID token is valid, using the given client ID.
*
* It verifies:
*
* <ul>
* <li>The RS256 signature, which uses RSA and SHA-256 based on the public keys downloaded from
* the public certificate endpoint.</li>
* <li>The current time against the issued at and expiration time (allowing for a 5 minute clock
* skew).</li>
* <li>The issuer is {@code "accounts.google.com"}.</li>
* <li>The audience and issuee match the client ID (skipped if {@code clientId} is {@code null}.
* </li>
* <li>
* </ul>
*
* @param idToken Google ID token
* @param clientId client ID or {@code null} to skip checking it
* @return {@code true} if verified successfully or {@code false} if failed
* @since 1.8
*/
public boolean verify(GoogleIdToken idToken, String clientId)
throws GeneralSecurityException, IOException {
return verify(
clientId == null ? Collections.<String>emptySet() : Collections.singleton(clientId),
idToken);
}
/**
* Verifies that the given ID token is valid, using the given set of client IDs.
*
* It verifies:
*
* <ul>
* <li>The RS256 signature, which uses RSA and SHA-256 based on the public keys downloaded from
* the public certificate endpoint.</li>
* <li>The current time against the issued at and expiration time (allowing for a 5 minute clock
* skew).</li>
* <li>The issuer is {@code "accounts.google.com"}.</li>
* <li>The audience and issuee match one of the client IDs (skipped if {@code clientIds} is
* {@code null}.</li>
* <li>
* </ul>
*
* @param idToken Google ID token
* @param clientIds set of client IDs
* @return {@code true} if verified successfully or {@code false} if failed
* @since 1.9
*/
public boolean verify(Set<String> clientIds, GoogleIdToken idToken)
throws GeneralSecurityException, IOException {
// check the payload
GoogleIdToken.Payload payload = idToken.getPayload();
if (!payload.isValidTime(300) || !"accounts.google.com".equals(payload.getIssuer())
|| !clientIds.isEmpty() && (!clientIds.contains(payload.getAudience())
|| !clientIds.contains(payload.getIssuee()))) {
return false;
}
// check the signature
JsonWebSignature.Header header = idToken.getHeader();
String algorithm = header.getAlgorithm();
if (algorithm.equals("RS256")) {
lock.lock();
try {
// load public keys; expire 5 minutes (300 seconds) before actual expiration time
if (publicKeys == null || clock.currentTimeMillis() + 300000 > expirationTimeMilliseconds) {
loadPublicCerts();
}
Signature signer = Signature.getInstance("SHA256withRSA");
for (PublicKey publicKey : publicKeys) {
signer.initVerify(publicKey);
signer.update(idToken.getSignedContentBytes());
if (signer.verify(idToken.getSignatureBytes())) {
return true;
}
}
} finally {
lock.unlock();
}
}
return false;
}
/**
* Downloads the public keys from the public certificates endpoint at
* {@code "https://www.googleapis.com/oauth2/v1/certs"}.
*
* <p>
* This method is automatically called if the public keys have not yet been initialized or if the
* expiration time is very close, so normally this doesn't need to be called. Only call this
* method explicitly to force the public keys to be updated.
* </p>
*/
public GoogleIdTokenVerifier loadPublicCerts() throws GeneralSecurityException, IOException {
lock.lock();
try {
publicKeys = new ArrayList<PublicKey>();
// HTTP request to public endpoint
CertificateFactory factory = CertificateFactory.getInstance("X509");
HttpResponse certsResponse = transport.createRequestFactory()
.buildGetRequest(new GenericUrl("https://www.googleapis.com/oauth2/v1/certs")).execute();
// parse Cache-Control max-age parameter
for (String arg : certsResponse.getHeaders().getCacheControl().split(",")) {
Matcher m = MAX_AGE_PATTERN.matcher(arg);
if (m.matches()) {
expirationTimeMilliseconds = clock.currentTimeMillis() + Long.valueOf(m.group(1)) * 1000;
break;
}
}
// parse each public key in the JSON response
JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent());
JsonToken currentToken = parser.getCurrentToken();
// token is null at start, so get next token
if (currentToken == null) {
currentToken = parser.nextToken();
}
Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT);
try {
while (parser.nextToken() != JsonToken.END_OBJECT) {
parser.nextToken();
String certValue = parser.getText();
X509Certificate x509Cert = (X509Certificate) factory.generateCertificate(
new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue)));
publicKeys.add(x509Cert.getPublicKey());
}
publicKeys = Collections.unmodifiableList(publicKeys);
} finally {
parser.close();
}
return this;
} finally {
lock.unlock();
}
}
/**
* Builder for {@link GoogleIdTokenVerifier}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.9
*/
public static class Builder {
/** HTTP transport. */
private final HttpTransport transport;
/** JSON factory. */
private final JsonFactory jsonFactory;
/** Set of Client IDs. */
private Set<String> clientIds = new HashSet<String>();
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport
* @param jsonFactory JSON factory
*/
public Builder(HttpTransport transport, JsonFactory jsonFactory) {
this.transport = transport;
this.jsonFactory = jsonFactory;
}
/** Builds a new instance of {@link GoogleIdTokenVerifier}. */
public GoogleIdTokenVerifier build() {
return new GoogleIdTokenVerifier(clientIds, transport, jsonFactory);
}
/** Returns the HTTP transport. */
public final HttpTransport getTransport() {
return transport;
}
/** Returns the JSON factory. */
public final JsonFactory getJsonFactory() {
return jsonFactory;
}
/** Returns the set of client IDs. */
public final Set<String> getClientIds() {
return clientIds;
}
/**
* Sets a list of client IDs.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setClientIds(Iterable<String> clientIds) {
this.clientIds.clear();
for (String clientId : clientIds) {
this.clientIds.add(clientId);
}
return this;
}
/**
* Sets a list of client IDs.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setClientIds(String... clientIds) {
this.clientIds.clear();
Collections.addAll(this.clientIds, clientIds);
return this;
}
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.auth.oauth2;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.Key;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* OAuth 2.0 client secrets JSON model as specified in <a
* href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets">client_secrets.json
* file format</a>.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
static GoogleClientSecrets loadClientSecretsResource(JsonFactory jsonFactory) throws IOException {
return GoogleClientSecrets.load(
jsonFactory, SampleClass.class.getResourceAsStream("/client_secrets.json"));
}
* </pre>
*
* @since 1.7
* @author Yaniv Inbar
*/
public final class GoogleClientSecrets extends GenericJson {
/** Details for installed applications. */
@Key
private Details installed;
/** Details for web applications. */
@Key
private Details web;
/** Returns the details for installed applications. */
public Details getInstalled() {
return installed;
}
/** Sets the details for installed applications. */
public GoogleClientSecrets setInstalled(Details installed) {
this.installed = installed;
return this;
}
/** Returns the details for web applications. */
public Details getWeb() {
return web;
}
/** Sets the details for web applications. */
public GoogleClientSecrets setWeb(Details web) {
this.web = web;
return this;
}
/** Returns the details for either installed or web applications. */
public Details getDetails() {
// that web or installed, but not both
Preconditions.checkArgument((web == null) != (installed == null));
return web == null ? installed : web;
}
/** Client credential details. */
public static final class Details extends GenericJson {
/** Client ID. */
@Key("client_id")
private String clientId;
/** Client secret. */
@Key("client_secret")
private String clientSecret;
/** Redirect URIs. */
@Key("redirect_uris")
private List<String> redirectUris;
/** Authorization server URI. */
@Key("auth_uri")
private String authUri;
/** Token server URI. */
@Key("token_uri")
private String tokenUri;
/** Returns the client ID. */
public String getClientId() {
return clientId;
}
/** Sets the client ID. */
public Details setClientId(String clientId) {
this.clientId = clientId;
return this;
}
/** Returns the client secret. */
public String getClientSecret() {
return clientSecret;
}
/** Sets the client secret. */
public Details setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
return this;
}
/** Returns the redirect URIs. */
public List<String> getRedirectUris() {
return redirectUris;
}
/** Sets the redirect URIs. */
public Details setRedirectUris(List<String> redirectUris) {
this.redirectUris = redirectUris;
return this;
}
/** Returns the authorization server URI. */
public String getAuthUri() {
return authUri;
}
/** Sets the authorization server URI. */
public Details setAuthUri(String authUri) {
this.authUri = authUri;
return this;
}
/** Returns the token server URI. */
public String getTokenUri() {
return tokenUri;
}
/** Sets the token server URI. */
public Details setTokenUri(String tokenUri) {
this.tokenUri = tokenUri;
return this;
}
}
/** Loads the {@code client_secrets.json} file from the given input stream. */
public static GoogleClientSecrets load(JsonFactory jsonFactory, InputStream inputStream)
throws IOException {
// TODO(mlinder): Change this method to take a charset
return jsonFactory.fromInputStream(inputStream, GoogleClientSecrets.class);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis.auth.clientlogin;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.util.Key;
import com.google.api.client.util.StringUtils;
import java.io.IOException;
/**
* Client Login authentication method as described in <a
* href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html" >ClientLogin for
* Installed Applications</a>.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class ClientLogin {
/**
* HTTP transport required for executing request in {@link #authenticate()}.
*
* @since 1.3
*/
public HttpTransport transport;
/**
* URL for the Client Login authorization server.
*
* <p>
* By default this is {@code "https://www.google.com"}, but it may be overridden for testing
* purposes.
* </p>
*
* @since 1.3
*/
public GenericUrl serverUrl = new GenericUrl("https://www.google.com");
/**
* Short string identifying your application for logging purposes of the form:
* "companyName-applicationName-versionID".
*/
@Key("source")
public String applicationName;
/**
* Name of the Google service you're requesting authorization for, for example {@code "cl"} for
* Google Calendar.
*/
@Key("service")
public String authTokenType;
/** User's full email address. */
@Key("Email")
public String username;
/** User's password. */
@Key("Passwd")
public String password;
/**
* Type of account to request authorization for. Possible values are:
*
* <ul>
* <li>GOOGLE (get authorization for a Google account only)</li>
* <li>HOSTED (get authorization for a hosted account only)</li>
* <li>HOSTED_OR_GOOGLE (get authorization first for a hosted account; if attempt fails, get
* authorization for a Google account)</li>
* </ul>
*
* Use HOSTED_OR_GOOGLE if you're not sure which type of account you want authorization for. If
* the user information matches both a hosted and a Google account, only the hosted account is
* authorized.
*
* @since 1.1
*/
@Key
public String accountType;
/** (optional) Token representing the specific CAPTCHA challenge. */
@Key("logintoken")
public String captchaToken;
/** (optional) String entered by the user as an answer to a CAPTCHA challenge. */
@Key("logincaptcha")
public String captchaAnswer;
/**
* Key/value data to parse a success response.
*
* <p>
* Sample usage, taking advantage that this class implements {@link HttpRequestInitializer}:
* </p>
*
* <pre>
public static HttpRequestFactory createRequestFactory(
HttpTransport transport, Response response) {
return transport.createRequestFactory(response);
}
* </pre>
*
* <p>
* If you have a custom request initializer, take a look at the sample usage for
* {@link HttpExecuteInterceptor}, which this class also implements.
* </p>
*/
public static final class Response implements HttpExecuteInterceptor, HttpRequestInitializer {
/** Authentication token. */
@Key("Auth")
public String auth;
/** Returns the authorization header value to use based on the authentication token. */
public String getAuthorizationHeaderValue() {
return ClientLogin.getAuthorizationHeaderValue(auth);
}
public void initialize(HttpRequest request) {
request.setInterceptor(this);
}
public void intercept(HttpRequest request) {
request.getHeaders().setAuthorization(getAuthorizationHeaderValue());
}
}
/** Key/value data to parse an error response. */
public static final class ErrorInfo {
@Key("Error")
public String error;
@Key("Url")
public String url;
@Key("CaptchaToken")
public String captchaToken;
@Key("CaptchaUrl")
public String captchaUrl;
}
/**
* Authenticates based on the provided field values.
*
* @throws ClientLoginResponseException if the authentication response has an error code, such as
* for a CAPTCHA challenge.
*/
public Response authenticate() throws IOException {
GenericUrl url = serverUrl.clone();
url.appendRawPath("/accounts/ClientLogin");
HttpRequest request =
transport.createRequestFactory().buildPostRequest(url, new UrlEncodedContent(this));
request.setParser(AuthKeyValueParser.INSTANCE);
request.setContentLoggingLimit(0);
request.setThrowExceptionOnExecuteError(false);
HttpResponse response = request.execute();
// check for an HTTP success response (2xx)
if (response.isSuccessStatusCode()) {
return response.parseAs(Response.class);
}
// On error, throw a ClientLoginResponseException with the parsed error details
ErrorInfo details = response.parseAs(ErrorInfo.class);
String detailString = details.toString();
StringBuilder message = HttpResponseException.computeMessageBuffer(response);
if (!com.google.common.base.Strings.isNullOrEmpty(detailString)) {
message.append(StringUtils.LINE_SEPARATOR).append(detailString);
}
throw new ClientLoginResponseException(response, details, message.toString());
}
/**
* Returns Google Login {@code "Authorization"} header value based on the given authentication
* token.
*
* @since 1.13
*/
public static String getAuthorizationHeaderValue(String authToken) {
return "GoogleLogin auth=" + authToken;
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* 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.google.api.client.googleapis.auth.clientlogin;
import com.google.api.client.googleapis.auth.clientlogin.ClientLogin.ErrorInfo;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
/**
* Exception thrown when an error status code is detected in an HTTP response to a Google
* ClientLogin request in {@link ClientLogin} .
*
* <p>
* To get the structured details, use {@link #getDetails()}.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class ClientLoginResponseException extends HttpResponseException {
private static final long serialVersionUID = 4974317674023010928L;
/** Error details or {@code null} for none. */
private final transient ErrorInfo details;
/**
* @param response HTTP response
* @param details error details or {@code null} for none
* @param message message details
*/
ClientLoginResponseException(HttpResponse response, ErrorInfo details, String message) {
super(response, message);
this.details = details;
}
/** Return the error details or {@code null} for none. */
public final ErrorInfo getDetails() {
return details;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.
*/
/**
* Google's legacy ClientLogin authentication method as described in <a
* href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html">ClientLogin for
* Installed Applications</a>.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.auth.clientlogin;
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.googleapis.auth.clientlogin;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.FieldInfo;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.ObjectParser;
import com.google.api.client.util.Types;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Map;
/**
* HTTP parser for Google response to an Authorization request.
*
* @since 1.10
* @author Yaniv Inbar
*/
@SuppressWarnings("deprecation")
final class AuthKeyValueParser implements com.google.api.client.http.HttpParser, ObjectParser {
/** Singleton instance. */
public static final AuthKeyValueParser INSTANCE = new AuthKeyValueParser();
public String getContentType() {
return "text/plain";
}
public <T> T parse(HttpResponse response, Class<T> dataClass) throws IOException {
response.setContentLoggingLimit(0);
InputStream content = response.getContent();
try {
return parse(content, dataClass);
} finally {
content.close();
}
}
public <T> T parse(InputStream content, Class<T> dataClass) throws IOException {
ClassInfo classInfo = ClassInfo.of(dataClass);
T newInstance = Types.newInstance(dataClass);
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
int equals = line.indexOf('=');
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
// get the field from the type information
Field field = classInfo.getField(key);
if (field != null) {
Class<?> fieldClass = field.getType();
Object fieldValue;
if (fieldClass == boolean.class || fieldClass == Boolean.class) {
fieldValue = Boolean.valueOf(value);
} else {
fieldValue = value;
}
FieldInfo.setFieldValue(field, newInstance, fieldValue);
} else if (GenericData.class.isAssignableFrom(dataClass)) {
GenericData data = (GenericData) newInstance;
data.set(key, value);
} else if (Map.class.isAssignableFrom(dataClass)) {
@SuppressWarnings("unchecked")
Map<Object, Object> map = (Map<Object, Object>) newInstance;
map.put(key, value);
}
}
return newInstance;
}
private AuthKeyValueParser() {
}
public <T> T parseAndClose(InputStream in, Charset charset, Class<T> dataClass)
throws IOException {
Reader reader = new InputStreamReader(in, charset);
return parseAndClose(reader, dataClass);
}
public Object parseAndClose(InputStream in, Charset charset, Type dataType) {
throw new UnsupportedOperationException(
"Type-based parsing is not yet supported -- use Class<T> instead");
}
public <T> T parseAndClose(Reader reader, Class<T> dataClass) throws IOException {
try {
ClassInfo classInfo = ClassInfo.of(dataClass);
T newInstance = Types.newInstance(dataClass);
BufferedReader breader = new BufferedReader(reader);
while (true) {
String line = breader.readLine();
if (line == null) {
break;
}
int equals = line.indexOf('=');
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
// get the field from the type information
Field field = classInfo.getField(key);
if (field != null) {
Class<?> fieldClass = field.getType();
Object fieldValue;
if (fieldClass == boolean.class || fieldClass == Boolean.class) {
fieldValue = Boolean.valueOf(value);
} else {
fieldValue = value;
}
FieldInfo.setFieldValue(field, newInstance, fieldValue);
} else if (GenericData.class.isAssignableFrom(dataClass)) {
GenericData data = (GenericData) newInstance;
data.set(key, value);
} else if (Map.class.isAssignableFrom(dataClass)) {
@SuppressWarnings("unchecked")
Map<Object, Object> map = (Map<Object, Object>) newInstance;
map.put(key, value);
}
}
return newInstance;
} finally {
reader.close();
}
}
public Object parseAndClose(Reader reader, Type dataType) {
throw new UnsupportedOperationException(
"Type-based parsing is not yet supported -- use Class<T> instead");
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis;
/**
* Utility class for the Google API Client Library.
*
* @since 1.12
* @author rmistry@google.com (Ravi Mistry)
*/
public class GoogleUtils {
/** Current version of the Google API Client Library for Java. */
public static final String VERSION = "1.14.0-beta-SNAPSHOT";
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.batch;
import com.google.api.client.http.BackOffPolicy;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* An instance of this class represents a single batch of requests.
*
* <p>
* Sample use:
* </p>
*
* <pre>
BatchRequest batch = new BatchRequest(transport, httpRequestInitializer);
batch.queue(volumesList, Volumes.class, GoogleJsonErrorContainer.class,
new BatchCallback<Volumes, GoogleJsonErrorContainer>() {
public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) {
log("Success");
printVolumes(volumes.getItems());
}
public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) {
log(e.getError().getMessage());
}
});
batch.queue(volumesList, Volumes.class, GoogleJsonErrorContainer.class,
new BatchCallback<Volumes, GoogleJsonErrorContainer>() {
public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) {
log("Success");
printVolumes(volumes.getItems());
}
public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) {
log(e.getError().getMessage());
}
});
batch.execute();
* </pre>
*
* <p>
* The content of each individual response is stored in memory. There is thus a potential of
* encountering an {@link OutOfMemoryError} for very large responses.
* </p>
*
* <p>
* Redirects are currently not followed in {@link BatchRequest}.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.9
* @author rmistry@google.com (Ravi Mistry)
*/
public final class BatchRequest {
/** The URL where batch requests are sent. */
private GenericUrl batchUrl = new GenericUrl("https://www.googleapis.com/batch");
/** The request factory for connections to the server. */
private final HttpRequestFactory requestFactory;
/** The list of queued request infos. */
List<RequestInfo<?, ?>> requestInfos = new ArrayList<RequestInfo<?, ?>>();
/** A container class used to hold callbacks and data classes. */
static class RequestInfo<T, E> {
final BatchCallback<T, E> callback;
final Class<T> dataClass;
final Class<E> errorClass;
final HttpRequest request;
RequestInfo(BatchCallback<T, E> callback,
Class<T> dataClass,
Class<E> errorClass,
HttpRequest request) {
this.callback = callback;
this.dataClass = dataClass;
this.errorClass = errorClass;
this.request = request;
}
}
/**
* Construct the {@link BatchRequest}.
*
* @param transport The transport to use for requests
* @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or
* {@code null} for none
*/
public BatchRequest(HttpTransport transport, HttpRequestInitializer httpRequestInitializer) {
this.requestFactory = httpRequestInitializer == null
? transport.createRequestFactory() : transport
.createRequestFactory(httpRequestInitializer);
}
/**
* Sets the URL that will be hit when {@link #execute()} is called. The default value is
* {@code https://www.googleapis.com/batch}.
*/
public BatchRequest setBatchUrl(GenericUrl batchUrl) {
this.batchUrl = batchUrl;
return this;
}
/** Returns the URL that will be hit when {@link #execute()} is called. */
public GenericUrl getBatchUrl() {
return batchUrl;
}
/**
* Queues the specified {@link HttpRequest} for batched execution. Batched requests are executed
* when {@link #execute()} is called.
*
* @param <T> destination class type
* @param <E> error class type
* @param httpRequest HTTP Request
* @param dataClass Data class the response will be parsed into or {@code Void.class} to ignore
* the content
* @param errorClass Data class the unsuccessful response will be parsed into or
* {@code Void.class} to ignore the content
* @param callback Batch Callback
* @return this Batch request
* @throws IOException If building the HTTP Request fails
*/
public <T, E> BatchRequest queue(HttpRequest httpRequest,
Class<T> dataClass,
Class<E> errorClass,
BatchCallback<T, E> callback) throws IOException {
Preconditions.checkNotNull(httpRequest);
// TODO(rmistry): Add BatchUnparsedCallback with onResponse(InputStream content, HttpHeaders).
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(dataClass);
Preconditions.checkNotNull(errorClass);
requestInfos.add(new RequestInfo<T, E>(callback, dataClass, errorClass, httpRequest));
return this;
}
/**
* Returns the number of queued requests in this batch request.
*/
public int size() {
return requestInfos.size();
}
/**
* Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks.
*
* <p>
* Calling {@link #execute()} executes and clears the queued requests. This means that the
* {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests
* again.
* </p>
*/
public void execute() throws IOException {
boolean retryAllowed;
Preconditions.checkState(!requestInfos.isEmpty());
HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null);
HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor();
batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor));
int retriesRemaining = batchRequest.getNumberOfRetries();
BackOffPolicy backOffPolicy = batchRequest.getBackOffPolicy();
if (backOffPolicy != null) {
// Reset the BackOffPolicy at the start of each execute.
backOffPolicy.reset();
}
do {
retryAllowed = retriesRemaining > 0;
batchRequest.setContent(new MultipartMixedContent(requestInfos, "__END_OF_PART__"));
HttpResponse response = batchRequest.execute();
BatchUnparsedResponse batchResponse;
try {
// Find the boundary from the Content-Type header.
String boundary = "--" + response.getMediaType().getParameter("boundary");
// Parse the content stream.
InputStream contentStream = response.getContent();
batchResponse =
new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed);
while (batchResponse.hasNext) {
batchResponse.parseNextResponse();
}
} finally {
response.disconnect();
}
List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos;
if (!unsuccessfulRequestInfos.isEmpty()) {
requestInfos = unsuccessfulRequestInfos;
// backOff if required.
if (batchResponse.backOffRequired && backOffPolicy != null) {
long backOffTime = backOffPolicy.getNextBackOffMillis();
if (backOffTime != BackOffPolicy.STOP) {
sleep(backOffTime);
}
}
} else {
break;
}
retriesRemaining--;
} while (retryAllowed);
requestInfos.clear();
}
/**
* An exception safe sleep where if the sleeping is interrupted the exception is ignored.
*
* @param millis to sleep
*/
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
// Ignore.
}
}
/**
* Batch HTTP request execute interceptor that loops through all individual HTTP requests and runs
* their interceptors.
*/
class BatchInterceptor implements HttpExecuteInterceptor {
private HttpExecuteInterceptor originalInterceptor;
BatchInterceptor(HttpExecuteInterceptor originalInterceptor) {
this.originalInterceptor = originalInterceptor;
}
public void intercept(HttpRequest batchRequest) throws IOException {
if (originalInterceptor != null) {
originalInterceptor.intercept(batchRequest);
}
for (RequestInfo<?, ?> requestInfo : requestInfos) {
HttpExecuteInterceptor interceptor = requestInfo.request.getInterceptor();
if (interceptor != null) {
interceptor.intercept(requestInfo.request);
}
}
}
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.
*/
/**
* JSON batch for Google API's.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.9
* @author Ravi Mistry
*/
package com.google.api.client.googleapis.batch.json;
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.batch.json;
import com.google.api.client.googleapis.batch.BatchCallback;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.http.HttpHeaders;
import java.io.IOException;
/**
* Callback for an individual batch JSON response.
*
* <p>
* Sample use:
* </p>
*
* <pre>
batch.queue(volumesList.buildHttpRequest(), Volumes.class, GoogleJsonErrorContainer.class,
new JsonBatchCallback<Volumes>() {
public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) {
log("Success");
printVolumes(volumes.getItems());
}
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
log(e.getMessage());
}
});
* </pre>
*
* @param <T> Type of the data model class
* @since 1.9
* @author rmistry@google.com (Ravi Mistry)
*/
public abstract class JsonBatchCallback<T> implements BatchCallback<T, GoogleJsonErrorContainer> {
public final void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders)
throws IOException {
onFailure(e.getError(), responseHeaders);
}
/**
* Called if the individual batch response is unsuccessful.
*
* <p>
* Upgrade warning: in prior version 1.12 the response headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*
* @param e Google JSON error response content
* @param responseHeaders Headers of the batch response
*/
public abstract void onFailure(GoogleJsonError e, HttpHeaders responseHeaders)
throws IOException;
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.
*/
/**
* Batch for Google API's.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.9
* @author Ravi Mistry
*/
package com.google.api.client.googleapis.batch;
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.batch;
import com.google.api.client.googleapis.batch.BatchRequest.RequestInfo;
import com.google.api.client.http.BackOffPolicy;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpStatusCodes;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.util.ObjectParser;
import com.google.api.client.util.StringUtils;
import com.google.common.base.Preconditions;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* The unparsed batch response.
*
* @author rmistry@google.com (Ravi Mistry)
*/
final class BatchUnparsedResponse {
/** The boundary used in the batch response to separate individual responses. */
private final String boundary;
/** List of request infos. */
private final List<RequestInfo<?, ?>> requestInfos;
/** Buffers characters from the input stream. */
private final BufferedReader bufferedReader;
/** Determines whether there are any responses to be parsed. */
boolean hasNext = true;
/** List of unsuccessful HTTP requests that can be retried. */
List<RequestInfo<?, ?>> unsuccessfulRequestInfos = new ArrayList<RequestInfo<?, ?>>();
/** Indicates if back off is required before the next retry. */
boolean backOffRequired;
/** The content Id the response is currently at. */
private int contentId = 0;
/** Whether unsuccessful HTTP requests can be retried. */
private final boolean retryAllowed;
/**
* Construct the {@link BatchUnparsedResponse}.
*
* @param inputStream Input stream that contains the batch response
* @param boundary The boundary of the batch response
* @param requestInfos List of request infos
* @param retryAllowed Whether unsuccessful HTTP requests can be retried
*/
BatchUnparsedResponse(InputStream inputStream, String boundary,
List<RequestInfo<?, ?>> requestInfos, boolean retryAllowed)
throws IOException {
this.boundary = boundary;
this.requestInfos = requestInfos;
this.retryAllowed = retryAllowed;
this.bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
// First line in the stream will be the boundary.
checkForFinalBoundary(bufferedReader.readLine());
}
/**
* Parses the next response in the queue if a data class and a {@link BatchCallback} is specified.
*
* <p>
* This method closes the input stream if there are no more individual responses left.
* </p>
*/
void parseNextResponse() throws IOException {
contentId++;
// Extract the outer headers.
String line;
while ((line = bufferedReader.readLine()) != null && !line.equals("")) {
// Do nothing.
}
// Extract the status code.
String statusLine = bufferedReader.readLine();
Preconditions.checkState(statusLine != null);
String[] statusParts = statusLine.split(" ");
int statusCode = Integer.parseInt(statusParts[1]);
// Extract and store the inner headers.
// TODO(rmistry): Handle inner headers that span multiple lines. More details here:
// http://tools.ietf.org/html/rfc2616#section-2.2
List<String> headerNames = new ArrayList<String>();
List<String> headerValues = new ArrayList<String>();
while ((line = bufferedReader.readLine()) != null && !line.equals("")) {
String[] headerParts = line.split(": ", 2);
headerNames.add(headerParts[0]);
headerValues.add(headerParts[1]);
}
// Extract the response part content.
// TODO(rmistry): Investigate a way to use the stream directly. This is to reduce the chance of
// an OutOfMemoryError and will make parsing more efficient.
StringBuilder partContent = new StringBuilder();
while ((line = bufferedReader.readLine()) != null && !line.startsWith(boundary)) {
partContent.append(line);
}
HttpResponse response =
getFakeResponse(statusCode, partContent.toString(), headerNames, headerValues);
parseAndCallback(requestInfos.get(contentId - 1), statusCode, contentId, response);
checkForFinalBoundary(line);
}
/**
* Parse an object into a new instance of the data class using
* {@link HttpResponse#parseAs(java.lang.reflect.Type)}.
*/
private <T, E> void parseAndCallback(
RequestInfo<T, E> requestInfo, int statusCode, int contentID, HttpResponse response)
throws IOException {
BatchCallback<T, E> callback = requestInfo.callback;
HttpHeaders responseHeaders = response.getHeaders();
HttpUnsuccessfulResponseHandler unsuccessfulResponseHandler =
requestInfo.request.getUnsuccessfulResponseHandler();
BackOffPolicy backOffPolicy = requestInfo.request.getBackOffPolicy();
// Reset backOff flag.
backOffRequired = false;
if (HttpStatusCodes.isSuccess(statusCode)) {
if (callback == null) {
// No point in parsing if there is no callback.
return;
}
T parsed = getParsedDataClass(
requestInfo.dataClass, response, requestInfo, responseHeaders.getContentType());
callback.onSuccess(parsed, responseHeaders);
} else {
HttpContent content = requestInfo.request.getContent();
boolean retrySupported = retryAllowed && (content == null || content.retrySupported());
boolean errorHandled = false;
boolean redirectRequest = false;
if (unsuccessfulResponseHandler != null) {
errorHandled = unsuccessfulResponseHandler.handleResponse(
requestInfo.request, response, retrySupported);
}
if (!errorHandled) {
if (requestInfo.request.handleRedirect(response.getStatusCode(), response.getHeaders())) {
redirectRequest = true;
} else if (retrySupported && backOffPolicy != null
&& backOffPolicy.isBackOffRequired(response.getStatusCode())) {
backOffRequired = true;
}
}
if (retrySupported && (errorHandled || backOffRequired || redirectRequest)) {
unsuccessfulRequestInfos.add(requestInfo);
} else {
if (callback == null) {
// No point in parsing if there is no callback.
return;
}
E parsed = getParsedDataClass(
requestInfo.errorClass, response, requestInfo, responseHeaders.getContentType());
callback.onFailure(parsed, responseHeaders);
}
}
}
@SuppressWarnings("deprecation")
private <A, T, E> A getParsedDataClass(
Class<A> dataClass, HttpResponse response, RequestInfo<T, E> requestInfo, String contentType)
throws IOException {
// TODO(mlinder): Remove the HttpResponse reference and directly parse the InputStream
com.google.api.client.http.HttpParser oldParser = requestInfo.request.getParser(contentType);
ObjectParser parser = requestInfo.request.getParser();
A parsed = null;
if (dataClass != Void.class) {
parsed = parser != null ? parser.parseAndClose(
response.getContent(), response.getContentCharset(), dataClass) : oldParser.parse(
response, dataClass);
}
return parsed;
}
/** Create a fake HTTP response object populated with the partContent and the statusCode. */
@Deprecated
private HttpResponse getFakeResponse(final int statusCode, final String partContent,
List<String> headerNames, List<String> headerValues)
throws IOException {
HttpRequest request = new FakeResponseHttpTransport(
statusCode, partContent, headerNames, headerValues).createRequestFactory()
.buildPostRequest(new GenericUrl("http://google.com/"), null);
request.setLoggingEnabled(false);
request.setThrowExceptionOnExecuteError(false);
return request.execute();
}
/**
* If the boundary line consists of the boundary and "--" then there are no more individual
* responses left to be parsed and the input stream is closed.
*/
private void checkForFinalBoundary(String boundaryLine) throws IOException {
if (boundaryLine.equals(boundary + "--")) {
hasNext = false;
bufferedReader.close();
}
}
@Deprecated
private static class FakeResponseHttpTransport extends HttpTransport {
private int statusCode;
private String partContent;
private List<String> headerNames;
private List<String> headerValues;
FakeResponseHttpTransport(
int statusCode, String partContent, List<String> headerNames, List<String> headerValues) {
super();
this.statusCode = statusCode;
this.partContent = partContent;
this.headerNames = headerNames;
this.headerValues = headerValues;
}
@Override
protected LowLevelHttpRequest buildDeleteRequest(String url) {
return null;
}
@Override
protected LowLevelHttpRequest buildGetRequest(String url) {
return null;
}
@Override
protected LowLevelHttpRequest buildPostRequest(String url) {
return new FakeLowLevelHttpRequest(partContent, statusCode, headerNames, headerValues);
}
@Override
protected LowLevelHttpRequest buildPutRequest(String url) {
return null;
}
}
@Deprecated
private static class FakeLowLevelHttpRequest extends LowLevelHttpRequest {
// TODO(rmistry): Read in partContent as bytes instead of String for efficiency.
private String partContent;
private int statusCode;
private List<String> headerNames;
private List<String> headerValues;
FakeLowLevelHttpRequest(
String partContent, int statusCode, List<String> headerNames, List<String> headerValues) {
this.partContent = partContent;
this.statusCode = statusCode;
this.headerNames = headerNames;
this.headerValues = headerValues;
}
@Override
public void addHeader(String name, String value) {
}
@Override
public void setContent(HttpContent content) {
}
@Override
public LowLevelHttpResponse execute() {
FakeLowLevelHttpResponse response = new FakeLowLevelHttpResponse(new ByteArrayInputStream(
StringUtils.getBytesUtf8(partContent)), statusCode, headerNames, headerValues);
return response;
}
}
@Deprecated
private static class FakeLowLevelHttpResponse extends LowLevelHttpResponse {
private InputStream partContent;
private int statusCode;
private List<String> headerNames = new ArrayList<String>();
private List<String> headerValues = new ArrayList<String>();
FakeLowLevelHttpResponse(InputStream partContent, int statusCode, List<String> headerNames,
List<String> headerValues) {
this.partContent = partContent;
this.statusCode = statusCode;
this.headerNames = headerNames;
this.headerValues = headerValues;
}
@Override
public InputStream getContent() {
return partContent;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getContentEncoding() {
return null;
}
@Override
public long getContentLength() {
return 0;
}
@Override
public String getContentType() {
return null;
}
@Override
public String getStatusLine() {
return null;
}
@Override
public String getReasonPhrase() {
return null;
}
@Override
public int getHeaderCount() {
return headerNames.size();
}
@Override
public String getHeaderName(int index) {
return headerNames.get(index);
}
@Override
public String getHeaderValue(int index) {
return headerValues.get(index);
}
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.batch;
import com.google.api.client.http.AbstractHttpContent;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.HttpRequest;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.List;
/**
* Serializes MIME Multipart/Mixed content as specified by <a
* href="http://tools.ietf.org/html/rfc2046">RFC 2046: Multipurpose Internet Mail Extensions</a>.
*
* <p>
* Takes in a list of {@link HttpRequest} and serializes their headers and content separating each
* request with a boundary. The "Content-ID" header of each request is incremented in order.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.9
* @author rmistry@google.com (Ravi Mistry)
*/
class MultipartMixedContent extends AbstractHttpContent {
private static final String CR_LF = "\r\n";
private static final String TWO_DASHES = "--";
/** List of request infos. */
private List<BatchRequest.RequestInfo<?, ?>> requestInfos;
/**
* Construct an instance of {@link MultipartMixedContent}.
*
* @param requestInfos List of request infos
* @param boundary Boundary string to use for separating each HTTP request
*/
MultipartMixedContent(List<BatchRequest.RequestInfo<?, ?>> requestInfos, String boundary) {
super(new HttpMediaType("multipart/mixed").setParameter(
"boundary", Preconditions.checkNotNull(boundary)));
Preconditions.checkNotNull(requestInfos);
Preconditions.checkArgument(!requestInfos.isEmpty());
this.requestInfos = Collections.unmodifiableList(requestInfos);
}
private String getBoundary() {
return getMediaType().getParameter("boundary");
}
public void writeTo(OutputStream out) throws IOException {
int contentId = 1;
Writer writer = new OutputStreamWriter(out);
String boundary = getBoundary();
for (BatchRequest.RequestInfo<?, ?> requestInfo : requestInfos) {
HttpRequest request = requestInfo.request;
// Write batch separator.
writer.write(TWO_DASHES);
writer.write(boundary);
writer.write(CR_LF);
// Write multipart headers.
writer.write("Content-Type: application/http");
writer.write(CR_LF);
writer.write("Content-Transfer-Encoding: binary");
writer.write(CR_LF);
writer.write("Content-ID: ");
writer.write(String.valueOf(contentId++));
writer.write(CR_LF);
writer.write(CR_LF);
// Write the batch method and path.
writer.write(request.getRequestMethod());
writer.write(" ");
writer.write(request.getUrl().build());
writer.write(CR_LF);
// Write the batch headers.
HttpHeaders.serializeHeadersForMultipartRequests(request.getHeaders(), null, null, writer);
// Write the data to the body.
HttpContent data = request.getContent();
if (data != null) {
String type = data.getType();
if (type != null) {
writeHeader(writer, "Content-Type", type);
}
long length = data.getLength();
if (length != -1) {
writeHeader(writer, "Content-Length", length);
}
writer.write(CR_LF);
writer.flush();
data.writeTo(out);
}
writer.write(CR_LF);
}
// Write the end of the batch separator.
writer.write(TWO_DASHES);
writer.write(boundary);
writer.write(TWO_DASHES);
writer.write(CR_LF);
writer.flush();
}
/** Writes a header to the Writer. */
private void writeHeader(Writer writer, String name, Object value) throws IOException {
writer.write(name);
writer.write(": ");
writer.write(value.toString());
writer.write(CR_LF);
}
@Override
public MultipartMixedContent setMediaType(HttpMediaType mediaType) {
super.setMediaType(mediaType);
return this;
}
}
| Java |
/*
* Copyright (c) 2012 Google Inc.
*
* 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.google.api.client.googleapis.batch;
import com.google.api.client.http.HttpHeaders;
import java.io.IOException;
/**
* Callback for an individual batch response.
*
* <p>
* Sample use:
* </p>
*
* <pre>
batch.queue(volumesList.buildHttpRequest(), Volumes.class, GoogleJsonErrorContainer.class,
new BatchCallback<Volumes, GoogleJsonErrorContainer>() {
public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) {
log("Success");
printVolumes(volumes.getItems());
}
public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) {
log(e.getError().getMessage());
}
});
* </pre>
*
* @param <T> Type of the data model class
* @param <E> Type of the error data model class
* @since 1.9
* @author rmistry@google.com (Ravi Mistry)
*/
public interface BatchCallback<T, E> {
/**
* Called if the individual batch response is successful.
*
* <p>
* Upgrade warning: this method now throws an {@link IOException}. In prior version 1.11 it did
* not throw an exception.
* </p>
*
* <p>
* Upgrade warning: in prior version 1.12 the response headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*
* @param t instance of the parsed data model class
* @param responseHeaders Headers of the batch response
*/
void onSuccess(T t, HttpHeaders responseHeaders) throws IOException;
/**
* Called if the individual batch response is unsuccessful.
*
* <p>
* Upgrade warning: in prior version 1.12 the response headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*
* @param e instance of data class representing the error response content
* @param responseHeaders Headers of the batch response
*/
void onFailure(E e, HttpHeaders responseHeaders) throws IOException;
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.testing.services;
import com.google.api.client.googleapis.services.AbstractGoogleClient;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.ObjectParser;
/**
* Thread-safe mock Google client.
*
* @since 1.12
* @author Yaniv Inbar
*/
public class MockGoogleClient extends AbstractGoogleClient {
/**
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param objectParser object parser
*/
public MockGoogleClient(HttpTransport transport, HttpRequestInitializer httpRequestInitializer,
String rootUrl, String servicePath, ObjectParser objectParser) {
super(transport, httpRequestInitializer, rootUrl, servicePath, objectParser);
}
/**
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param objectParser object parser or {@code null} for none
* @param googleClientRequestInitializer Google request initializer or {@code null} for none
* @param applicationName application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @param suppressPatternChecks whether discovery pattern checks should be suppressed on required
* parameters
*/
public MockGoogleClient(HttpTransport transport, HttpRequestInitializer httpRequestInitializer,
String rootUrl, String servicePath, ObjectParser objectParser,
GoogleClientRequestInitializer googleClientRequestInitializer, String applicationName,
boolean suppressPatternChecks) {
super(transport, httpRequestInitializer, rootUrl, servicePath, objectParser,
googleClientRequestInitializer, applicationName, suppressPatternChecks);
}
/**
* Builder for {@link MockGoogleClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
public static class Builder extends AbstractGoogleClient.Builder {
/**
* @param transport The transport to use for requests
* @param rootUrl root URL of the service. Must end with a "/"
* @param servicePath service path
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
*/
public Builder(HttpTransport transport, String rootUrl, String servicePath,
ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) {
super(transport, rootUrl, servicePath, objectParser, httpRequestInitializer);
}
@Override
public MockGoogleClient build() {
return new MockGoogleClient(getTransport(), getHttpRequestInitializer(), getRootUrl(),
getServicePath(), getObjectParser(), getGoogleClientRequestInitializer(),
getApplicationName(), getSuppressPatternChecks());
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setGoogleClientRequestInitializer(
GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
@Override
public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
}
}
| Java |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Test utilities for the {@code com.google.api.client.googleapis.json} package.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.testing.services.json;
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.