code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
#pragma once
#include "VisualizeObj2D.hpp"
#include <Graphics/BMPFont.hpp>
namespace zzz{
class VText2D : public VisualizeObj2D
{
public:
VText2D(string &str,int x, int y):str_(str)
{
Vector2i size=BMPFont::Instance().Size(str.c_str());
bbox_.Min()=Vector2i(x, y);
bbox_.Max()=Vector2i(x+size[0], y+size[1]);
}
virtual void DrawPixels(Vis2DRenderer *renderer, double basex, double basey)
{
int x = basex + bbox_.Min(0);
int y = basey + bbox_.Min(1);
renderer->SetRasterPos(x, y);
BMPFont::Instance().Draw(str_.c_str());
}
string str_;
int posx_,posy_;
};
}
|
zzz-engine
|
zzzEngine/zVisualization/zVisualization/Visualizer/VText2D.hpp
|
C++
|
gpl3
| 627
|
SET(THISLIB zImage)
FILE(GLOB_RECURSE LibSrc *.cpp)
IF( "${DEBUG_MODE}" EQUAL "1")
SET(THISLIB ${THISLIB}D)
ENDIF()
IF( "${BIT_MODE}" EQUAL "64" )
SET(THISLIB ${THISLIB}_X64)
ENDIF()
ADD_LIBRARY(${THISLIB} STATIC ${LibSrc})
#MESSAGE("zImage Lib Path: ${BASENAME}")
|
zzz-engine
|
zzzEngine/zImage/CMakeLists.txt
|
CMake
|
gpl3
| 277
|
#pragma once
// Separate link so when change a lib, only link needs redo.
#include "zImageConfig.hpp"
#ifndef ZZZ_NO_PRAGMA_LIB
#ifdef ZZZ_COMPILER_MSVC
#ifdef ZZZ_LIB_LIBJPEG
#ifdef ZZZ_OS_WIN64
#pragma comment(lib,"jpeg_x64.lib")
#else
#pragma comment(lib,"jpeg.lib")
#endif
#endif
#ifdef ZZZ_LIB_LIBPNG
#ifdef ZZZ_OS_WIN64
#pragma comment(lib,"libpng15_x64.lib")
#else
#pragma comment(lib,"libpng15.lib")
#endif
#endif
#ifdef ZZZ_LIB_LIBTIFF
#ifdef ZZZ_OS_WIN64
#pragma comment(lib,"libtiff_x64.lib")
#else
#pragma comment(lib,"libtiff.lib")
#endif
#endif
#ifdef ZZZ_LIB_DEVIL
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"devil.lib")
#pragma comment(lib,"ilu.lib")
#pragma comment(lib,"ilut.lib")
#else
#pragma comment(lib,"devil_x64.lib")
#pragma comment(lib,"ilu_x64.lib")
#pragma comment(lib,"ilut_x64.lib")
#endif
#endif // ZZZ_LIB_DEVIL
#ifdef ZZZ_LIB_FREEIMAGE
#pragma comment(lib,"FreeImage.lib")
#endif // ZZZ_LIB_FREEIMAGE
#endif // ZZZ_COMPILER_MSVC
#endif // ZZZ_NO_PRAGMA_LIB
|
zzz-engine
|
zzzEngine/zImage/zImage/zImageAutoLink3rdParty.hpp
|
C++
|
gpl3
| 1,050
|
#pragma once
// Separate link so when change a lib, only link needs redo.
#include "zImageConfig.hpp"
#include "zImageAutoLink3rdParty.hpp"
#ifndef ZZZ_NO_PRAGMA_LIB
#ifdef ZZZ_COMPILER_MSVC
#ifdef ZZZ_DYNAMIC
#ifdef ZZZ_DEBUG
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zImageD.lib")
#else
#pragma comment(lib,"zImageD_x64.lib")
#endif // ZZZ_OS_WIN64
#else
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zImage.lib")
#else
#pragma comment(lib,"zImage_x64.lib")
#endif // ZZZ_OS_WIN64
#endif
#else
#ifdef ZZZ_DEBUG
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zImageD.lib")
#else
#pragma comment(lib,"zImageD_x64.lib")
#endif // ZZZ_OS_WIN64
#else
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zImage.lib")
#else
#pragma comment(lib,"zImage_x64.lib")
#endif // ZZZ_OS_WIN64
#endif
#endif
#endif // ZZZ_COMPILER_MSVC
#endif // ZZZ_NO_PRAGMA_LIB
|
zzz-engine
|
zzzEngine/zImage/zImage/zImageAutoLink.hpp
|
C++
|
gpl3
| 988
|
#pragma once
#include "Image.hpp"
#include <zMat.hpp>
//For simple image process
//scale, flip, offset, etc
//TODO: flip...
namespace zzz{
template<typename T>
class ImageProcessor
{
public:
static void ScaleToShow(Image<T> &image);
static void FlipH(Image<T> &image) //flip horizontally
{
Array<2,T> ori(image);
Dress(image)=Dress(ori)(Colon(),Colon(image.Cols()-1,0,-1));
}
static void FlipV(Image<T> &image) //flip vertically
{
Array<2,T> ori(image);
Dress(image)=Dress(ori)(Colon(image.Rows()-1,0,-1),Colon());
}
};
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageProcessor.hpp
|
C++
|
gpl3
| 580
|
#include "ImageProcessor.hpp"
#include <Graphics\AABB.hpp>
namespace zzz {
template<>
void ImageProcessor<float>::ScaleToShow(Image<float> &image)
{
float minx=image.Min(),maxx=image.Max();
float diff = maxx-minx;
float scale = 1.0f / diff;
for (zuint i=0; i<image.size(); i++)
{
image[i]-=minx;
image[i]*=scale;
}
}
template<>
void ImageProcessor<Vector3f>::ScaleToShow(Image<Vector3f> &image)
{
AABB<3,float> aabb;
aabb.AddData(image.begin(), image.end());
Vector3f diff=aabb.Diff();
Vector3f scale=Vector3f(1.0f)/diff;
for (zuint i=0; i<image.size(); i++)
{
image[i]-=aabb.Min();
image[i]*=scale;
}
}
}; // namespace zzz
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageProcessor.cpp
|
C++
|
gpl3
| 700
|
#pragma once
#include <Math/Vector2.hpp>
#include <Math/Array2.hpp>
#include <Utility/IOInterface.hpp>
#include "ImageDefines.hpp"
//Image cooridnate is row(bottom to top), col(left to right)
//always use row and column
//therefore x,y must be translated
//make it this way is to coorperate with opengl
//so you do not need to flip when using textures or drawpi
namespace zzz{
template<typename T>
class Image : public Array<2,T>, public IOData {
using Array<2,T>::sizes;
public:
Image()
:orir_(0),oric_(0) {
}
Image(const Image<T> &image)
:orir_(image.orir_),oric_(image.oric_) {
*this=image;
}
Image(int nrow, int ncol)
:Array<2,T>(nrow, ncol), orir_(0),oric_(0) {
}
explicit Image(const string &filename)
:orir_(0),oric_(0) {
LoadFile(filename);
}
explicit Image(const Vector2ui size)
:Array<2,T>(size),orir_(0),oric_(0) {
}
using Array<2,T>::SetSize;
zuint Rows() const {
return sizes[0];
}
zuint Cols() const {
return sizes[1];
}
bool LoadFile(const string &filename);
bool SaveFile(const string &filename);
//half width, half height
void HalfImageTo(Image<T> &image) const;
void HalfImage() {
Image<T> img;
HalfImageTo(img);
*this=img;
}
//double width, double height, no interpolation
void DoubleImageTo(Image<T> &image) const;
void DoubleImage() {
Image<T> img;
DoubleImageTo(img);
*this=img;
}
//enlarge or shrink image
void ResizeTo(Image<T> &image) const;
void Resize(int nrow, int ncol) {
Image<T> img(nrow,ncol);
if (sizes[0]!=0 && sizes[1]!=0)
ResizeTo(img);
*this=img;
}
//access
T & At(int r, int c) {
return Array<2,T>::At(r+orir_, c+oric_);
}
const T & At(int r, int c) const {
return Array<2,T>::At(r+orir_, c+oric_);
}
T & operator()(int r, int c) {
return At(r, c);
}
const T & operator()(int r, int c) const {
return At(r, c);
}
//toindex
zuint ToIndex(const VectorBase<2,int> &pos) const {
return Vector2ui(pos[0]+orir_,pos[1]+oric_).Dot(Array<2,T>::subsizes);
}
VectorBase<2,int> ToIndex(zuint idx) const {
Vector<2,int> pos(Array<2,T>::ToIndex(idx));
pos[0]-=orir_;
pos[1]-=oric_;
return pos;
}
//interpolate
template<typename T1>
T Interpolate(const Vector<2,T1> &rc) const {
return Interpolate(rc[0], rc[1]);
}
template<typename T1>
T Interpolate(T1 r, T1 c) const {
double row(r), col(c);
// do the interpolation
int r0=Clamp<int>(-orir_,floor(row),int(Rows())-1-orir_);
int r1=Clamp<int>(-orir_,ceil(row),int(Rows())-1-orir_);
int c0=Clamp<int>(-oric_,floor(col),int(Cols())-1-oric_);
int c1=Clamp<int>(-oric_,ceil(col),int(Cols())-1-oric_);
const double fractR = row - r0;
const double fractC = col - c0;
const T syx = At(r0,c0);
const T syx1 = At(r0,c1);
const T sy1x = At(r1,c0);
const T sy1x1 = At(r1,c1);
// normal interpolation within range
const T tmp1 = syx + (syx1-syx)*fractC;
const T tmp2 = sy1x + (sy1x1-sy1x)*fractC;
return (tmp1 + (tmp2-tmp1)*fractR);
}
using Array<2,T>::operator[];
//inside image
template<typename T1>
bool IsInside(const Vector<2,T1> &pos) const {
if (Within<T1>(0,pos[0]+orir_,Rows()-EPSILON) && Within<T1>(0,pos[1]+oric_,Cols()-EPSILON)) return true;
else return false;
}
//upleft is zero, right is x, down is y
template<typename T1>
Vector<2,T1> ConvertImageCoordFromXY(T1 x, T1 y) const {
return Vector<2,T1>(Rows()-1-y,x);
}
//downleft is zero, right is x, up is y
template<typename T1>
Vector<2,T1> ConvertImageCoordFromX_Y(T1 x, T1 y) const {
return Vector<2,T1>(y,x);
}
public:
int orir_, oric_;
public:
static const int Channels_,Format_,Type_;
};
template<typename T>
void zzz::Image<T>::ResizeTo(Image<T> &dest) const {
zuint r,c;
double fr,fc;
const double dc = static_cast<double>(Cols()-1)/(dest.Cols()-1);
const double dr = static_cast<double>(Rows()-1)/(dest.Rows()-1);
for (fr=0.0,r=0; r<dest.Rows(); ++r,fr+=dr) for (fc=0.0,c=0; c<dest.Cols(); ++c,fc+=dc)
dest.At(r,c) = Interpolate(fr,fc);
}
template<typename T>
void zzz::Image<T>::DoubleImageTo(Image<T> &image) const {
int row=Rows()*2;
int column=Cols()*2;
image.SetSize(row,column);
for (int i=0; i<row; i++) for (int j=0; j<column; j++)
image.At(i,j)=At(i/2,j/2);
}
template<typename T>
void zzz::Image<T>::HalfImageTo(Image<T> &image) const {
int row=Rows()/2;
int column=Cols()/2;
image.SetSize(row,column);
for (int i=0; i<row; i++) for (int j=0; j<column; j++)
image.At(i,j)=At(i*2,j*2);
}
typedef Image<float> Imagef;
typedef Image<zuchar> Imageuc;
typedef Image<Vector3f> Image3f;
typedef Image<Vector3uc> Image3uc;
typedef Image<Vector4f> Image4f;
typedef Image<Vector4uc> Image4uc;
// IOObject
template<typename T>
class IOObject<Image<T> >
{
public:
static void WriteFileB(FILE *fp, const Image<T> &src) {
IOObject<ArrayBase<2,T> >::WriteFileB(fp, src);
IOObject<int>::WriteFileB(fp, src.orir_);
IOObject<int>::WriteFileB(fp, src.oric_);
}
static void ReadFileB(FILE *fp, Image<T>& dst) {
IOObject<ArrayBase<2,T> >::ReadFileB(fp, dst);
IOObject<int>::ReadFileB(fp, dst.orir_);
IOObject<int>::ReadFileB(fp, dst.oric_);
}
static void WriteFileR(RecordFile &fp, const zint32 label, const Image<T>& src) {
IOObject<ArrayBase<2,T> >::WriteFileR(fp, label, src);
IOObject<int>::WriteFileR(fp, src.orir_);
IOObject<int>::WriteFileR(fp, src.oric_);
}
static void ReadFileR(RecordFile &fp, const zint32 label, Image<T>& dst) {
IOObject<ArrayBase<2,T> >::ReadFileR(fp, label, dst);
IOObject<int>::ReadFileR(fp, dst.orir_);
IOObject<int>::ReadFileR(fp, dst.oric_);
}
};
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/Image.hpp
|
C++
|
gpl3
| 5,970
|
#pragma once
#include "Image.hpp"
//For drawing element onto image
namespace zzz{
// cannot be put into the class, otherwise cannot be implement in cpp
void RasterizeLine(int r0, int c0, int r1, int c1, vector<Vector2i> &res);
template<typename T>
class ImageDrawer
{
public:
ImageDrawer(Image<T> &img):img_(img){}
Image<T> &img_;
void DrawPoint(const T &p, int pos, float alpha=1);
void DrawPoint(const T &p, int r, int c, float alpha=1);
void DrawLine(const T &p, double r0, double c0, double r1, double c1, float alpha=1);
void DrawCircle(const T &p, double r0, double c0, double radius, float alpha=1);
void DrawBox(const T &p, double r0, double c0, double r1, double c1, float alpha=1);
void DrawCross(const T &p, double r0, double c0, double len, float alpha=1);
void FillBox(const T &p, double r0, double c0, double r1, double c1, float alpha=1);
void FillCircle(const T &p, double r0, double c0, double radius, float alpha=1);
};
template<typename T>
void ImageDrawer<T>::DrawPoint(const T &p, int pos, float alpha)
{
if (!Within(0,pos,(int)img_.size()-1)) return;
img_.at(pos)=p*alpha+img_.at(pos)*(1.0f-alpha);
}
template<typename T>
void ImageDrawer<T>::DrawPoint(const T &p, int r, int c, float alpha)
{
if (!img_.IsInside(Vector2i(r,c))) return;
img_.At(r,c)=p*alpha+img_.At(r,c)*(1.0f-alpha);
}
template<typename T>
void ImageDrawer<T>::DrawLine(const T &p, double r0, double c0, double r1, double c1, float alpha)
{
int ir0=int(floor(r0)), ic0=int(floor(c0));
int ir1=int(floor(r1)), ic1=int(floor(c1));
vector<Vector2i> line;
RasterizeLine(ir0,ic0,ir1,ic1,line);
for (zuint i=0; i<line.size(); i++)
DrawPoint(p,line[i][0],line[i][1],alpha);
}
template<typename T>
void ImageDrawer<T>::DrawCircle(const T &p, double r0, double c0, double radius, float alpha)
{
int ir0=int(floor(r0)), ic0=int(floor(c0));
int sr=Round(ir0+radius*cos(0.0)),sc=Round(ic0+radius*sin(0.0));
for (int i=1; i<=20; i++)
{
double angle=i/20.0*PI*2;
int sr1=Round(ir0+radius*cos(angle)),sc1=Round(ic0+radius*sin(angle));
DrawLine(p,sr,sc,sr1,sc1,alpha);
sr=sr1;sc=sc1;
}
}
template<typename T>
void ImageDrawer<T>::DrawBox(const T &p, double r0, double c0, double r1, double c1, float alpha)
{
DrawLine(p,r0,c0,r1,c0,alpha);
DrawLine(p,r1,c0,r1,c1,alpha);
DrawLine(p,r1,c1,r0,c1,alpha);
DrawLine(p,r0,c1,r0,c0,alpha);
}
template<typename T>
void ImageDrawer<T>::DrawCross(const T &p, double r0, double c0, double len, float alpha)
{
DrawLine(p,r0,c0,r0+len,c0,alpha);
DrawLine(p,r0,c0,r0,c0+len,alpha);
DrawLine(p,r0,c0,r0-len,c0,alpha);
DrawLine(p,r0,c0,r0,c0-len,alpha);
}
template<typename T>
void ImageDrawer<T>::FillBox(const T &p, double r0, double c0, double r1, double c1, float alpha)
{
if (r0<r1)
for (int r=r0; r<=r1; r++)
DrawLine(p,r,c0,r,c1,alpha);
else
for (int r=r1; r<=r0; r++)
DrawLine(p,r,c0,r,c1,alpha);
}
//there should be a faster way to do this
//fill it row by row
//for each row, find the start point and end point
template<typename T>
void ImageDrawer<T>::FillCircle(const T &p, double r0, double c0, double radius, float alpha)
{
int ir0=int(floor(r0)), ic0=int(floor(c0));
for (int r=ir0-radius; r<ir0; r++)
{
// if (r<0 || r>=(int)img_.Rows()) continue;
double halfwidth=Sqrt<double>(radius*radius-(r-ir0)*(r-ir0));
DrawLine(p,r,Round(ic0-halfwidth),r,Round(ic0+halfwidth),alpha);
DrawLine(p,2*r0-r,Round(ic0-halfwidth),2*r0-r,Round(ic0+halfwidth),alpha);
}
DrawLine(p,ir0,ic0-radius,ir0,ic0+radius,alpha);
}
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageDrawer.hpp
|
C++
|
gpl3
| 3,697
|
#pragma once
#include "Image.hpp"
namespace zzz{
template<typename T>
class PixelHelper {
public:
static const T Min;
static const T Max;
static inline T Clamp(const T& v)
{
return zzz::Clamp<T>(Min, v, Max);
}
template<typename T1>
static inline T Clamp(const T1& v)
{
return static_cast<T>(zzz::Clamp<T1>(Min, v, Max));
}
};
template<typename FROM, typename TO>
inline void ConvertPixel(const FROM &from, TO &to);
template<typename FROM, typename TO>
inline TO ConvertPixel(const FROM &from)
{
TO to;
ConvertPixel<FROM, TO>(from,to);
return to;
}
template<typename FROM, typename TO>
void ConvertImage(const Image<FROM> &from, Image<TO> &to)
{
to.SetSize(from.Size());
to.orir_=from.orir_;
to.oric_=from.oric_;
for (zuint i=0; i<from.size(); i++)
ConvertPixel<FROM, TO>(from[i],to[i]);
}
//clamp
template<>
inline Vector3f PixelHelper<Vector3f>::Clamp(const Vector3f& v)
{
Vector3f x=v;
x[0]=zzz::Clamp<float>(Min[0],x[0],Max[0]);
x[1]=zzz::Clamp<float>(Min[1],x[1],Max[1]);
x[2]=zzz::Clamp<float>(Min[2],x[2],Max[2]);
return x;
}
template<>
inline Vector4f PixelHelper<Vector4f>::Clamp(const Vector4f& v)
{
Vector4f x=v;
x[0]=zzz::Clamp<float>(Min[0],x[0],Max[0]);
x[1]=zzz::Clamp<float>(Min[1],x[1],Max[1]);
x[2]=zzz::Clamp<float>(Min[2],x[2],Max[2]);
x[3]=zzz::Clamp<float>(Min[3],x[3],Max[3]);
return x;
}
template<>
inline Vector3uc PixelHelper<Vector3uc>::Clamp(const Vector3uc& v)
{
Vector3uc x=v;
zzz::Clamp<zuchar>(Min[0],x[0],Max[0]);
zzz::Clamp<zuchar>(Min[1],x[1],Max[1]);
zzz::Clamp<zuchar>(Min[2],x[2],Max[2]);
return x;
}
template<>
inline Vector4uc PixelHelper<Vector4uc>::Clamp(const Vector4uc& v)
{
Vector4uc x=v;
zzz::Clamp<zuchar>(Min[0],x[0],Max[0]);
zzz::Clamp<zuchar>(Min[1],x[1],Max[1]);
zzz::Clamp<zuchar>(Min[2],x[2],Max[2]);
zzz::Clamp<zuchar>(Min[3],x[3],Max[3]);
return x;
}
//conversion function
template<>
inline void ConvertPixel<zuchar, float>(const zuchar &v, float &t)
{t=PixelHelper<float>::Clamp(v/255.0f);}
template<>
inline void ConvertPixel<float, zuchar>(const float &v, zuchar &t)
{t=PixelHelper<zuchar>::Clamp(v*255.0f);}
template<>
inline void ConvertPixel<Vector3uc, zuchar>(const Vector3uc &v, zuchar &t)
{t=PixelHelper<zuchar>::Clamp(int((0.212671f *v[0] + 0.715160f * v[1] + 0.072169f * v[2])));}
template<>
inline void ConvertPixel<Vector4uc, zuchar>(const Vector4uc &v, zuchar &t)
{t=PixelHelper<zuchar>::Clamp(int((0.212671f *v[0] + 0.715160f * v[1] + 0.072169f * v[2])));}
template<>
inline void ConvertPixel<Vector3f, float>(const Vector3f &v, float &t)
{t=PixelHelper<float>::Clamp((0.212671f *v[0] + 0.715160f * v[1] + 0.072169f * v[2]));}
template<>
inline void ConvertPixel<Vector4f, float>(const Vector4f &v, float &t)
{t=PixelHelper<float>::Clamp((0.212671f *v[0] + 0.715160f * v[1] + 0.072169f * v[2]));}
template<>
inline void ConvertPixel<Vector3uc, float>(const Vector3uc &v, float &t)
{t=PixelHelper<float>::Clamp(0.212671f * v[0] / 255.0f + 0.715160f * v[1] / 255.0f + 0.072169f * v[2] / 255.0f);}
template<>
inline void ConvertPixel<float, Vector3f>(const float &v, Vector3f &t)
{t=Vector3f(v);}
template<>
inline void ConvertPixel<zuchar, Vector3f>(const zuchar &v, Vector3f &t)
{t=Vector3f(v/255.0f);}
template<>
inline void ConvertPixel<Vector3uc, Vector3f>(const Vector3uc &v, Vector3f &t)
{t=Vector3f(v[0] / 255.0f, v[1] / 255.0f, v[2] / 255.0f);}
template<>
inline void ConvertPixel<Vector3f, Vector3uc>(const Vector3f &v, Vector3uc &t)
{t=Vector3uc(v[0] * 255.0f, v[1] * 255.0f, v[2] * 255.0f);}
template<>
inline void ConvertPixel<Vector3f, Vector4f>(const Vector3f& v, Vector4f &t)
{t=Vector4f(v[0],v[1],v[2],1.0f);}
template<>
inline void ConvertPixel<Vector4f, Vector3f>(const Vector4f& v, Vector3f &t)
{t=Vector3f(v[0],v[1],v[2]);}
template<>
inline void ConvertPixel<Vector4f, Vector4uc>(const Vector4f& v, Vector4uc &t)
{t=Vector4uc(v[0]*255.0f,v[1]*255.0f,v[2]*255.0f,v[3]*255.0f);}
template<>
inline void ConvertPixel<Vector4uc, Vector4f>(const Vector4uc& v, Vector4f &t)
{t=Vector4f(v[0]/255.0f,v[1]/255.0f,v[2]/255.0f,v[3]/255.0f);}
template<>
inline void ConvertPixel<Vector3f, zuchar>(const Vector3f &v, zuchar &t)
{t=PixelHelper<zuchar>::Clamp((0.212671f *v[0] + 0.715160f * v[1] + 0.072169f * v[2])*255);}
} // namespace zzz
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageHelper.hpp
|
C++
|
gpl3
| 4,482
|
#pragma once
namespace zzz{
//copy from gl.h
#define ZZZ_BYTE 0x1400
#define ZZZ_UNSIGNED_BYTE 0x1401
#define ZZZ_SHORT 0x1402
#define ZZZ_UNSIGNED_SHORT 0x1403
#define ZZZ_INT 0x1404
#define ZZZ_UNSIGNED_INT 0x1405
#define ZZZ_FLOAT 0x1406
#define ZZZ_DOUBLE 0x140A
#define ZZZ_RGB 0x1907
#define ZZZ_RGBA 0x1908
#define ZZZ_LUMINANCE 0x1909
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageDefines.hpp
|
C++
|
gpl3
| 616
|
#include "ImageDrawer.hpp"
namespace zzz{
void RasterizeLine(int r0, int c0, int r1, int c1, vector<Vector2i> &res)
{
res.clear();
double dr=r1-r0,dc=c1-c0;
if (dr==0 && dc==0)
{
res.push_back(Vector2i(r0,c0));
return;
}
if (abs(dr)>abs(dc))
{
double slope=dc/dr;
if (r1>r0)
for (int r=r0; r<=r1; r++)
{
int c=Round((r-r0)*slope+c0);
res.push_back(Vector2i(r,c));
}
else
for (int r=r1; r<=r0; r++)
{
int c=Round((r-r0)*slope+c0);
res.push_back(Vector2i(r,c));
}
}
else
{
double slope=dr/dc;
if (c1>c0)
for (int c=c0; c<=c1; c++)
{
int r=Round((c-c0)*slope+r0);
res.push_back(Vector2i(r,c));
}
else
for (int c=c1; c<=c0; c++)
{
int r=Round((c-c0)*slope+r0);
res.push_back(Vector2i(r,c));
}
}
return;
}
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageDrawer.cpp
|
C++
|
gpl3
| 943
|
#pragma once
#include "../Utility/CacheSet.hpp"
#include "Image.hpp"
namespace zzz{
class ImageDirCacheSet : public CacheSet<Image3uc>
{
public:
void SetFiles(const vector<string> &files, int cache_size)
{
files_=files;
SetSize(files_.size(),cache_size);
}
private:
Image3uc* Load(zuint i)
{
Image3uc *img=new Image3uc(files_[i].c_str());
return img;
}
vector<string> files_;
};
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageDirCacheSet.hpp
|
C++
|
gpl3
| 432
|
#include "ImageHelper.hpp"
namespace zzz{
//Min and Max
template<>
const float PixelHelper<float>::Min=0;
template<>
const float PixelHelper<float>::Max=1;
template<>
const Vector3f PixelHelper<Vector3f>::Min=Vector3f(0,0,0);
template<>
const Vector3f PixelHelper<Vector3f>::Max=Vector3f(1,1,1);
template<>
const Vector4f PixelHelper<Vector4f>::Min=Vector4f(0,0,0,0);
template<>
const Vector4f PixelHelper<Vector4f>::Max=Vector4f(1,1,1,1);
template<>
const zuchar PixelHelper<zuchar>::Min=0;
template<>
const zuchar PixelHelper<zuchar>::Max=255;
template<>
const Vector3uc PixelHelper<Vector3uc>::Min=Vector3uc(0,0,0);
template<>
const Vector3uc PixelHelper<Vector3uc>::Max=Vector3uc(255,255,255);
template<>
const Vector4uc PixelHelper<Vector4uc>::Min=Vector4uc(0,0,0,0);
template<>
const Vector4uc PixelHelper<Vector4uc>::Max=Vector4uc(255,255,255,255);
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageHelper.cpp
|
C++
|
gpl3
| 892
|
#pragma once
#include <Math/Vector2.hpp>
namespace zzz{
//R=row, C=column
//R from bottom to top, C from left to right
//_R from top to bottom, _C from right ot left
//X from left to right, Y from bottom to top
//_X from right to left, _Y from top to bottom
//X=C, Y=R
//image coordinate used in Image is R,C
typedef Vector2f CoordRCf; //original
typedef Vector2f CoordXYf; //xy
typedef Vector2f CoordX_Yf; //x,-y
typedef Vector2f Coord_XYf; //-x,y
typedef Vector2f32 CoordRCf32; //original
typedef Vector2f32 CoordXYf32; //xy
typedef Vector2f32 CoordX_Yf32; //x,-y
typedef Vector2f32 Coord_XYf32; //-x,y
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageCoord.hpp
|
C++
|
gpl3
| 652
|
#include "Image.hpp"
namespace zzz{
#define IMAGE_SPECIALIZE(T,format,type,channels) \
template<>\
const int Image<T>::Channels_=channels; \
template<>\
const int Image<T>::Format_=format; \
template<>\
const int Image<T>::Type_=type;
IMAGE_SPECIALIZE(Vector4uc,ZZZ_RGBA,ZZZ_UNSIGNED_BYTE,4);
IMAGE_SPECIALIZE(Vector4f,ZZZ_RGBA,ZZZ_FLOAT,4);
IMAGE_SPECIALIZE(Vector3uc,ZZZ_RGB,ZZZ_UNSIGNED_BYTE,3);
IMAGE_SPECIALIZE(Vector3f,ZZZ_RGB,ZZZ_FLOAT,3);
IMAGE_SPECIALIZE(zuchar,ZZZ_LUMINANCE,ZZZ_UNSIGNED_BYTE,1);
IMAGE_SPECIALIZE(float,ZZZ_LUMINANCE,ZZZ_FLOAT,1);
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/Image.cpp
|
C++
|
gpl3
| 578
|
#pragma once
#include "Image.hpp"
#include "ImageHelper.hpp"
#include <Function/GaussianFunction.hpp>
#include <Function/Gaussian2DFunction.hpp>
#include <Math/DVector.hpp>
#include <Math/DMatrix.hpp>
namespace zzz{
template<typename T>
class ImageFilter
{
public:
//general convolve
static void ConvolveRow(DVectord & kern, Image<T> * src, Image<T> * dst); //convolve row
static void ConvolveCol(DVectord & kern, Image<T> * src, Image<T> * dst); //convolve column
static void ConvolveDouble(DVectord &kern, Image<T> *src, Image<T> * dst); //first convolve row, then convolve column
static void Convolve2D(DMatrixd &kern, Image<T> *src, Image<T> *dst); //convolve a 2d block
private:
static T ConvolveRowHelper(DVectord & kernel, Image<T> * src, zuint r, zuint c);
static T ConvolveColHelper(DVectord & kernel, Image<T> * src, zuint r, zuint c);
static T Convolve2DHelper(DMatrixd & kernel, Image<T> * src, zuint r, zuint c);
public:
//Gaussian Blur
static void GaussBlurImage(Image<T> * src, Image<T> * dst, int kernelsize, double sigma);
static DVectord GaussianKernel1D(int kernelsize, double sigma);
static DMatrixd GaussianKernel2D(int kernelsize, double sigma);
};
//general
template<typename T>
T ImageFilter<T>::ConvolveRowHelper(DVectord & kernel, Image<T> * src, zuint r, zuint c)
{
T pixel(0);
int cen = kernel.size / 2;
for (int i = 0; i < (int)kernel.size; i++)
{
int col = c + (i - cen);
if (col < 0) col = 0;
if (col >= (int)src->Cols()) col = src->Cols() - 1;
pixel += src->At(r,col)*kernel[i];
}
return PixelHelper<T>::Clamp(pixel);
}
template<typename T>
void ImageFilter<T>::ConvolveRow(DVectord & kern, Image<T> * src, Image<T> * dst)
{
dst->SetSize(src->Size());
for (zuint r = 0; r < src->Rows(); r++) for (zuint c = 0; c < src->Cols(); c++)
dst->At(r, c)=ConvolveRowHelper(kern, src, r, c);
}
template<typename T>
T ImageFilter<T>::ConvolveColHelper(DVectord & kernel, Image<T> * src, zuint r, zuint c)
{
T pixel(0);
int cen = kernel.size / 2;
for (int j = 0; j < (int)kernel.size; j++)
{
int row = r + (j - cen);
if (row < 0) row = 0;
if (row >= (int)src->Rows()) row = src->Rows() - 1;
pixel += src->At(row,c)*kernel[j];
}
return PixelHelper<T>::Clamp(pixel);
}
template<typename T>
void ImageFilter<T>::ConvolveCol(DVectord & kern, Image<T> * src, Image<T> * dst)
{
dst->SetSize(src->Size());
for (zuint r = 0; r < src->Rows(); r++) for (zuint c = 0; c < src->Cols(); c++)
dst->At(r, c)=ConvolveColHelper(kern, src, r, c);
}
template<typename T>
void ImageFilter<T>::ConvolveDouble(DVectord & kern, Image<T> * src, Image<T> * dst)
{
dst->SetSize(src->Size());
Image<T> tmpImage(src->Size());
ConvolveRow(kern, src, &tmpImage);
ConvolveCol(kern, &tmpImage, dst);
}
template<typename T>
T zzz::ImageFilter<T>::Convolve2DHelper(DMatrixd & kernel, Image<T> * src, zuint r, zuint c)
{
T pixel(0);
int cenr = kernel.nrow / 2;
int cenc = kernel.ncol / 2;
for (int i=0; i<(int)kernel.nrow; i++)
{
int row=r+(i-cenr);
if (row<0) row=0;
if (row>=(int)src->Rows()) row=src->Rows()-1;
for (int j=0; j<(int)kernel.ncol; j++)
{
int col=c+(j-cenc);
if (col<0) col=0;
if (col>=(int)src->Cols()) col=src->Cols()-1;
pixel+=src->At(row,col)*kernel(i,j);
}
}
return PixelHelper<T>::Clamp(pixel);
}
template<typename T>
void zzz::ImageFilter<T>::Convolve2D(DMatrixd &kern, Image<T> *src, Image<T> *dst)
{
dst->SetSize(src->Size());
for (zuint r=0; r<src->Rows(); r++) for (zuint c=0; c<src->Cols(); c++)
dst->At(r,c)=Convolve2DHelper(kern,src,r,c);
}
//////////////////////////////////////////////////////////////////////////
//for gaussian
template<typename T>
void ImageFilter<T>::GaussBlurImage(Image<T> * src, Image<T> * dst, int kernelsize, double sigma)
{
//These two method should product the same result
//method1: do 2 times 1d convolve(row and column)
DVectord convkernel = GaussianKernel1D(kernelsize, sigma);
ImageFilter<T>::ConvolveDouble(convkernel,src,dst);
//method2: do a 2d convolve
// DMatrixd convkernel=GaussianKernel2D(kernelsize, sigma);
// ImageFilter<T>::Convolve2D(convkernel,src,dst);
}
template<typename T>
DVectord ImageFilter<T>::GaussianKernel1D(int kernelsize, double sigma)
{
GaussianFunction func(0,sigma);
if (kernelsize%2==0) kernelsize++;
DVectord kern(kernelsize);
int c = kernelsize / 2;
for (int i = 0; i < (kernelsize + 1) / 2; i++)
{
double v = func(i);
kern[c+i] = v;
kern[c-i] = v;
}
kern/=kern.Sum();
return kern;
}
template<typename T>
DMatrixd ImageFilter<T>::GaussianKernel2D(int kernelsize, double sigma)
{
Gaussian2DFunction func(Vector2d(0,0),sigma);
if (kernelsize % 2 == 0) kernelsize++;
DMatrixd mat(kernelsize,kernelsize);
int c = kernelsize / 2;
for (int i = 0; i < (kernelsize + 1) / 2; i++) for (int j = 0; j < (kernelsize + 1) / 2; j++)
{
double v = func(Vector2d(i,j));
mat(c+i,c+j) = v;
mat(c-i,c+j) = v;
mat(c+i,c-j) = v;
mat(c-i,c-j) = v;
}
mat/=mat.Sum();
return mat;
}
//////////////////////////////////////////////////////////////////////////
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageFilter.hpp
|
C++
|
gpl3
| 5,371
|
#pragma once
#include "../Utility/CacheSet.hpp"
#include "Image.hpp"
namespace zzz{
template<typename T>
class ImageCacheSet : public CacheSet<Image<T> >
{
public:
void SetData(const string &pattern, int start, int end, int cache_size)
{
pattern_=pattern;
start_=start;
end_=end;
SetSize(end-start+1,cache_size);
}
private:
Image<T>* Load(zuint i)
{
char filename[1024];
sprintf(filename,pattern_.c_str(),start_+i);
Image<T> *img=new Image<T>(filename);
return img;
}
string pattern_;
int start_,end_;
};
}
|
zzz-engine
|
zzzEngine/zImage/zImage/Image/ImageCacheSet.hpp
|
C++
|
gpl3
| 582
|
#pragma once
#include <EnvDetect.hpp>
#include <LibraryConfig.hpp>
#ifdef ZZZ_OS_WIN32
#include "zImageConfig.hpp.win32"
#endif
#ifdef ZZZ_OS_WIN64
#include "zImageConfig.hpp.win64"
#endif
#if !defined(ZZZ_LIB_DEVIL) && !defined(ZZZ_LIB_FREEIMAGE)
#define ZZZ_IMAGE_BY_SELF
#endif
#ifdef ZZZ_DYNAMIC
#ifdef ZGRAPHICS_SOURCE
#define ZIMAGE_FUNC __declspec(dllexport)
#define ZIMAGE_CLASS __declspec(dllexport)
#else
#define ZIMAGE_FUNC __declspec(dllimport)
#define ZIMAGE_CLASS __declspec(dllimport)
#endif
#else
#define ZIMAGE_FUNC
#define ZIMAGE_CLASS
#endif
|
zzz-engine
|
zzzEngine/zImage/zImage/zImageConfig.hpp
|
C++
|
gpl3
| 619
|
#include <zImageConfig.hpp>
#ifdef ZZZ_DYNAMIC
#include <zCoreAutoLink.hpp>
#include <zImageAutoLink3rdParty.hpp>
#endif
|
zzz-engine
|
zzzEngine/zImage/zImage/zImageAutoLink.cpp
|
C++
|
gpl3
| 126
|
#pragma once
#include "zImageConfig.hpp"
#include "Image/ImageHelper.hpp"
#include "Image/ImageDrawer.hpp"
#include "Image/ImageFilter.hpp"
#include "Image/ImageProcessor.hpp"
#include "Image/Image.hpp"
//#include "Image/ImageCoord.hpp"
|
zzz-engine
|
zzzEngine/zImage/zImage/zImage.hpp
|
C++
|
gpl3
| 251
|
#include <LibraryConfig.hpp>
#ifdef ZZZ_LIB_FREEIMAGE
#include "Image.hpp"
#include "ImageHelper.hpp"
#include <FreeImage.h>
namespace zzz{
//NOT WORKING YET
//DONT KNOW HOW TO CONVERT ANY IMAGE TO RGBA
FIBITMAP *LoadImage(const string &filename)
{
FIBITMAP *bitmap;
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
// check the file signature and get its format
// (the second argument is currently not used by FreeImage)
fif = FreeImage_GetFileType(filename, 0);
if(fif == FIF_UNKNOWN) {
// no signature ?
// try to guess the file format from the file extension
fif = FreeImage_GetFIFFromFilename(filename);
}
// check that the plugin has reading capabilities ...
if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
// Load the file
bitmap = FreeImage_Load(fif, filename, 0);
}
return bitmap;
}
bool SaveImage(FIBITMAP *bitmap, const string &filename)
{
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
BOOL bSuccess = FALSE;
// Try to guess the file format from the file extension
fif = FreeImage_GetFIFFromFilename(filename);
if(fif != FIF_UNKNOWN) {
// Check that the dib can be saved in this format
BOOL bCanSave;
FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(bitmap);
if(image_type == FIT_BITMAP) {
// standard bitmap type
WORD bpp = FreeImage_GetBPP(bitmap);
bCanSave = (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp));
} else {
// special bitmap type
bCanSave = FreeImage_FIFSupportsExportType(fif, image_type);
}
if(bCanSave) {
bSuccess = FreeImage_Save(fif, bitmap, filename, 0);
return bSuccess==TRUE;
}
}
return bSuccess==TRUE;
}
template<typename T>
void ConvertFrom(FIBITMAP *dib, Image<T> &dst)
{
const FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(dib);
const FREE_IMAGE_COLOR_TYPE image_color = FreeImage_GetColorType(dib);
zuint height = FreeImage_GetHeight(dib);
zuint width = FreeImage_GetWidth(dib);
zsize size_all = height * width;
switch(image_type)
{
case FIT_BITMAP:
if (image_color == FIC_RGB)
{
Image<Vector3uc> img(height, width);
memcpy(img.Data(), FreeImage_GetBits(dib), sizeof(Vector3uc)*size_all);
ConvertImage<T, Vector3uc>(img, dst);
}
else if (image_color == FIC_RGBALPHA)
{
Image<Vector4uc> img(height, width);
memcpy(img.Data(), FreeImage_GetBits(dib), sizeof(Vector3uc)*size_all);
ConvertImage<T, Vector4uc>(img, dst);
}
break;
}
}
#define IMAGE_SPECIALIZE(T) \
bool Image<T>::LoadFile(const string &filename)\
{\
FIBITMAP *image=LoadImage(filename); \
ConvertFrom(image, *this); \
FreeImage_Unload(image); \
return true; \
}\
bool Image<T>::SaveFile(const string &filename)\
{\
FIBITMAP *image=FreeImage_Allocate(\
Cols(),Rows(),sizeof(T),\
FI_RGBA_RED_MASK,FI_RGBA_GREEN_MASK,FI_RGBA_BLUE_MASK); \
memcpy(FreeImage_GetBits(image),v,sizeof(T)*size_all); \
SaveImage(image,filename); \
FreeImage_Unload(image); \
return true; \
}\
;
IMAGE_SPECIALIZE(Vector4f);
IMAGE_SPECIALIZE(Vector3f);
IMAGE_SPECIALIZE(Vector4uc);
IMAGE_SPECIALIZE(Vector3uc);
IMAGE_SPECIALIZE(float);
IMAGE_SPECIALIZE(zuchar);
#undef IMAGE_SPECIALIZE
} // namespace zzz
#endif // ZZZ_LIB_FREEIMAGE
|
zzz-engine
|
zzzEngine/zImage/zImage/ImageIO/ImageByFreeImage.cpp
|
C++
|
gpl3
| 3,418
|
#include "../zImageConfig.hpp"
#ifdef ZZZ_LIB_DEVIL
#include <Utility/StringTools.hpp>
#include <Utility/Log.hpp>
#include "../Image/Image.hpp"
#include "ILImage.hpp"
namespace zzz{
#define IMAGE_SPECIALIZE(T,format,type,channels) \
template<>\
bool Image<T>::LoadFile(const string &filename)\
{\
ILImage image; \
ZLOG(ZVERBOSE)<<"Loading image: "<<filename<<"\n"; \
if (image.Load(filename.c_str())==IL_FALSE) {ZLOG(ZERROR)<<"Load image failed: "<<filename<<endl; return false;}\
image.Convert(format,type); \
SetSize(image.Height(),image.Width()); \
memcpy(Data(),image.GetData(),sizeof(T)*size_all); \
return true; \
}\
template<>\
bool Image<T>::SaveFile(const string &filename)\
{\
ILImage image; \
image.Convert(format,type); \
image.Resize(Cols(),Rows(),1); \
memcpy(image.GetData(),Data(),sizeof(T)*size_all); \
if (channels==4) image.Convert(IL_RGBA,IL_UNSIGNED_BYTE); \
ZLOG(ZVERBOSE)<<"Saving image: "<<filename<<"\n"; \
if (image.Save(filename.c_str())==IL_FALSE) {ZLOG(ZERROR)<<"Save image failed: "<<filename<<endl; return false;}\
return true; \
}\
;
IMAGE_SPECIALIZE(Vector4uc,ZZZ_RGBA,ZZZ_UNSIGNED_BYTE,4);
IMAGE_SPECIALIZE(Vector4f,ZZZ_RGBA,ZZZ_FLOAT,4);
IMAGE_SPECIALIZE(Vector3uc,ZZZ_RGB,ZZZ_UNSIGNED_BYTE,3);
IMAGE_SPECIALIZE(Vector3f,ZZZ_RGB,ZZZ_FLOAT,3);
IMAGE_SPECIALIZE(zuchar,ZZZ_LUMINANCE,ZZZ_UNSIGNED_BYTE,1);
IMAGE_SPECIALIZE(float,ZZZ_LUMINANCE,ZZZ_FLOAT,1);
}
#endif // ZZZ_LIB_DEVIL
|
zzz-engine
|
zzzEngine/zImage/zImage/ImageIO/ImageByDevil.cpp
|
C++
|
gpl3
| 1,489
|
#include "ILImage.hpp"
#include <zImageAutoLink3rdParty.hpp>
#ifdef ZZZ_LIB_DEVIL
#include <cstring>
//
//
// ILIMAGE
//
//
ILImage::ILImage()
:Id(0)
{
iStartUp();
iGenBind();
return;
}
ILImage::ILImage(const char *FileName)
:Id(0)
{
iStartUp();
iGenBind();
ilLoadImage(FileName);
return;
}
ILImage::ILImage(const ILImage &Image)
:Id(0)
{
iStartUp();
iGenBind();
*this = Image;
return;
}
ILImage::~ILImage()
{
if (Id)
ilDeleteImages(1, &Id);
Id = 0;
return;
}
ILboolean ILImage::Load(const char *FileName)
{
iGenBind();
return ilLoadImage(FileName);
}
ILboolean ILImage::Load(const char *FileName, ILenum Type)
{
iGenBind();
return ilLoad(Type, FileName);
}
ILboolean ILImage::Save(const char *FileName, bool overwrite)
{
iGenBind();
if (overwrite) ilEnable(IL_FILE_OVERWRITE);
else ilDisable(IL_FILE_OVERWRITE);
return ilSaveImage(FileName);
}
ILboolean ILImage::Save(const char *FileName, ILenum Type, bool overwrite)
{
char filename[1024];
#ifdef WIN32
strcpy_s(filename,1024,FileName);
#else
strcpy(filename,FileName);
#endif
iGenBind();
if (overwrite) ilEnable(IL_FILE_OVERWRITE);
else ilDisable(IL_FILE_OVERWRITE);
return ilSave(Type, filename);
}
//
// ImageLib functions
//
ILboolean ILImage::ActiveImage(ILuint Number)
{
if (Id)
{
Bind();
return ilActiveImage(Number);
}
return IL_FALSE;
}
ILboolean ILImage::ActiveLayer(ILuint Number)
{
if (Id)
{
Bind();
return ilActiveLayer(Number);
}
return IL_FALSE;
}
ILboolean ILImage::ActiveMipmap(ILuint Number)
{
if (Id)
{
Bind();
return ilActiveMipmap(Number);
}
return IL_FALSE;
}
ILboolean ILImage::Clear()
{
if (Id)
{
Bind();
return ilClearImage();
}
return IL_FALSE;
}
void ILImage::ClearColour(ILclampf Red, ILclampf Green, ILclampf Blue, ILclampf Alpha)
{
ilClearColour(Red, Green, Blue, Alpha);
return;
}
ILboolean ILImage::Convert(ILenum NewFormat, ILenum NewType/*=IL_UNSIGNED_BYTE*/)
{
if (Id)
{
Bind();
return ilConvertImage(NewFormat, NewType);
}
return IL_FALSE;
}
ILboolean ILImage::Copy(ILuint Src)
{
if (Id)
{
Bind();
return ilCopyImage(Src);
}
return IL_FALSE;
}
ILboolean ILImage::Default()
{
if (Id)
{
Bind();
return ilDefaultImage();
}
return IL_FALSE;
}
ILboolean ILImage::Flip()
{
if (Id)
{
Bind();
return iluFlipImage();
}
return IL_FALSE;
}
ILboolean ILImage::SwapColours()
{
if (Id)
{
Bind();
return iluSwapColours();
}
return IL_FALSE;
}
ILboolean ILImage::Resize(ILuint Width, ILuint Height, ILuint Depth)
{
if (Id)
{
Bind();
return iluScale(Width, Height, Depth);
}
return IL_FALSE;
}
ILboolean ILImage::TexImage(ILuint Width, ILuint Height, ILuint Depth, ILubyte Bpp, ILenum Format, ILenum Type, void *Data)
{
if (Id)
{
Bind();
return ilTexImage(Width, Height, Depth, Bpp, Format, Type, Data);
}
return IL_FALSE;
}
//
// Image handling
//
void ILImage::Bind() const
{
if (Id) ilBindImage(Id);
return;
}
// Note: Behaviour may be changed!
void ILImage::Bind(ILuint Image)
{
if (Id == Image) return;
Delete(); // Should we delete it?
Id = Image;
ilBindImage(Id);
return;
}
void ILImage::Delete()
{
if (Id == 0) return;
ilDeleteImages(1, &Id);
Id = 0;
return;
}
//
// Image characteristics
//
ILuint ILImage::Width()
{
if (Id)
{
Bind();
return ilGetInteger(IL_IMAGE_WIDTH);
}
return 0;
}
ILuint ILImage::Height()
{
if (Id)
{
Bind();
return ilGetInteger(IL_IMAGE_HEIGHT);
}
return 0;
}
ILuint ILImage::Depth()
{
if (Id)
{
Bind();
return ilGetInteger(IL_IMAGE_DEPTH);
}
return 0;
}
ILubyte ILImage::Bpp()
{
if (Id)
{
Bind();
return ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
}
return 0;
}
ILubyte ILImage::Bitpp()
{
if (Id)
{
Bind();
return ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
}
return 0;
}
ILenum ILImage::Format()
{
if (Id)
{
Bind();
return ilGetInteger(IL_IMAGE_FORMAT);
}
return 0;
}
ILenum ILImage::PaletteType()
{
if (Id)
{
Bind();
return ilGetInteger(IL_PALETTE_TYPE);
}
return 0;
}
ILenum ILImage::PaletteAlphaIndex()
{
if (Id)
{
Bind();
return ilGetInteger(IL_PNG_ALPHA_INDEX);
}
return 0;
}
ILenum ILImage::Type()
{
if (Id)
{
Bind();
return ilGetInteger(IL_IMAGE_TYPE);
}
return 0;
}
ILenum ILImage::NumImages()
{
if (Id)
{
Bind();
return ilGetInteger(IL_NUM_IMAGES);
}
return 0;
}
ILenum ILImage::NumMipmaps()
{
if (Id)
{
Bind();
return ilGetInteger(IL_NUM_MIPMAPS);
}
return 0;
}
ILuint ILImage::GetId() const
{
return Id;
}
ILenum ILImage::GetOrigin(void)
{
ILinfo Info;
if (Id)
{
Bind();
iluGetImageInfo(&Info);
return Info.Origin;
}
return 0;
}
ILubyte* ILImage::GetData()
{
if (Id)
{
Bind();
return ilGetData();
}
return 0;
}
ILubyte* ILImage::GetPalette()
{
if (Id)
{
Bind();
return ilGetPalette();
}
return 0;
}
//
// Private members
//
void ILImage::iStartUp()
{
static bool ilinited=false;
if (ilinited)
return;
ilInit();
iluInit();
ilutInit();
ilEnable(IL_ORIGIN_SET);
ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
ilinited=true;
return;
}
void ILImage::iGenBind()
{
if (Id == 0) ilGenImages(1, &Id);
ilBindImage(Id);
return;
}
//
// Operators
//
ILImage& ILImage::operator = (ILuint Image)
{
if (Id == 0) Id = Image;
else
{
Bind();
ilCopyImage(Image);
}
return *this;
}
ILImage& ILImage::operator = (const ILImage &Image)
{
if (Id == 0) Id = Image.GetId();
else
{
Bind();
ilCopyImage(Image.GetId());
}
return *this;
}
//
//
// ILFILTERS
//
//
ILboolean ILFilters::Alienify(ILImage &Image)
{
Image.Bind();
return iluAlienify();
}
ILboolean ILFilters::BlurAvg(ILImage &Image, ILuint Iter)
{
Image.Bind();
return iluBlurAvg(Iter);
}
ILboolean ILFilters::BlurGaussian(ILImage &Image, ILuint Iter)
{
Image.Bind();
return iluBlurGaussian(Iter);
}
ILboolean ILFilters::Contrast(ILImage &Image, ILfloat Contrast)
{
Image.Bind();
return iluContrast(Contrast);
}
ILboolean ILFilters::EdgeDetectE(ILImage &Image)
{
Image.Bind();
return iluEdgeDetectP();
}
ILboolean ILFilters::EdgeDetectP(ILImage &Image)
{
Image.Bind();
return iluEdgeDetectP();
}
ILboolean ILFilters::EdgeDetectS(ILImage &Image)
{
Image.Bind();
return iluEdgeDetectS();
}
ILboolean ILFilters::Emboss(ILImage &Image)
{
Image.Bind();
return iluEmboss();
}
ILboolean ILFilters::Gamma(ILImage &Image, ILfloat Gamma)
{
Image.Bind();
return iluGammaCorrect(Gamma);
}
ILboolean ILFilters::Negative(ILImage &Image)
{
Image.Bind();
return iluNegative();
}
ILboolean ILFilters::Noisify(ILImage &Image, ILubyte Factor)
{
Image.Bind();
return iluNoisify(Factor);
}
ILboolean ILFilters::Pixelize(ILImage &Image, ILuint PixSize)
{
Image.Bind();
return iluPixelize(PixSize);
}
ILboolean ILFilters::Saturate(ILImage &Image, ILfloat Saturation)
{
Image.Bind();
return iluSaturate1f(Saturation);
}
ILboolean ILFilters::Saturate(ILImage &Image, ILfloat r, ILfloat g, ILfloat b, ILfloat Saturation)
{
Image.Bind();
return iluSaturate4f(r, g, b, Saturation);
}
ILboolean ILFilters::ScaleColours(ILImage &Image, ILfloat r, ILfloat g, ILfloat b)
{
Image.Bind();
return iluScaleColours(r, g, b);
}
ILboolean ILFilters::Sharpen(ILImage &Image, ILfloat Factor, ILuint Iter)
{
Image.Bind();
return iluSharpen(Factor, Iter);
}
//
//
// ILOPENGL
//
//
//void ILOpenGL::Init()
//{
// ilutRenderer(ILUT_OPENGL);
// return;
//}
//
//GLuint ILOpenGL::BindTex(ILImage &Image)
//{
// Image.Bind();
// return ilutGLBindTexImage();
//}
//
//ILboolean ILOpenGL::Upload(ILImage &Image, ILuint Level)
//{
// Image.Bind();
// return ilutGLTexImage(Level);
//}
//
//GLuint ILOpenGL::Mipmap(ILImage &Image)
//{
// Image.Bind();
// return ilutGLBuildMipmaps();
//}
//
//ILboolean ILOpenGL::Screen()
//{
// return ilutGLScreen();
//}
//
//ILboolean ILOpenGL::Screenie()
//{
// return ilutGLScreenie();
//}
//
//void ILOpenGL::DrawImage(ILImage &image)
//{
// glDrawPixels(image.Width(),image.Height(),image.Format(),image.Type(),image.GetData());
//}
//
//
// ILVALIDATE
//
//
ILboolean ILValidate::Valid(ILenum Type, char *FileName)
{
return ilIsValid(Type, FileName);
}
ILboolean ILValidate::Valid(ILenum Type, FILE *File)
{
return ilIsValidF(Type, File);
}
ILboolean ILValidate::Valid(ILenum Type, void *Lump, ILuint Size)
{
return ilIsValidL(Type, Lump, Size);
}
//
//
// ILSTATE
//
//
ILboolean ILState::Disable(ILenum State)
{
return ilDisable(State);
}
ILboolean ILState::Enable(ILenum State)
{
return ilEnable(State);
}
void ILState::Get(ILenum Mode, ILboolean &Param)
{
ilGetBooleanv(Mode, &Param);
return;
}
void ILState::Get(ILenum Mode, ILint &Param)
{
ilGetIntegerv(Mode, &Param);
return;
}
ILboolean ILState::GetBool(ILenum Mode)
{
return ilGetBoolean(Mode);
}
ILint ILState::GetInt(ILenum Mode)
{
return ilGetInteger(Mode);
}
const char *ILState::GetString(ILenum StringName)
{
return ilGetString(StringName);
}
ILboolean ILState::IsDisabled(ILenum Mode)
{
return ilIsDisabled(Mode);
}
ILboolean ILState::IsEnabled(ILenum Mode)
{
return ilIsEnabled(Mode);
}
ILboolean ILState::Origin(ILenum Mode)
{
return ilOriginFunc(Mode);
}
void ILState::Pop()
{
ilPopAttrib();
return;
}
void ILState::Push(ILuint Bits = IL_ALL_ATTRIB_BITS)
{
ilPushAttrib(Bits);
return;
}
//
//
// ILERROR
//
//
void ILError::Check(void (*Callback)(const char *))
{
static ILenum Error;
while ((Error = ilGetError()) != IL_NO_ERROR) Callback(iluErrorString(Error));
return;
}
void ILError::Check(void (*Callback)(ILenum))
{
static ILenum Error;
while ((Error = ilGetError()) != IL_NO_ERROR) Callback(Error);
return;
}
ILenum ILError::Get()
{
return ilGetError();
}
const char *ILError::String()
{
return iluErrorString(ilGetError());
}
const char *ILError::String(ILenum Error)
{
return iluErrorString(Error);
}
#endif // ZZZ_LIB_DEVIL
|
zzz-engine
|
zzzEngine/zImage/zImage/ImageIO/ILImage.cpp
|
C++
|
gpl3
| 10,857
|
#include "../zImageConfig.hpp"
#ifdef ZZZ_IMAGE_BY_SELF
#include <Utility/StringTools.hpp>
#include <Utility/Log.hpp>
#include "../Image/Image.hpp"
namespace zzz{
#define UNIMPLEMENT(T) \
template<>\
bool Image<T>::LoadFile(const string &filename)\
{\
ZLOGF<<"Load image from "<<filename<<" is not implemented!\n"; \
return false; \
}\
template<>\
bool Image<T>::SaveFile(const string &filename)\
{\
ZLOGF<<"Save image to "<<filename<<" is not implemented!\n"; \
return false; \
}
UNIMPLEMENT(Vector4uc);
UNIMPLEMENT(Vector4f);
UNIMPLEMENT(Vector3uc);
UNIMPLEMENT(Vector3f);
UNIMPLEMENT(zuchar);
UNIMPLEMENT(float);
#undef UNIMPLEMENT
}
#endif // ZZZ_IMAGE_BY_SELF
|
zzz-engine
|
zzzEngine/zImage/zImage/ImageIO/ImageBySelf.cpp
|
C++
|
gpl3
| 711
|
#pragma once
#include <common.hpp>
namespace zzz{
struct bitmap_file_header
{
zuint16 type;
zuint32 size;
zuint16 reserved1;
zuint16 reserved2;
zuint32 off_bits;
};
struct bitmap_information_header
{
zuint32 size;
zuint32 width;
zuint32 height;
zuint16 planes;
zuint16 bit_count;
zuint32 compression;
zuint32 size_image;
zuint32 x_pels_per_meter;
zuint32 y_pels_per_meter;
zuint32 clr_used;
zuint32 clr_important;
};
inline void read_bih(std::ifstream& stream, bitmap_information_header& bih);
inline void read_bfh(std::ifstream& stream, bitmap_file_header& bfh);
inline void write_bih(std::ofstream& stream, const bitmap_information_header& bih);
inline void write_bfh(std::ofstream& stream, const bitmap_file_header& bfh);
class bitmap_image
{
public:
enum channel_mode {
rgb_mode = 0,
bgr_mode = 1
};
enum color_plane {
blue_plane = 0,
green_plane = 1,
red_plane = 2
};
bitmap_image()
: file_name_(""),
data_(0),
bytes_per_pixel_(3),
length_(0),
width_(0),
height_(0),
row_increment_(0),
channel_mode_(bgr_mode)
{
}
bitmap_image(const std::string& _filename)
: file_name_(_filename),
data_(0),
bytes_per_pixel_(0),
length_(0),
width_(0),
height_(0),
row_increment_(0),
channel_mode_(bgr_mode)
{
load_bitmap();
}
bitmap_image(const zuint32 width, const zuint32 height)
: file_name_(""),
data_(0),
bytes_per_pixel_(3),
length_(0),
width_(width),
height_(height),
row_increment_(0),
channel_mode_(bgr_mode)
{
create_bitmap();
}
bitmap_image(const bitmap_image& image)
: file_name_(image.file_name_),
data_(0),
bytes_per_pixel_(3),
width_(image.width_),
height_(image.height_),
row_increment_(0),
channel_mode_(bgr_mode)
{
create_bitmap();
std::copy(image.data_, image.data_ + image.length_, data_);
}
~bitmap_image()
{
delete [] data_;
}
void save_image(const std::string& file_name)
{
std::ofstream stream(file_name.c_str(),std::ios::binary);
if(!stream)
{
std::cout << "bitmap_image::save_image(): Error - Could not open file " << file_name << " for writing!" << std::endl;
return;
}
bitmap_file_header bfh;
bitmap_information_header bih;
bih.width = width_;
bih.height = height_;
bih.bit_count = static_cast<zuint16>(bytes_per_pixel_ << 3);
bih.clr_important = 0;
bih.clr_used = 0;
bih.compression = 0;
bih.planes = 1;
bih.size = 40;
bih.x_pels_per_meter = 0;
bih.y_pels_per_meter = 0;
bih.size_image = (((bih.width * bytes_per_pixel_) + 3) & 0xFFFC) * bih.height;
bfh.type = 19778;
bfh.size = 55 + bih.size_image;
bfh.reserved1 = 0;
bfh.reserved2 = 0;
bfh.off_bits = bih.struct_size() + bfh.struct_size();
write_bfh(stream,bfh);
write_bih(stream,bih);
zuint32 padding = (4 - ((3 * width_) % 4)) % 4;
char padding_data[4] = {0x0,0x0,0x0,0x0};
for (zuint32 i = 0; i < height_; ++i)
{
unsigned char* data_ptr = data_ + (row_increment_ * (height_ - i - 1));
stream.write(reinterpret_cast<char*>(data_ptr),sizeof(unsigned char) * bytes_per_pixel_ * width_);
stream.write(padding_data,padding);
}
stream.close();
}
void create_bitmap()
{
length_ = width_ * height_ * bytes_per_pixel_;
row_increment_ = width_ * bytes_per_pixel_;
if (0 != data_) {
delete[] data_;
}
data_ = new unsigned char[length_];
valid_ = true;
}
void load_bitmap()
{
std::ifstream stream(file_name_.c_str(),std::ios::binary);
if (!stream) {
std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - file " << file_name_ << " not found!" << std::endl;
return;
}
bitmap_file_header bfh;
bitmap_information_header bih;
read_bfh(stream,bfh);
read_bih(stream,bih);
if(bfh.type != 19778)
{
stream.close();
std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - Invalid type value " << bfh.type << " expected 19778." << std::endl;
return;
}
if(bih.bit_count != 24)
{
stream.close();
std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - Invalid bit depth " << bih.bit_count << " expected 24." << std::endl;
return;
}
height_ = bih.height;
width_ = bih.width;
bytes_per_pixel_ = bih.bit_count >> 3;
zuint32 padding = (4 - ((3 * width_) % 4)) % 4;
char padding_data[4] = {0,0,0,0};
create_bitmap();
for (zuint32 i = 0; i < height_; ++i)
{
unsigned char* data_ptr = row(height_ - i - 1); // read in inverted row order
stream.read(reinterpret_cast<char*>(data_ptr),sizeof(char) * bytes_per_pixel_ * width_);
stream.read(padding_data,padding);
}
valid_ = true;
}
bool valid_;
std::string file_name_;
unsigned char* data_;
zuint32 bytes_per_pixel_;
zuint32 length_;
zuint32 width_;
zuint32 height_;
zuint32 row_increment_;
channel_mode channel_mode_;
};
/* Utility Routines */
inline bool big_endian()
{
zuint32 v = 0x01;
return (1 != reinterpret_cast<char*>(&v)[0]);
}
inline zuint16 flip(const zuint16& v)
{
return ((v >> 8) | (v << 8));
}
inline zuint32 flip(const zuint32& v)
{
return (((v & 0xFF000000) >> 0x18) | ((v & 0x000000FF) << 0x18) |
((v & 0x00FF0000) >> 0x08) | ((v & 0x0000FF00) << 0x08));
}
template<typename T>
inline void read_from_stream(std::ifstream& stream,T& t)
{
stream.read(reinterpret_cast<char*>(&t),sizeof(T));
}
template<typename T> inline void write_to_stream(std::ofstream& stream,const T& t)
{
stream.write(reinterpret_cast<const char*>(&t),sizeof(T));
}
inline void read_bfh(std::ifstream& stream, bitmap_file_header& bfh)
{
read_from_stream(stream,bfh.type);
read_from_stream(stream,bfh.size);
read_from_stream(stream,bfh.reserved1);
read_from_stream(stream,bfh.reserved2);
read_from_stream(stream,bfh.off_bits);
if(big_endian())
{
flip(bfh.type);
flip(bfh.size);
flip(bfh.reserved1);
flip(bfh.reserved2);
flip(bfh.off_bits);
}
}
inline void write_bfh(std::ofstream& stream, const bitmap_file_header& bfh)
{
if(big_endian())
{
flip(bfh.type);
flip(bfh.size);
flip(bfh.reserved1);
flip(bfh.reserved2);
flip(bfh.off_bits);
}
write_to_stream(stream,bfh.type);
write_to_stream(stream,bfh.size);
write_to_stream(stream,bfh.reserved1);
write_to_stream(stream,bfh.reserved2);
write_to_stream(stream,bfh.off_bits);
}
inline void read_bih(std::ifstream& stream,bitmap_information_header& bih)
{
read_from_stream(stream,bih.size);
read_from_stream(stream,bih.width);
read_from_stream(stream,bih.height);
read_from_stream(stream,bih.planes);
read_from_stream(stream,bih.bit_count);
read_from_stream(stream,bih.compression);
read_from_stream(stream,bih.size_image);
read_from_stream(stream,bih.x_pels_per_meter);
read_from_stream(stream,bih.y_pels_per_meter);
read_from_stream(stream,bih.clr_used);
read_from_stream(stream,bih.clr_important);
if(big_endian())
{
flip(bih.size);
flip(bih.width);
flip(bih.height);
flip(bih.planes);
flip(bih.bit_count);
flip(bih.compression);
flip(bih.size_image);
flip(bih.x_pels_per_meter);
flip(bih.y_pels_per_meter);
flip(bih.clr_used);
flip(bih.clr_important);
}
}
inline void write_bih(std::ofstream& stream, const bitmap_information_header& bih)
{
if(big_endian())
{
flip(bih.size);
flip(bih.width);
flip(bih.height);
flip(bih.planes);
flip(bih.bit_count);
flip(bih.compression);
flip(bih.size_image);
flip(bih.x_pels_per_meter);
flip(bih.y_pels_per_meter);
flip(bih.clr_used);
flip(bih.clr_important);
}
write_to_stream(stream,bih.size);
write_to_stream(stream,bih.width);
write_to_stream(stream,bih.height);
write_to_stream(stream,bih.planes);
write_to_stream(stream,bih.bit_count);
write_to_stream(stream,bih.compression);
write_to_stream(stream,bih.size_image);
write_to_stream(stream,bih.x_pels_per_meter);
write_to_stream(stream,bih.y_pels_per_meter);
write_to_stream(stream,bih.clr_used);
write_to_stream(stream,bih.clr_important);
}
} // namespace zzz
|
zzz-engine
|
zzzEngine/zImage/zImage/ImageIO/BmpIO.hpp
|
C++
|
gpl3
| 8,931
|
#pragma once
#include <LibraryConfig.hpp>
#ifdef ZZZ_LIB_DEVIL
#include <IL/ilut.h> // Probably only have to #include this one
class ILImage
{
public:
ILImage();
ILImage(const char *);
ILImage(const ILImage &);
virtual ~ILImage();
ILboolean Load(const char *);
ILboolean Load(const char *, ILenum);
ILboolean Save(const char *, bool overwrite=true);
ILboolean Save(const char *, ILenum, bool overwrite=true);
// ImageLib functions
ILboolean ActiveImage(ILuint);
ILboolean ActiveLayer(ILuint);
ILboolean ActiveMipmap(ILuint);
ILboolean Clear(void);
void ClearColour(ILclampf, ILclampf, ILclampf, ILclampf);
ILboolean Convert(ILenum NewFormat, ILenum NewType=IL_UNSIGNED_BYTE);
ILboolean Copy(ILuint);
ILboolean Default(void);
ILboolean Flip(void);
ILboolean SwapColours(void);
ILboolean Resize(ILuint, ILuint, ILuint);
ILboolean TexImage(ILuint, ILuint, ILuint, ILubyte, ILenum, ILenum, void*);
// Image handling
void Bind(void) const;
void Bind(ILuint);
void Close(void) { this->Delete(); }
void Delete(void);
void iGenBind();
ILenum PaletteAlphaIndex();
// Image characteristics
ILuint Width(void);
ILuint Height(void);
ILuint Depth(void);
ILubyte Bpp(void);
ILubyte Bitpp(void);
ILenum PaletteType(void);
ILenum Format(void);
ILenum Type(void);
ILuint NumImages(void);
ILuint NumMipmaps(void);
ILuint GetId(void) const;
ILenum GetOrigin(void);
ILubyte *GetData(void);
ILubyte *GetPalette(void);
// Rendering
ILuint BindImage(void);
ILuint BindImage(ILenum);
// Operators
ILImage& operator = (ILuint);
ILImage& operator = (const ILImage &);
protected:
ILuint Id;
private:
static void iStartUp();
};
class ILFilters
{
public:
static ILboolean Alienify(ILImage &);
static ILboolean BlurAvg(ILImage &, ILuint Iter);
static ILboolean BlurGaussian(ILImage &, ILuint Iter);
static ILboolean Contrast(ILImage &, ILfloat Contrast);
static ILboolean EdgeDetectE(ILImage &);
static ILboolean EdgeDetectP(ILImage &);
static ILboolean EdgeDetectS(ILImage &);
static ILboolean Emboss(ILImage &);
static ILboolean Gamma(ILImage &, ILfloat Gamma);
static ILboolean Negative(ILImage &);
static ILboolean Noisify(ILImage &, ILubyte Factor);
static ILboolean Pixelize(ILImage &, ILuint PixSize);
static ILboolean Saturate(ILImage &, ILfloat Saturation);
static ILboolean Saturate(ILImage &, ILfloat r, ILfloat g, ILfloat b, ILfloat Saturation);
static ILboolean ScaleColours(ILImage &, ILfloat r, ILfloat g, ILfloat b);
static ILboolean Sharpen(ILImage &, ILfloat Factor, ILuint Iter);
};
//class ILOpenGL
//{
//public:
// static void Init(void);
// static GLuint BindTex(ILImage &);
// static ILboolean Upload(ILImage &, ILuint);
// static GLuint Mipmap(ILImage &);
// static ILboolean Screen(void);
// static ILboolean Screenie(void);
// static void DrawImage(ILImage &);
//};
class ILValidate
{
public:
static ILboolean Valid(ILenum, char *);
static ILboolean Valid(ILenum, FILE *);
static ILboolean Valid(ILenum, void *, ILuint);
};
class ILState
{
public:
static ILboolean Disable(ILenum);
static ILboolean Enable(ILenum);
static void Get(ILenum, ILboolean &);
static void Get(ILenum, ILint &);
static ILboolean GetBool(ILenum);
static ILint GetInt(ILenum);
static const char *GetString(ILenum);
static ILboolean IsDisabled(ILenum);
static ILboolean IsEnabled(ILenum);
static ILboolean Origin(ILenum);
static void Pop(void);
static void Push(ILuint);
};
class ILError
{
public:
static void Check(void (*Callback)(const char *));
static void Check(void (*Callback)(ILenum));
static ILenum Get(void);
static const char *String(void);
static const char *String(ILenum);
};
#endif // ZZZ_LIB_DEVIL
|
zzz-engine
|
zzzEngine/zImage/zImage/ImageIO/ILImage.hpp
|
C++
|
gpl3
| 4,115
|
#include <zCore.hpp>
#include <zCoreAutolink.hpp>
#include <zImageAutolink.hpp>
using namespace zzz;
ZFLAGS_SWITCH2(print_mode, "Output all 256 ascii letters", 'p');
ZFLAGS_STRING2(input, "", "Input font map image file name", 'i');
ZFLAGS_STRING2(output, "BMPFontData.hpp", "Output c++ code file name", 'o');
ZFLAGS_INT2(height, 12, "font height in pixels", 'h');
ZFLAGS_INT2(width, 8, "font width in pixels", 'w');
ZFLAGS_INT2(row, 16, "font map row number", 'r');
ZFLAGS_INT2(col, 16, "font map column number", 'c');
int main(int argc, char *argv[])
{
ZCMDPARSE(argv[0]);
if (FLAGS_print_mode) {
for (int i=0; i<16; i++)
{
for (int j=0; j<16; j++)
{
char x(i*16+j);
if (x=='\n') x=' ';
zout<<x;
}
zout<<endl;
}
return 0;
}
ZCHECK_FALSE(FLAGS_input.empty())
<<"Need input file name!";
Imageuc img(FLAGS_input.c_str());
const int height=FLAGS_height;
const int width=FLAGS_width;
const int row=FLAGS_row;
const int col=FLAGS_col;
ZCHECK(img.Cols()==width*col && img.Rows()==height*row)
<<"font size or font arrangement is not correct:"<<ZVAR(height)<<ZVAR(width)<<ZVAR(row)<<ZVAR(col);
ofstream fo(FLAGS_output.c_str());
fo<<"#pragma warning(disable:4309)\n";
fo<<"const int fontwidth="<<width<<",fontheight="<<height<<"; \n";
fo<<"const char fontmap[]={";
for (int fr=0;fr<height;fr++) for (int r=row-1; r>=0; r--)
{
for (int fc=0;fc<width*col;fc++)
{
fo<<int(img.At(r*height+fr,fc));
if (fr!=height-1 || r!=row-1 || fc!=width*col) //last one
fo<<',';
}
fo<<"\\\n";
}
fo<<"}; \n";
fo.close();
}
|
zzz-engine
|
Tools/BMPFontMaker/BMPFontMaker.cpp
|
C++
|
gpl3
| 1,700
|
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(zzzCode)
SET(EXECUTABLE_OUTPUT_PATH "${zzzCode_BINARY_DIR}/bin" CACHE INTERNAL "")
SET(LIBRARY_OUTPUT_PATH "${zzzCode_BINARY_DIR}/lib" CACHE INTERNAL "")
LINK_DIRECTORIES("${zzzCode_BINARY_DIR}/lib")
SET(LIB_MODE Minimal Full)
SET(CMAKE_BUILD_TYPE Debug)
IF(("${CMAKE_BUILD_TYPE}" EQUAL "Release"))
SET(DEBUG_MODE 0)
ELSE()
SET(DEBUG_MODE 1)
ENDIF()
IF( "${CMAKE_SIZEOF_VOID_P}" EQUAL "8" )
SET(BIT_MODE 64)
ELSEIF( "${CMAKE_SIZEOF_VOID_P}" EQUAL "4" )
SET(BIT_MODE 32)
ELSE()
SET(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}_Unknown")
ENDIF()
INCLUDE_DIRECTORIES(zzzEngine/zCore/zCore)
INCLUDE_DIRECTORIES(zzzEngine/zGraphics/zGraphics)
INCLUDE_DIRECTORIES(zzzEngine/zVision/zVision)
INCLUDE_DIRECTORIES(zzzEngine/zMatrix/zMatrix)
INCLUDE_DIRECTORIES(zzzEngine/zImage/zImage)
INCLUDE_DIRECTORIES(zzzEngine/zVisualization/zVisualization)
INCLUDE_DIRECTORIES(zzzEngine/zAI/zAI)
INCLUDE_DIRECTORIES(3rdParty/Freeglut/include)
INCLUDE_DIRECTORIES(3rdParty/Glew)
INCLUDE_DIRECTORIES(3rdParty/UnitTest++/src)
ADD_DEFINITIONS(-DZZZ_NO_PRAGMA_LIB)
IF((WIN32) AND (${LIB_MODE} EQUAL FULL) AND (${CMAKE_CXX_COMPILER} MATCHES ".*/cl.exe"))
SET(COMMON_INCLUDE_PATH "d:/library/include")
SET(COMMON_LIB_PATH "d:/library/lib")
SET(COMMON_64LIB_PATH "d:/library/X64_lib")
SET(BOOST_INCLUDE_PATH "d:/boost/boost_1_44_0")
SET(BOOST_LIB_PATH "d:/boost/boost_1_44_0/stage/lib")
SET(BOOST_64LIB_PATH "d:/boost/boost_1_44_0/stage/lib64")
SET(QT_INCLUDE_PATH "d:/Qt/4.7.3/include")
SET(QT_LIB_PATH "d:/Qt/4.7.3/lib")
SET(QT_64LIB_PATH "d:/Qt/4.7.3/lib64")
INCLUDE_DIRECTORIES(${COMMON_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${BOOST_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${QT_INCLUDE_PATH})
IF (${BIT_MODE} EQUAL 32)
LINK_DIRECTORIES(${COMMON_LIB_PATH})
LINK_DIRECTORIES(${BOOST_LIB_PATH})
LINK_DIRECTORIES(${QT_LIB_PATH})
ELSE()
LINK_DIRECTORIES(${COMMON_64LIB_PATH})
LINK_DIRECTORIES(${BOOST_64LIB_PATH})
LINK_DIRECTORIES(${QT_64LIB_PATH})
ENDIF()
ENDIF()
IF(UNIX)
ENDIF(UNIX)
MESSAGE("CMAKE_CXX_COMPILER: ${CMAKE_CXX_COMPILER}")
MESSAGE("COMMON_INCLUDE_PATH: ${COMMON_INCLUDE_PATH}")
MESSAGE("BOOST_INCLUDE_PATH: ${BOOST_INCLUDE_PATH}")
MESSAGE("QT_INCLUDE_PATH: ${QT_INCLUDE_PATH}")
ADD_SUBDIRECTORY(3rdParty)
ADD_SUBDIRECTORY(zzzEngine)
ADD_SUBDIRECTORY(EngineTest/MathTest)
|
zzz-engine
|
CMakeLists.txt
|
CMake
|
gpl3
| 2,408
|
cmake -G"NMake Makefiles" -DCMAKE_BUILD_TYPE=Release ..
|
zzz-engine
|
cmakegen.bat
|
Batchfile
|
gpl3
| 57
|
package com.nopackname.response;
public class API_MY_GEN_MOD_REINIT_RESPONSE extends API_SUB_RESPONSE {
private int ct;
private int it;
private int wt;
private int exp;
private int money;
public int getCt() {
return ct;
}
public void setCt(int ct) {
this.ct = ct;
}
public int getIt() {
return it;
}
public void setIt(int it) {
this.it = it;
}
public int getWt() {
return wt;
}
public void setWt(int wt) {
this.wt = wt;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_MY_GEN_MOD_REINIT_RESPONSE.java
|
Java
|
asf20
| 846
|
package com.nopackname.response;
public class API_MY_GEN_MOD_WASHPRICE_RESPONSE extends API_SUB_RESPONSE {
int exp;
int money;
int money2;
int p;
int pmax;
int pc;
int pi;
int pw;
int pcmax;
int pimax;
int pwmax;
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public int getMoney2() {
return money2;
}
public void setMoney2(int money2) {
this.money2 = money2;
}
public int getP() {
return p;
}
public void setP(int p) {
this.p = p;
}
public int getPmax() {
return pmax;
}
public void setPmax(int pmax) {
this.pmax = pmax;
}
public int getPc() {
return pc;
}
public void setPc(int pc) {
this.pc = pc;
}
public int getPi() {
return pi;
}
public void setPi(int pi) {
this.pi = pi;
}
public int getPw() {
return pw;
}
public void setPw(int pw) {
this.pw = pw;
}
public int getPcmax() {
return pcmax;
}
public void setPcmax(int pcmax) {
this.pcmax = pcmax;
}
public int getPimax() {
return pimax;
}
public void setPimax(int pimax) {
this.pimax = pimax;
}
public int getPwmax() {
return pwmax;
}
public void setPwmax(int pwmax) {
this.pwmax = pwmax;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_MY_GEN_MOD_WASHPRICE_RESPONSE.java
|
Java
|
asf20
| 1,703
|
package com.nopackname.response;
public class API_BASE_RESPONSE {
private int code;
private API_SUB_RESPONSE ret;// json
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public API_SUB_RESPONSE getRet() {
return ret;
}
public void setRet(API_SUB_RESPONSE ret) {
this.ret = ret;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_BASE_RESPONSE.java
|
Java
|
asf20
| 424
|
package com.nopackname.response;
import java.util.ArrayList;
import java.util.List;
import com.nopackname.bean.City;
import com.nopackname.tools.JSONUtil;
public class API_GET_USERINFO2_RESPONSE {
private int code;
private API_GET_USERINFO2_RET ret;// json
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public API_GET_USERINFO2_RET getRet() {
return ret;
}
public void setRet(API_GET_USERINFO2_RET ret) {
this.ret = ret;
}
public static void main(String[] args) {
API_GET_USERINFO2_RESPONSE resp = new API_GET_USERINFO2_RESPONSE();
resp.setCode(0);
API_GET_USERINFO2_RET ret = new API_GET_USERINFO2_RET();
List<Object> user = new ArrayList<Object>();
user.add(90972);// id
user.add("小凡");// player name
user.add(3);// type
user.add(132);// level
user.add(5161);// ???
user.add("鱼和熊");// union name
user.add(38);// ???
user.add(1);// ???
user.add(0);// ???
List<Object> subAttr = new ArrayList<Object>();
subAttr.add(0); // ???
subAttr.add(0); // ???
subAttr.add(""); // ???
user.add(subAttr);
user.add(0);// ???
user.add(0);// ???
ret.setUser(user);
List<City> city = new ArrayList<City>();
City oneCity = new City();
oneCity.setId(90921);
oneCity.setName("巨鹿城");
oneCity.setIn(3);
city.add(oneCity);
ret.setCity(city);
resp.setRet(ret);
System.out.println(JSONUtil.generateJSON(resp));
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_GET_USERINFO2_RESPONSE.java
|
Java
|
asf20
| 1,740
|
package com.nopackname.response;
import java.util.ArrayList;
import java.util.List;
import com.nopackname.bean.Attribute;
import com.nopackname.bean.Good;
import com.nopackname.bean.Item;
import com.nopackname.tools.JSONUtil;
public class API_GOODS_LIST_RESPONSE {
private List<Good> item;
private int max;
private String num;
private int size;
public List<Good> getItem() {
return item;
}
public void setItem(List<Good> item) {
this.item = item;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public static void main(String[] args) {
API_GOODS_LIST_RESPONSE resp = new API_GOODS_LIST_RESPONSE();
List<Good> item = new ArrayList<Good>();
Good good = new Good();
Item it = new Item();
it.setId(999999);
it.setSid(122);
it.setUp(0);
Attribute attr = new Attribute();
attr.setXed(0);
attr.setXea(0);
attr.setExd(0);
attr.setExa(0);
attr.setEnd(0);
attr.setEna(124);
attr.setC(0);
attr.setCourage(0);
attr.setWisdom(0);
attr.setInstinct(0);
attr.setR_power(0);
it.setAttr(attr);
good.setItem(it);
good.setSale(4000);
good.setNum(1);
good.setUse(0);
good.setJewel_effect(null);
item.add(good);
resp.setItem(item);
resp.setMax(6);
resp.setNum("6");
resp.setSize(6);
System.out.println(JSONUtil.generateJSON(resp));
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_GOODS_LIST_RESPONSE.java
|
Java
|
asf20
| 1,926
|
package com.nopackname.response;
public class API_GOODS_SALE_RESPONSE {
private int credit;
public int getCredit() {
return credit;
}
public void setCredit(int credit) {
this.credit = credit;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_GOODS_SALE_RESPONSE.java
|
Java
|
asf20
| 248
|
package com.nopackname.response;
import java.util.ArrayList;
import java.util.List;
import com.nopackname.tools.JSONUtil;
public class API_UNION_MEMBER_RET {
private List<Object> list;
private List<Integer> score;
private int max;
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public List<Integer> getScore() {
return score;
}
public void setScore(List<Integer> score) {
this.score = score;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public static void main(String[] args) {
API_UNION_MEMBER_RET resp = new API_UNION_MEMBER_RET();
resp.setMax(5);
List<Object> list = new ArrayList<Object>();
List<Object> member = new ArrayList<Object>();
member.add(90972);// id
member.add("小凡");// player name
member.add(3);// type
member.add(132);// level
member.add(5161);// union id
member.add("鱼和熊");// union name
member.add(38);// ???
member.add(1);// ???
member.add(0);// ???
List<Object> subAttr = new ArrayList<Object>();
subAttr.add(0); // ???
subAttr.add(0); // ???
subAttr.add(""); // ???
member.add(subAttr);
member.add(0);// ???
member.add(0);// ???
list.add(member);
resp.setList(list);
List<Integer> score = new ArrayList<Integer>();
score.add(98290569);
resp.setScore(score);
System.out.println(JSONUtil.generateJSON(resp));
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_UNION_MEMBER_RET.java
|
Java
|
asf20
| 1,744
|
package com.nopackname.response;
public class API_MY_GEN_MOD_REINIT_BASE_RESPONSE {
private int code;
private API_MY_GEN_MOD_REINIT_RESPONSE ret;// json
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public API_MY_GEN_MOD_REINIT_RESPONSE getRet() {
return ret;
}
public void setRet(API_MY_GEN_MOD_REINIT_RESPONSE ret) {
this.ret = ret;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_MY_GEN_MOD_REINIT_BASE_RESPONSE.java
|
Java
|
asf20
| 484
|
package com.nopackname.response;
import java.util.List;
import com.nopackname.bean.Event;
import com.nopackname.bean.Gift;
import com.nopackname.bean.Status;
import com.nopackname.bean.User;
public class API_GET_USERINFO_RESPONSE extends API_SUB_RESPONSE {
private User user;
private List<Gift> gifts;
private List<Event> events;
private Status status;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Gift> getGifts() {
return gifts;
}
public void setGifts(List<Gift> gifts) {
this.gifts = gifts;
}
public List<Event> getEvents() {
return events;
}
public void setEvents(List<Event> events) {
this.events = events;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_GET_USERINFO_RESPONSE.java
|
Java
|
asf20
| 985
|
package com.nopackname.response;
import java.util.ArrayList;
import java.util.List;
import com.nopackname.tools.JSONUtil;
public class API_UNION_MEMBER_RESPONSE {
private int code;
private API_UNION_MEMBER_RET ret;// json
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public API_UNION_MEMBER_RET getRet() {
return ret;
}
public void setRet(API_UNION_MEMBER_RET ret) {
this.ret = ret;
}
public static void main(String[] args) {
API_UNION_MEMBER_RESPONSE resp = new API_UNION_MEMBER_RESPONSE();
resp.setCode(0);
API_UNION_MEMBER_RET ret = new API_UNION_MEMBER_RET();
ret.setMax(5);
List<Object> list = new ArrayList<Object>();
List<Object> member = new ArrayList<Object>();
member.add(90972);// id
member.add("小凡");// player name
member.add(3);// type
member.add(132);// level
member.add(5161);// ???
member.add("鱼和熊");// union name
member.add(38);// ???
member.add(1);// ???
member.add(0);// ???
List<Object> subAttr = new ArrayList<Object>();
subAttr.add(0); // ???
subAttr.add(0); // ???
subAttr.add(""); // ???
member.add(subAttr);
member.add(0);// ???
member.add(0);// ???
list.add(member);
ret.setList(list);
List<Integer> score = new ArrayList<Integer>();
score.add(98290569);
ret.setScore(score);
resp.setRet(ret);
System.out.println(JSONUtil.generateJSON(resp));
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_UNION_MEMBER_RESPONSE.java
|
Java
|
asf20
| 1,707
|
package com.nopackname.response;
public class API_MY_GEN_MOD_REJECT_RESPONSE extends API_SUB_RESPONSE {
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_MY_GEN_MOD_REJECT_RESPONSE.java
|
Java
|
asf20
| 111
|
package com.nopackname.response;
public class API_MY_GEN_MOD_ACCEPT_RESPONSE extends API_SUB_RESPONSE {
int p;
int pmax;
int pc;
int pi;
int pw;
int pcmax;
int pimax;
int pwmax;
public int getP() {
return p;
}
public void setP(int p) {
this.p = p;
}
public int getPmax() {
return pmax;
}
public void setPmax(int pmax) {
this.pmax = pmax;
}
public int getPc() {
return pc;
}
public void setPc(int pc) {
this.pc = pc;
}
public int getPi() {
return pi;
}
public void setPi(int pi) {
this.pi = pi;
}
public int getPw() {
return pw;
}
public void setPw(int pw) {
this.pw = pw;
}
public int getPcmax() {
return pcmax;
}
public void setPcmax(int pcmax) {
this.pcmax = pcmax;
}
public int getPimax() {
return pimax;
}
public void setPimax(int pimax) {
this.pimax = pimax;
}
public int getPwmax() {
return pwmax;
}
public void setPwmax(int pwmax) {
this.pwmax = pwmax;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_MY_GEN_MOD_ACCEPT_RESPONSE.java
|
Java
|
asf20
| 1,247
|
package com.nopackname.response;
public class API_GOODS_RESPONSE {
private int code;
private API_GOODS_LIST_RESPONSE ret;// json
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public API_GOODS_LIST_RESPONSE getRet() {
return ret;
}
public void setRet(API_GOODS_LIST_RESPONSE ret) {
this.ret = ret;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_GOODS_RESPONSE.java
|
Java
|
asf20
| 446
|
package com.nopackname.response;
public class API_MY_GEN_MOD_WASHPRICE_BASE_RESPONSE {
private int code;
private API_MY_GEN_MOD_WASHPRICE_RESPONSE ret;// json
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public API_MY_GEN_MOD_WASHPRICE_RESPONSE getRet() {
return ret;
}
public void setRet(API_MY_GEN_MOD_WASHPRICE_RESPONSE ret) {
this.ret = ret;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_MY_GEN_MOD_WASHPRICE_BASE_RESPONSE.java
|
Java
|
asf20
| 496
|
package com.nopackname.response;
// super class
public class API_SUB_RESPONSE {
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_SUB_RESPONSE.java
|
Java
|
asf20
| 90
|
package com.nopackname.response;
import java.util.List;
import com.nopackname.bean.City;
public class API_GET_USERINFO2_RET {
private List<Object> user;
private List<City> city;
public List<Object> getUser() {
return user;
}
public void setUser(List<Object> user) {
this.user = user;
}
public List<City> getCity() {
return city;
}
public void setCity(List<City> city) {
this.city = city;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_GET_USERINFO2_RET.java
|
Java
|
asf20
| 499
|
package com.nopackname.response;
public class API_GOODS_RESPONSE2 {
private int code;
private API_GOODS_SALE_RESPONSE ret;// json
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public API_GOODS_SALE_RESPONSE getRet() {
return ret;
}
public void setRet(API_GOODS_SALE_RESPONSE ret) {
this.ret = ret;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/response/API_GOODS_RESPONSE2.java
|
Java
|
asf20
| 447
|
package com.nopackname.db;
public class Global {
// ================= bai cai jun ==================
public static final int bcjId = 91793;
public static final int bcjCity = 91739;
public static final int bcjYuanshao = 378933;
// ================= yan bai cai ==================
public static final int yanbcCity = 141093;
public static final int yanbcZhouyu = 385477;
public static final int yanbcSunjian = 376119;
/** 飞骗 */
public static final int SID_HOURSE_41 = 41;
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/db/Global.java
|
Java
|
asf20
| 533
|
package com.nopackname;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.nopackname.api.*;
import com.nopackname.db.Global;
import com.nopackname.tools.*;
import com.nopackname.response.*;
public class Emulator {
/**
* @param args
*/
public static void main(String[] args) {
// constant
// init
int myGeneralId = Global.bcjYuanshao;
int myCity = Global.bcjCity;
// target
int pcTarget = -1;
int piTarget = -1;
int pwTarget = -1;
int currentPc = 0;
int currentPi = 0;
int currentPw = 0;
int currentPcMax = 0;
int currentPiMax = 0;
int currentPwMax = 0;
Queue<API> commands = new ConcurrentLinkedQueue<API>();
commands.add(new API_GET_USERINFO());
commands.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.WASHPRICE, myGeneralId, myCity));
commands.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.REINIT, myGeneralId, myCity, API_MY_GEN_MOD.MODE_EXP));
// do command
while (true) {
API cmd = commands.poll();
if (null == cmd) {
break;
}
String uriString = API.HOST_MAIN + cmd.toString();
Map<String, String> headers = new HashMap<String, String>();
final HttpResult result = new HttpResult();
try {
HttpClient.httpGet(uriString, headers, result, API.generateAccLgoinResponseHandler(result));
} catch (Exception e) {
// TODO: handle exception
}
if (cmd instanceof API_MY_GEN_MOD) {
// logical
API_MY_GEN_MOD gen = (API_MY_GEN_MOD) cmd;
if (API_MY_GEN_MOD.REINIT.equals(gen.getAction())) {
API_MY_GEN_MOD_REINIT_BASE_RESPONSE resp = (API_MY_GEN_MOD_REINIT_BASE_RESPONSE) JSONUtil
.parseObject(result.getResponse(), API_MY_GEN_MOD_REINIT_BASE_RESPONSE.class);
API_MY_GEN_MOD_REINIT_RESPONSE reinit = resp.getRet();
boolean accept = false;
// judgement
if (pcTarget > 0) {
if (reinit.getCt() > currentPc) {
} else {
}
if (currentPc < currentPcMax - 10) {
}
}
if (piTarget > 0) {
System.out.println("now jueji: " + reinit.getIt() + " pre jueji: " + currentPi);
if (reinit.getIt() > currentPi) {
} else {
}
if (currentPi < currentPiMax - 10) {
}
}
if (pwTarget > 0) {
if (reinit.getWt() > currentPw) {
} else {
}
if (currentPw < currentPwMax - 10) {
}
}
if (accept) {
// accept
currentPc = reinit.getCt();
currentPi = reinit.getIt();
currentPw = reinit.getWt();
commands.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.ACCEPT, myGeneralId, myCity,
API_MY_GEN_MOD.MODE_EXP));
} else
// reject
commands.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.REJECT, myGeneralId, myCity,
API_MY_GEN_MOD.MODE_EXP));
// reinit
commands
.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.REINIT, myGeneralId, myCity, API_MY_GEN_MOD.MODE_EXP));
} else if (API_MY_GEN_MOD.REJECT.equals(gen.getAction())) {
} else if (API_MY_GEN_MOD.ACCEPT.equals(gen.getAction())) {
} else if (API_MY_GEN_MOD.WASHPRICE.equals(gen.getAction())) {
API_MY_GEN_MOD_WASHPRICE_BASE_RESPONSE baseResp = (API_MY_GEN_MOD_WASHPRICE_BASE_RESPONSE) JSONUtil
.parseObject(result.getResponse(), API_MY_GEN_MOD_WASHPRICE_BASE_RESPONSE.class);
API_MY_GEN_MOD_WASHPRICE_RESPONSE resp = baseResp.getRet();
currentPc = resp.getPc();
currentPcMax = resp.getPcmax();
if (currentPc < currentPcMax - 10) {
pcTarget = currentPcMax - 10;
}
currentPi = resp.getPi();
currentPiMax = resp.getPimax();
if (currentPi < currentPiMax - 10) {
piTarget = currentPiMax - 10;
}
currentPw = resp.getPw();
currentPwMax = resp.getPwmax();
if (currentPw < currentPwMax - 10) {
pwTarget = currentPwMax - 10;
}
}
} else if (cmd instanceof API_GEN_CONSCRIBE) {
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Finished.");
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/Emulator.java
|
Java
|
asf20
| 5,638
|
package com.nopackname;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.nopackname.api.*;
import com.nopackname.db.Global;
import com.nopackname.tools.*;
import com.nopackname.response.*;
public class WASH {
/**
* @param args
*/
public static void main(String[] args) {
// constant
// initial
int myGeneralId = Global.yanbcZhouyu;
int myCity = Global.yanbcCity;
// target
int pcTarget = -1;
int piTarget = -1;
int pwTarget = -2; // initial value -2
int currentPc = 0;
int currentPi = 0;
int currentPw = 0;
int currentPcMax = 0;
int currentPiMax = 0;
int currentPwMax = 0;
Queue<API> commands = new ConcurrentLinkedQueue<API>();
commands.add(new API_GET_USERINFO());
commands.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.WASHPRICE, myGeneralId,
myCity));
commands.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.REINIT, myGeneralId,
myCity, API_MY_GEN_MOD.MODE_EXP));
// do command
while (true) {
API cmd = commands.poll();
if (null == cmd)
break;
String uriString = API.HOST_MAIN + cmd.toString();
Map<String, String> headers = new HashMap<String, String>();
final HttpResult result = new HttpResult();
try {
HttpClient.httpGet(uriString, headers, result,
API.generateAccLgoinResponseHandler(result));
} catch (Exception e) {
}
if (cmd instanceof API_MY_GEN_MOD) {
// logical
API_MY_GEN_MOD gen = (API_MY_GEN_MOD) cmd;
if (API_MY_GEN_MOD.REINIT.equals(gen.getAction())) {
API_MY_GEN_MOD_REINIT_BASE_RESPONSE resp = (API_MY_GEN_MOD_REINIT_BASE_RESPONSE) JSONUtil
.parseObject(result.getResponse(),
API_MY_GEN_MOD_REINIT_BASE_RESPONSE.class);
API_MY_GEN_MOD_REINIT_RESPONSE reinit = resp.getRet();
boolean accept = true;
// judgement
if (pcTarget > 0 && reinit.getCt() < currentPc)
accept = false;
if (piTarget > 0 && reinit.getIt() < currentPi)
accept = false;
if (pwTarget > 0 && reinit.getWt() < currentPw)
accept = false;
System.out.println("now wuli: " + reinit.getCt() + " pre: "
+ currentPc);
System.out.println("now jueji: " + reinit.getIt()
+ " pre: " + currentPi);
System.out.println("now moulve: " + reinit.getWt()
+ " pre: " + currentPw);
if (accept) {
// accept
currentPc = reinit.getCt();
currentPi = reinit.getIt();
currentPw = reinit.getWt();
commands.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.ACCEPT,
myGeneralId, myCity, API_MY_GEN_MOD.MODE_EXP));
System.out
.println("====================================================ACCEPTED!====================================================");
} else
// reject
commands.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.REJECT,
myGeneralId, myCity, API_MY_GEN_MOD.MODE_EXP));
// reinit
boolean needReinit = false;
if (pcTarget != -2 && currentPc < currentPcMax - 10)
needReinit = true;
if (piTarget != -2 && currentPi < currentPiMax - 10)
needReinit = true;
if (pwTarget != -2 && currentPw < currentPwMax - 10)
needReinit = true;
if (needReinit)
commands.add(new API_MY_GEN_MOD(API_MY_GEN_MOD.REINIT,
myGeneralId, myCity, API_MY_GEN_MOD.MODE_EXP));
} else if (API_MY_GEN_MOD.REJECT.equals(gen.getAction())) {
} else if (API_MY_GEN_MOD.ACCEPT.equals(gen.getAction())) {
} else if (API_MY_GEN_MOD.WASHPRICE.equals(gen.getAction())) {
API_MY_GEN_MOD_WASHPRICE_BASE_RESPONSE baseResp = (API_MY_GEN_MOD_WASHPRICE_BASE_RESPONSE) JSONUtil
.parseObject(
result.getResponse(),
API_MY_GEN_MOD_WASHPRICE_BASE_RESPONSE.class);
API_MY_GEN_MOD_WASHPRICE_RESPONSE resp = baseResp.getRet();
currentPc = resp.getPc();
currentPcMax = resp.getPcmax();
if (currentPc < currentPcMax - 10 && -1 == pcTarget)
pcTarget = currentPcMax - 10;
currentPi = resp.getPi();
currentPiMax = resp.getPimax();
if (currentPi < currentPiMax - 10 && -1 == piTarget)
piTarget = currentPiMax - 10;
currentPw = resp.getPw();
currentPwMax = resp.getPwmax();
if (currentPw < currentPwMax - 10 && -1 == pwTarget)
pwTarget = currentPwMax - 10;
}
} else if (cmd instanceof API_GEN_CONSCRIBE) {
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Finished.");
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/WASH.java
|
Java
|
asf20
| 6,168
|
package com.nopackname.bean;
public class Attribute {
private int xed;
private int xea;
private int exd;
private int exa;
private int end;
private int ena;
private int c;
private int courage;
private int wisdom;
private int instinct;
private int r_power;
public int getXed() {
return xed;
}
public void setXed(int xed) {
this.xed = xed;
}
public int getXea() {
return xea;
}
public void setXea(int xea) {
this.xea = xea;
}
public int getExd() {
return exd;
}
public void setExd(int exd) {
this.exd = exd;
}
public int getExa() {
return exa;
}
public void setExa(int exa) {
this.exa = exa;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getEna() {
return ena;
}
public void setEna(int ena) {
this.ena = ena;
}
public int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
public int getCourage() {
return courage;
}
public void setCourage(int courage) {
this.courage = courage;
}
public int getWisdom() {
return wisdom;
}
public void setWisdom(int wisdom) {
this.wisdom = wisdom;
}
public int getInstinct() {
return instinct;
}
public void setInstinct(int instinct) {
this.instinct = instinct;
}
public int getR_power() {
return r_power;
}
public void setR_power(int r_power) {
this.r_power = r_power;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/bean/Attribute.java
|
Java
|
asf20
| 1,789
|
package com.nopackname.bean;
public class Item {
private int id;
private int sid;
private int up;
private Attribute attr;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public int getUp() {
return up;
}
public void setUp(int up) {
this.up = up;
}
public Attribute getAttr() {
return attr;
}
public void setAttr(Attribute attr) {
this.attr = attr;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/bean/Item.java
|
Java
|
asf20
| 661
|
package com.nopackname.bean;
public class Gift {
private int id;
private String msg;
private int s;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getS() {
return s;
}
public void setS(int s) {
this.s = s;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/bean/Gift.java
|
Java
|
asf20
| 490
|
package com.nopackname.bean;
public class Event {
private int id;
private String icon;
private String name;
private String desc;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/bean/Event.java
|
Java
|
asf20
| 692
|
package com.nopackname.bean;
public class Status {
private int invite;
private int vs;
private int vr;
private int ce;
public int getInvite() {
return invite;
}
public void setInvite(int invite) {
this.invite = invite;
}
public int getVs() {
return vs;
}
public void setVs(int vs) {
this.vs = vs;
}
public int getVr() {
return vr;
}
public void setVr(int vr) {
this.vr = vr;
}
public int getCe() {
return ce;
}
public void setCe(int ce) {
this.ce = ce;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/bean/Status.java
|
Java
|
asf20
| 650
|
package com.nopackname.bean;
public class Good {
private Item item;
private int use;
private int sale;
private int num;
private Object jewel_effect;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public int getUse() {
return use;
}
public void setUse(int use) {
this.use = use;
}
public int getSale() {
return sale;
}
public void setSale(int sale) {
this.sale = sale;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Object getJewel_effect() {
return jewel_effect;
}
public void setJewel_effect(Object jewel_effect) {
this.jewel_effect = jewel_effect;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/bean/Good.java
|
Java
|
asf20
| 887
|
package com.nopackname.bean;
import java.util.List;
public class User {
private int id;
private String nick;
private int nation;
private int level;
private int money; // yuanbao
private String legion;
private int legionid;
private int power;
private int flag;
private int status;
private List<City> city;
private List<Object> conq;
private int exp;
private int honor;
private int lastmap;
private int m_uid;
private List<String> bt;
private int racewar;
private String bind;
private String activity;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public int getNation() {
return nation;
}
public void setNation(int nation) {
this.nation = nation;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public String getLegion() {
return legion;
}
public void setLegion(String legion) {
this.legion = legion;
}
public int getLegionid() {
return legionid;
}
public void setLegionid(int legionid) {
this.legionid = legionid;
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public List<City> getCity() {
return city;
}
public void setCity(List<City> city) {
this.city = city;
}
public List<Object> getConq() {
return conq;
}
public void setConq(List<Object> conq) {
this.conq = conq;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getHonor() {
return honor;
}
public void setHonor(int honor) {
this.honor = honor;
}
public int getLastmap() {
return lastmap;
}
public void setLastmap(int lastmap) {
this.lastmap = lastmap;
}
public int getM_uid() {
return m_uid;
}
public void setM_uid(int m_uid) {
this.m_uid = m_uid;
}
public List<String> getBt() {
return bt;
}
public void setBt(List<String> bt) {
this.bt = bt;
}
public int getRacewar() {
return racewar;
}
public void setRacewar(int racewar) {
this.racewar = racewar;
}
public String getBind() {
return bind;
}
public void setBind(String bind) {
this.bind = bind;
}
public String getActivity() {
return activity;
}
public void setActivity(String activity) {
this.activity = activity;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/bean/User.java
|
Java
|
asf20
| 3,446
|
package com.nopackname.bean;
public class City {
private int id;
private String name;
private int in;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIn() {
return in;
}
public void setIn(int in) {
this.in = in;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/bean/City.java
|
Java
|
asf20
| 504
|
package com.nopackname;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.nopackname.api.API;
import com.nopackname.api.API_GEN_CONSCRIBE;
import com.nopackname.api.API_GOODS;
import com.nopackname.bean.Good;
import com.nopackname.db.Global;
import com.nopackname.response.API_GOODS_LIST_RESPONSE;
import com.nopackname.response.API_GOODS_RESPONSE;
import com.nopackname.response.API_GOODS_RESPONSE2;
import com.nopackname.response.API_GOODS_SALE_RESPONSE;
import com.nopackname.tools.HttpClient;
import com.nopackname.tools.HttpResult;
import com.nopackname.tools.JSONUtil;
public class Sale {
/**
* @param args
*/
public static void main(String[] args) {
// constant
// init
int myCity = Global.bcjCity;
Queue<API> commands = new ConcurrentLinkedQueue<API>();
commands.add(new API_GOODS(API_GOODS.API_GOODS_TYPE_0,
API_GOODS.API_GOODS_ACTION_LIST, myCity, 1));
// do command
while (true) {
API cmd = commands.poll();
if (null == cmd) {
break;
}
String uriString = API.HOST_MAIN + cmd.toString();
Map<String, String> headers = new HashMap<String, String>();
final HttpResult result = new HttpResult();
try {
HttpClient.httpGet(uriString, headers, result,
API.generateAccLgoinResponseHandler(result));
} catch (Exception e) {
e.printStackTrace();
}
if (cmd instanceof API_GOODS) {
// logical
API_GOODS list = (API_GOODS) cmd;
if (API_GOODS.API_GOODS_ACTION_LIST.equals(list.getAction())) {
API_GOODS_RESPONSE resp = (API_GOODS_RESPONSE) JSONUtil
.parseObject(result.getResponse(),
API_GOODS_RESPONSE.class);
API_GOODS_LIST_RESPONSE listResp = resp.getRet();
System.out.println(listResp.getMax());
List<Good> item = listResp.getItem();
List<Integer> ids = new ArrayList<Integer>();
for (Good good : item) {
Integer id = good.getItem().getId();
if (!ids.contains(id)) {
ids.add(id);
}
}
// add to sale list
for (Integer id : ids) {
commands.add(new API_GOODS(id, 1,
API_GOODS.API_GOODS_ACTION_SALE, myCity));
}
} else if (API_GOODS.API_GOODS_ACTION_LIST.equals(list
.getAction())) {
API_GOODS_RESPONSE2 resp = (API_GOODS_RESPONSE2) JSONUtil
.parseObject(result.getResponse(),
API_GOODS_RESPONSE2.class);
API_GOODS_SALE_RESPONSE saleResp = resp.getRet();
System.out.println(saleResp.getCredit());
}
} else if (cmd instanceof API_GEN_CONSCRIBE) {
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Finished.");
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/Sale.java
|
Java
|
asf20
| 3,699
|
package com.nopackname.api;
public class API_GOODS extends API {
// /api_goods.php?jsonpcallback=jsonp1411869878198&_=1411870358831&
// key=7359fe71b7ab9f074a56e8612f3d26f0&action=list&type=0&city=91739&page=1&_l=chs&_p=ZZ-DROID-CHS-TTGW
// /api_goods.php?jsonpcallback=jsonp1411869878197&_=1411870358646&
// key=7359fe71b7ab9f074a56e8612f3d26f0&id=9047976&city=91739&action=sale&num=1&_l=chs&_p=ZZ-DROID-CHS-TTGW
private int id;
private int num;
private int type;
private String action;
private int city;
private int page;
public static final String API_GOODS_ACTION_LIST = "list";
public static final String API_GOODS_ACTION_SALE = "sale";
public static final int API_GOODS_TYPE_0 = 0;
// get page good list
public API_GOODS(int type, String action, int city, int page) {
super();
path = "/api_goods.php?";
this.type = type;
this.action = action;
this.city = city;
this.page = page;
}
public API_GOODS(int id, int num, String action, int city) {
super();
path = "/api_goods.php?";
this.id = id;
this.num = num;
this.action = action;
this.city = city;
}
@Override
public String toString() {
StringBuilder uriBuilder = new StringBuilder();
uriBuilder.append(path).append(JSONPCALLBACK).append(EQUAL).append(jsonpcallback);
uriBuilder.append(AND).append(_).append(EQUAL).append(tag_);
uriBuilder.append(AND).append(KEY).append(EQUAL).append(key);
uriBuilder.append(AND).append(ACTION).append(EQUAL).append(action);
if (API_GOODS_ACTION_LIST.equals(action)) {
uriBuilder.append(AND).append(TYPE).append(EQUAL).append(type);
}
if (API_GOODS_ACTION_SALE.equals(action)) {
uriBuilder.append(AND).append(ID).append(EQUAL).append(id);
uriBuilder.append(AND).append(NUM).append(EQUAL).append(num);
}
uriBuilder.append(AND).append(CITY).append(EQUAL).append(city);
uriBuilder.append(AND).append(_L).append(EQUAL).append(_l);
uriBuilder.append(AND).append(_P).append(EQUAL).append(_p);
return uriBuilder.toString();
}
// setter & getter
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API_GOODS.java
|
Java
|
asf20
| 3,118
|
package com.nopackname.api;
public class API_GET_USERINFO2 extends API {
// /api_get_userinfo2.php?jsonpcallback=jsonp1416379292183&_=1416379781520&key=740e978717d64de3a6476c90ff2695cd&
// id=90972&_l=chs&_p=ZZ-DROID-CHS-TTGW HTTP/1.0
public API_GET_USERINFO2(int id) {
super();
this.id = id;
path = "/api_get_userinfo2.php?";
}
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
StringBuilder uriBuilder = new StringBuilder();
uriBuilder.append(path).append(JSONPCALLBACK).append(EQUAL)
.append(jsonpcallback);
uriBuilder.append(AND).append(_).append(EQUAL).append(tag_);
uriBuilder.append(AND).append(KEY).append(EQUAL).append(key);
uriBuilder.append(AND).append(ID).append(EQUAL).append(id);
uriBuilder.append(AND).append(_L).append(EQUAL).append(_l);
uriBuilder.append(AND).append(_P).append(EQUAL).append(_p);
return uriBuilder.toString();
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API_GET_USERINFO2.java
|
Java
|
asf20
| 1,138
|
package com.nopackname.api;
public class API_GEN_CONSCRIBE extends API {
// /api_gen_conscribe.php?jsonpcallback=jsonp1411542456839&_=1411542462886&key=a1515c0cba99d6f4336f4d88d73bf93b&city=91739
// &action=gen_list&extra=0&rid=0&_l=chs&_p=ZZ-DROID-CHS-TTGW HTTP/1.0
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API_GEN_CONSCRIBE.java
|
Java
|
asf20
| 286
|
package com.nopackname.api;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import com.nopackname.tools.HttpClient;
import com.nopackname.tools.HttpResult;
public class API_CHAT extends API {
public static final String TARGETID = "targetid";
public static final String TARGETID_DEFAULT = "0";
public static final String TARGETTYPE = "targettype";
public static final String TARGETTYPE_DEFAULT = "0";
public static final String TARGETTYPE_WEI = "1";
public static final String TARGETTYPE_SHU = "2";
public static final String TARGETTYPE_WU = "3";
public static final String TXT = "txt";
String targetid = TARGETID_DEFAULT;
String targettype = TARGETTYPE_DEFAULT;
String txt = "";
public API_CHAT() {
super();
path = "/api_chat.php?";
}
public API_CHAT(String targetid, String targettype, String txt) {
super();
path = "/api_chat.php?";
this.targetid = targetid;
this.targettype = targettype;
this.txt = toURIEncoded(txt);
}
@Override
public String toString() {
// GET
// /api_chat.php?jsonpcallback=jsonp1410847222600&_=1410848897214&key=02bf4daf8213c95f90578a2486964ca1&
// targetid=0&targettype=0&txt=abc456&_l=chs&_p=ZZ-DROID-CHS-TTGW
// HTTP/1.0
StringBuilder uriBuilder = new StringBuilder();
uriBuilder.append(path).append(JSONPCALLBACK).append(EQUAL).append(jsonpcallback);
uriBuilder.append(AND).append(_).append(EQUAL).append(tag_);
uriBuilder.append(AND).append(KEY).append(EQUAL).append(key);
uriBuilder.append(AND).append(TARGETID).append(EQUAL).append(targetid);
uriBuilder.append(AND).append(TARGETTYPE).append(EQUAL).append(targettype);
uriBuilder.append(AND).append(TXT).append(EQUAL).append(txt);
uriBuilder.append(AND).append(_L).append(EQUAL).append(_l);
uriBuilder.append(AND).append(_P).append(EQUAL).append(_p);
return uriBuilder.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
// GET /api_chat.php?jsonpcallback=jsonp1411438646449&_=1411440345670&
// key=b149f2af001fd35f6f5fdc82d013dd80&lineid=141143901290&_l=chs&_p=ZZ-DROID-CHS-TTGW
// HTTP/1.0
API_CHAT chat = new API_CHAT();
chat.targettype = TARGETTYPE_DEFAULT;
chat.txt = toURIEncoded("今天疯狂爆丹 555");
System.out.println(chat.toString());
String uriString = "http://101.251.194.245" + chat.toString();
Map<String, String> headers = new HashMap<String, String>();
final HttpResult result = new HttpResult();
try {
HttpClient.httpGet(uriString, headers, result, generateAccLgoinResponseHandler(result));
} catch (Exception e) {
// TODO: handle exception
}
}
public static String parseTxt2Unicode(String msg) {
return toUnicodeString(msg);
}
public static String unicodeToGB(String s) {
StringBuffer sb = new StringBuffer();
StringTokenizer st = new StringTokenizer(s, "\\u");
while (st.hasMoreTokens()) {
sb.append((char) Integer.parseInt(st.nextToken(), 16));
}
return sb.toString();
}
public static String toURIEncoded(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
public static String toUnicodeString(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
sb.append("\\u" + Integer.toHexString(c));
}
}
return sb.toString();
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API_CHAT.java
|
Java
|
asf20
| 4,181
|
package com.nopackname.api;
public class API_MY_GEN_MOD extends API {
// /api_my_gen_mod.php?jsonpcallback=jsonp1411542456840&_=1411542466921&key=a1515c0cba99d6f4336f4d88d73bf93b
// &action=washprice&id=378933&city=91739&_l=chs&_p=ZZ-DROID-CHS-TTGW
// /api_my_gen_mod.php?jsonpcallback=jsonp1411542456841&_=1411542469673&key=a1515c0cba99d6f4336f4d88d73bf93b
// &action=reinit&id=378933&city=91739&mode=1&_l=chs&_p=ZZ-DROID-CHS-TTGW
// /api_my_gen_mod.php?jsonpcallback=jsonp1411542456872&_=1411542493170&key=a1515c0cba99d6f4336f4d88d73bf93b
// &action=reject&id=378933&city=91739&mode=1&_l=chs&_p=ZZ-DROID-CHS-TTGW
// /api_my_gen_mod.php?jsonpcallback=jsonp1411542456872&_=1411542493170&key=a1515c0cba99d6f4336f4d88d73bf93b
// &action=accept&id=378933&city=91739&mode=1&_l=chs&_p=ZZ-DROID-CHS-TTGW
// /api_my_gen_mod.php?jsonpcallback=jsonp1412059503532&_=1412062681261&key=8e6f2fdcaff0b469a689e3eb2a6b66ac
// &action=exptrain&mode=0&city=91739&id=378933&_l=chs&_p=ZZ-DROID-CHS-TTGW
/** for mod gen summary */
public static final String WASHPRICE = "washprice";
/** mod gen */
public static final String REINIT = "reinit";
public static final String REJECT = "reject";
public static final String ACCEPT = "accept";
/** train */
public static final String EXPTRAIN = "exptrain";
// constant
public static final int MODE_EXP = 1;
public static final int MODE_MONEY = 2;
public static final int MODE_MONEY2 = 3;
//
String action = WASHPRICE;
int id;
int city;
int mode = MODE_EXP;
public API_MY_GEN_MOD() {
super();
this.path = "/api_my_gen_mod.php?";
}
public API_MY_GEN_MOD(String action, int id, int city, int mode) {
super();
this.path = "/api_my_gen_mod.php?";
this.action = action;
this.id = id;
this.city = city;
this.mode = mode;
}
public API_MY_GEN_MOD(String action, int id, int city) {
super();
this.path = "/api_my_gen_mod.php?";
this.action = action;
this.id = id;
this.city = city;
}
@Override
public String toString() {
StringBuilder uriBuilder = new StringBuilder();
uriBuilder.append(path).append(JSONPCALLBACK).append(EQUAL).append(jsonpcallback);
uriBuilder.append(AND).append(_).append(EQUAL).append(tag_);
uriBuilder.append(AND).append(KEY).append(EQUAL).append(key);
//
uriBuilder.append(AND).append(ACTION).append(EQUAL).append(action);
uriBuilder.append(AND).append(ID).append(EQUAL).append(id);
uriBuilder.append(AND).append(CITY).append(EQUAL).append(city);
if (!WASHPRICE.equals(action)) {
uriBuilder.append(AND).append(MODE).append(EQUAL).append(mode);
}
//
uriBuilder.append(AND).append(_L).append(EQUAL).append(_l);
uriBuilder.append(AND).append(_P).append(EQUAL).append(_p);
return uriBuilder.toString();
}
// setter & getter
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public int getMode() {
return mode;
}
public void setMode(int mode) {
this.mode = mode;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API_MY_GEN_MOD.java
|
Java
|
asf20
| 3,653
|
package com.nopackname.api;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import com.nopackname.tools.HttpResult;
public class API {
// constant
public static final String ACTION = "action";
public static final String PAGE = "page";
public static final String ID = "id";
public static final String CITY = "city";
public static final String MODE = "mode";
public static final String TYPE = "type";
public static final String NUM = "num";
// hidden
public static long startUpTime = System.currentTimeMillis();
// symbol
public static final String AND = "&";
public static final String EQUAL = "=";
// http stuff
public static final String HOST_PRE = "http://m.zzsanguo.com";
public static final String HOST_MAIN = "http://s6.zzsanguo.com";
//
public static final String JSONPCALLBACK = "jsonpcallback";
/**
* i guess it records the start time of a command
*/
public static final String JSONP = "jsonp";
/**
* i guess it records the end time of a command
*/
public static final String _ = "_";
public static final String KEY = "key";
public static final String _L = "_l";
public static final String _L_DEFAULT_CHS = "chs";
public static final String _L_DEFAULT_EN = "en";
public static final String _P = "_p";
public static final String _P_DEFAULT_ANDROID = "ZZ-DROID-CHS-TTGW";
public static final String _P_DEFAULT_IPHONE = "ZZ-IPHONE-CHS";
//
String path;
String jsonpcallback;
long tag_;
String key;
//
int city;
//
String _l = _L_DEFAULT_CHS;
String _p = _P_DEFAULT_ANDROID;
public API() {
super();
// generate jsonpcallback
this.jsonpcallback = generateJSONPCallback();
this.tag_ = System.currentTimeMillis();
this.key = generateKey();
}
public static ResponseHandler<String> generateAccLgoinResponseHandler(
final HttpResult httpResult) {
// Create a custom response handler
return new ResponseHandler<String>() {
public String handleResponse(final HttpResponse response)
throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
httpResult.setStatus(String.valueOf(status));
String result = EntityUtils.toString(response.getEntity());
System.out.println("[RESPONSE]: " + result);
httpResult.setResponse(result);
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? result : null;
} else {
throw new ClientProtocolException(
"Unexpected response status: " + status);
}
}
};
}
private static int commandCount = 0;
private String generateJSONPCallback() {
return JSONPCALLBACK + startUpTime + commandCount++;
}
private String generateKey() {
return "740e978717d64de3a6476c90ff2695cd";
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API.java
|
Java
|
asf20
| 3,467
|
package com.nopackname.api;
public class API_GET_USERINFO extends API {
// /api_get_userinfo.php?jsonpcallback=jsonp1411542452515&_=1411542456494&
// key=a1515c0cba99d6f4336f4d88d73bf93b&_l=chs&_p=ZZ-DROID-CHS-TTGW
public API_GET_USERINFO() {
super();
path = "/api_get_userinfo.php?";
}
@Override
public String toString() {
StringBuilder uriBuilder = new StringBuilder();
uriBuilder.append(path).append(JSONPCALLBACK).append(EQUAL).append(jsonpcallback);
uriBuilder.append(AND).append(_).append(EQUAL).append(tag_);
uriBuilder.append(AND).append(KEY).append(EQUAL).append(key);
uriBuilder.append(AND).append(_L).append(EQUAL).append(_l);
uriBuilder.append(AND).append(_P).append(EQUAL).append(_p);
return uriBuilder.toString();
}
public static void main(String[] args) {
API_GET_USERINFO api_get_userinfo = new API_GET_USERINFO();
System.out.println(api_get_userinfo.toString());
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API_GET_USERINFO.java
|
Java
|
asf20
| 1,037
|
package com.nopackname.api;
public class MD5Ver extends API {
// http://m.zzsanguo.com/md5ver.dat?_p=ZZ-DROID-CHS-TTGW
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/MD5Ver.java
|
Java
|
asf20
| 133
|
package com.nopackname.api;
public class API_UNION extends API {
// /api_union.php?jsonpcallback=jsonp1416379292181&_=1416379777606&
// key=740e978717d64de3a6476c90ff2695cd&action=my&_l=chs&_p=ZZ-DROID-CHS-TTGW
// HTTP/1.0
// /api_union.php?jsonpcallback=jsonp1416379292182&_=1416379778980&
// key=740e978717d64de3a6476c90ff2695cd&action=member&page=1&_l=chs&_p=ZZ-DROID-CHS-TTGW
// HTTP/1.0
private String action;
private int page;
public static final String API_UNION_ACTION_MY = "my";
public static final String API_UNION_ACTION_MEMBER = "member";
// get page good list
public API_UNION(String action, int page) {
super();
path = "/api_union.php?";
this.action = action;
this.page = page;
}
public API_UNION(String action) {
super();
path = "/api_goods.php?";
this.action = action;
}
@Override
public String toString() {
StringBuilder uriBuilder = new StringBuilder();
uriBuilder.append(path).append(JSONPCALLBACK).append(EQUAL)
.append(jsonpcallback);
uriBuilder.append(AND).append(_).append(EQUAL).append(tag_);
uriBuilder.append(AND).append(KEY).append(EQUAL).append(key);
uriBuilder.append(AND).append(ACTION).append(EQUAL).append(action);
if (API_UNION_ACTION_MEMBER.equals(action)) {
uriBuilder.append(AND).append(PAGE).append(EQUAL).append(page);
}
uriBuilder.append(AND).append(_L).append(EQUAL).append(_l);
uriBuilder.append(AND).append(_P).append(EQUAL).append(_p);
return uriBuilder.toString();
}
// setter & getter
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API_UNION.java
|
Java
|
asf20
| 2,013
|
package com.nopackname.api;
public class API_GET_CITYINFO extends API {
// /api_get_cityinfo.php?jsonpcallback=jsonp1416379292190&_=1416379796398&
// key=740e978717d64de3a6476c90ff2695cd&action=trade_out&city=91739&uid_to=89880&city_to=89844&_l=chs&_p=ZZ-DROID-CHS-TTGW
// HTTP/1.0
public static final String UID_TO = "uid_to";
public static final String CITY_TO = "city_to";
private int uid_to;
private int city_to;
private String action;
public static final String API_GET_CITYINFO_ACTION_TRADE_OUT = "trade_out";
/**
* trade
*
* @param myCity
* @param uid_to
* @param city_to
*/
public API_GET_CITYINFO(String action, int myCity, int uid_to, int city_to) {
super();
path = "/api_get_cityinfo.php?";
this.action = action;
this.city = myCity;
this.uid_to = uid_to;
this.city_to = city_to;
}
@Override
public String toString() {
StringBuilder uriBuilder = new StringBuilder();
uriBuilder.append(path).append(JSONPCALLBACK).append(EQUAL)
.append(jsonpcallback);
uriBuilder.append(AND).append(_).append(EQUAL).append(tag_);
uriBuilder.append(AND).append(KEY).append(EQUAL).append(key);
uriBuilder.append(AND).append(ACTION).append(EQUAL).append(action);
if (API_GET_CITYINFO_ACTION_TRADE_OUT.equals(action)) {
uriBuilder.append(AND).append(CITY).append(EQUAL).append(city);
uriBuilder.append(AND).append(UID_TO).append(EQUAL).append(uid_to);
uriBuilder.append(AND).append(CITY_TO).append(EQUAL)
.append(city_to);
}
uriBuilder.append(AND).append(_L).append(EQUAL).append(_l);
uriBuilder.append(AND).append(_P).append(EQUAL).append(_p);
return uriBuilder.toString();
}
public int getUid_to() {
return uid_to;
}
public void setUid_to(int uid_to) {
this.uid_to = uid_to;
}
public int getCity_to() {
return city_to;
}
public void setCity_to(int city_to) {
this.city_to = city_to;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API_GET_CITYINFO.java
|
Java
|
asf20
| 2,416
|
package com.nopackname.api;
public class API_SP_SHOP extends API {
// /api_sp_shop.php?jsonpcallback=jsonp1412059503552&_=1412064756894&key=8e6f2fdcaff0b469a689e3eb2a6b66ac
// &city=91739&type=6&action=buy
// &_l=chs&_p=ZZ-DROID-CHS-TTGW
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/api/API_SP_SHOP.java
|
Java
|
asf20
| 260
|
package com.nopackname;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.nopackname.api.API;
import com.nopackname.api.API_GET_CITYINFO;
import com.nopackname.api.API_GET_USERINFO2;
import com.nopackname.api.API_UNION;
import com.nopackname.db.Global;
import com.nopackname.response.API_GET_USERINFO2_RESPONSE;
import com.nopackname.response.API_GET_USERINFO2_RET;
import com.nopackname.response.API_UNION_MEMBER_RESPONSE;
import com.nopackname.response.API_UNION_MEMBER_RET;
import com.nopackname.tools.HttpClient;
import com.nopackname.tools.HttpResult;
import com.nopackname.tools.JSONUtil;
public class Trade {
/**
* @param args
*/
public static void main(String[] args) {
// constant
// init
int myId = Global.bcjId;
int myCity = Global.bcjCity;
Queue<API> commands = new ConcurrentLinkedQueue<API>();
commands.add(new API_UNION(API_UNION.API_UNION_ACTION_MEMBER, 2));
// do command
while (true) {
API cmd = commands.poll();
if (null == cmd) {
break;
}
String uriString = API.HOST_MAIN + cmd.toString();
Map<String, String> headers = new HashMap<String, String>();
final HttpResult result = new HttpResult();
try {
HttpClient.httpGet(uriString, headers, result,
API.generateAccLgoinResponseHandler(result));
} catch (Exception e) {
e.printStackTrace();
}
if (cmd instanceof API_UNION) {
// query union member
API_UNION union = (API_UNION) cmd;
if (API_UNION.API_UNION_ACTION_MEMBER.equals(union.getAction())) {
API_UNION_MEMBER_RESPONSE resp = (API_UNION_MEMBER_RESPONSE) JSONUtil
.parseObject(result.getResponse(),
API_UNION_MEMBER_RESPONSE.class);
// save memberId
API_UNION_MEMBER_RET ret = resp.getRet();
List<Object> list = ret.getList();
for (Object member : list) {
@SuppressWarnings("unchecked")
List<Object> attr = (List<Object>) member;
Integer memberId = (Integer) attr.get(0);
if (myId != memberId) {
commands.add(new API_GET_USERINFO2(memberId));
}
}
}
} else if (cmd instanceof API_GET_USERINFO2) {
// query city id
API_GET_USERINFO2_RESPONSE resp = (API_GET_USERINFO2_RESPONSE) JSONUtil
.parseObject(result.getResponse(),
API_GET_USERINFO2_RESPONSE.class);
API_GET_USERINFO2_RET ret = resp.getRet();
int playerId = (Integer) ret.getUser().get(0);
int cityId = ret.getCity().get(0).getId();
commands.add(new API_GET_CITYINFO(
API_GET_CITYINFO.API_GET_CITYINFO_ACTION_TRADE_OUT,
myCity, playerId, cityId));
} else if (cmd instanceof API_GET_CITYINFO) {
// do trade response
System.out.println(result.getResponse());
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Finished.");
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/Trade.java
|
Java
|
asf20
| 3,844
|
package com.nopackname.tools;
public class HttpResult {
/**
* 返回HTTP状态
*/
private String status = "-1";
/**
* 返回请求结果
*/
private String response;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResponse() {
int start = response.indexOf("(");
int end = response.indexOf(")");
return response.substring(start + 1, end);
}
public void setResponse(String response) {
this.response = response;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/tools/HttpResult.java
|
Java
|
asf20
| 644
|
package com.nopackname.tools;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Encode {
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
"e", "f" };
public MD5Encode() {
}
private static MessageDigest md = null;
private static MessageDigest getDigest() {
if (null == md) {
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return md;
}
public static String update(String pwd) {
if (pwd == null) {
return "";
}
MessageDigest md = getDigest();
md.update(pwd.getBytes());
return byteArrayToHexString(md.digest());
}
public static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0) {
n = 256 + n;
}
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static void main(String[] args) {
String s0 = "jsonp1410599368611";
System.out.println(MD5Encode.update(s0));
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/tools/MD5Encode.java
|
Java
|
asf20
| 1,518
|
package com.nopackname.tools;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpClient {
public final static void main(String[] args) throws Exception {
}
/**
* http GET
*
* @param uri
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static HttpResult httpGet(String uri, Map<String, String> headers, final HttpResult httpResult,
ResponseHandler<String> responseHandler) throws ClientProtocolException, IOException {
String status = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getMethod() + " " + httpget.getURI());
for (Entry<String, String> entry : headers.entrySet()) {
httpget.addHeader(entry.getKey(), entry.getValue());
}
// long start = System.currentTimeMillis();
status = httpclient.execute(httpget, responseHandler);
// System.out.println("[HttpClient] - GET " + uri + " response: " +
// status);
// System.out.println("INNER COST: " + (System.currentTimeMillis() -
// start));
httpResult.setStatus(status);
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.close();
}
return httpResult;
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/tools/HttpClient.java
|
Java
|
asf20
| 1,793
|
package com.nopackname.tools;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nopackname.response.API_MY_GEN_MOD_REINIT_RESPONSE;
public class JSONUtil {
static ObjectMapper mapper = null;
public static void generateJSON(Object o, OutputStream os) {
JsonGenerator jsonGenerator = null;
try {
jsonGenerator = getMapper().getFactory().createGenerator(os);
jsonGenerator.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String generateJSON(Object o) {
String result = "";
JsonGenerator jsonGenerator = null;
StringWriter writer = null;
try {
writer = new StringWriter();
jsonGenerator = getMapper().getFactory().createGenerator(writer);
jsonGenerator.writeObject(o);
result = writer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
@SuppressWarnings("unchecked")
public static Object parseObject(String json,
@SuppressWarnings("rawtypes") Class clazz) {
try {
return getMapper().readValue(json, clazz);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static ObjectMapper getMapper() {
if (null == mapper) {
mapper = new ObjectMapper();
}
return mapper;
}
public static void main(String[] args) {
API_MY_GEN_MOD_REINIT_RESPONSE resp = new API_MY_GEN_MOD_REINIT_RESPONSE();
resp.setCt(1);
resp.setExp(999999);
resp.setIt(123);
resp.setMoney(5000);
resp.setWt(2);
System.out.println(JSONUtil.generateJSON(resp));
}
}
|
zzsg-hacker
|
trunk/zzsghacker/src/com/nopackname/tools/JSONUtil.java
|
Java
|
asf20
| 2,639
|
#!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import sys
DEFAULT_VERSION = "0.6c9"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
}
import sys, os
try: from hashlib import md5
except ImportError: from md5 import md5
def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""Automatically find/download setuptools and make it available on sys.path
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end with
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
it is not already available. If `download_delay` is specified, it should
be the number of seconds that will be paused before initiating a download,
should one be required. If an older version of setuptools is installed,
this routine will print a message to ``sys.stderr`` and raise SystemExit in
an attempt to abort the calling script.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
try:
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
except pkg_resources.DistributionNotFound:
return do_download()
def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
def update_md5(filenames):
"""Update our built-in md5 registry"""
import re
for name in filenames:
base = os.path.basename(name)
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()
data = [" %r: %r,\n" % it for it in md5_data.items()]
data.sort()
repl = "".join(data)
import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); src = f.read(); f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >>sys.stderr, "Internal error!"
sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile,'w')
f.write(src)
f.close()
if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:])
|
zzz-game-prototype
|
trunk/django-piston/ez_setup.py
|
Python
|
bsd
| 9,992
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import os
setup(
name = "django-piston",
version = "0.2.2",
url = 'http://bitbucket.org/jespern/django-piston/wiki/Home',
download_url = 'http://bitbucket.org/jespern/django-piston/downloads/',
license = 'BSD',
description = "Piston is a Django mini-framework creating APIs.",
author = 'Jesper Noehr',
author_email = 'jesper@noehr.org',
packages = find_packages(),
include_package_data = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
|
zzz-game-prototype
|
trunk/django-piston/setup.py
|
Python
|
bsd
| 979
|
##############################################################################
#
# Copyright (c) 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
$Id$
"""
import os, shutil, sys, tempfile, urllib2
tmpeggs = tempfile.mkdtemp()
is_jython = sys.platform.startswith('java')
try:
import pkg_resources
except ImportError:
ez = {}
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
import pkg_resources
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
def quote (c):
return c
cmd = 'from setuptools.command.easy_install import main; main()'
ws = pkg_resources.working_set
if len(sys.argv) > 2 and sys.argv[1] == '--version':
VERSION = ' == %s' % sys.argv[2]
args = sys.argv[3:] + ['bootstrap']
else:
VERSION = ''
args = sys.argv[1:] + ['bootstrap']
if is_jython:
import subprocess
assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
quote(tmpeggs), 'zc.buildout' + VERSION],
env=dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse('setuptools')).location
),
).wait() == 0
else:
assert os.spawnle(
os.P_WAIT, sys.executable, quote (sys.executable),
'-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse('setuptools')).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout' + VERSION)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs)
|
zzz-game-prototype
|
trunk/django-piston/tests/bootstrap.py
|
Python
|
bsd
| 2,574
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import os
setup(
name = "django-piston",
version = "0.2.2",
url = 'http://bitbucket.org/jespern/django-piston/wiki/Home',
download_url = 'http://bitbucket.org/jespern/django-piston/downloads/',
license = 'BSD',
description = "Piston is a Django mini-framework creating APIs.",
author = 'Jesper Noehr',
author_email = 'jesper@noehr.org',
packages = find_packages(),
include_package_data = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
|
zzz-game-prototype
|
trunk/django-piston/.svn/text-base/setup.py.svn-base
|
Python
|
bsd
| 979
|
#!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import sys
DEFAULT_VERSION = "0.6c9"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
}
import sys, os
try: from hashlib import md5
except ImportError: from md5 import md5
def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""Automatically find/download setuptools and make it available on sys.path
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end with
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
it is not already available. If `download_delay` is specified, it should
be the number of seconds that will be paused before initiating a download,
should one be required. If an older version of setuptools is installed,
this routine will print a message to ``sys.stderr`` and raise SystemExit in
an attempt to abort the calling script.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
try:
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
except pkg_resources.DistributionNotFound:
return do_download()
def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
def update_md5(filenames):
"""Update our built-in md5 registry"""
import re
for name in filenames:
base = os.path.basename(name)
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()
data = [" %r: %r,\n" % it for it in md5_data.items()]
data.sort()
repl = "".join(data)
import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); src = f.read(); f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >>sys.stderr, "Internal error!"
sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile,'w')
f.write(src)
f.close()
if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:])
|
zzz-game-prototype
|
trunk/django-piston/.svn/text-base/ez_setup.py.svn-base
|
Python
|
bsd
| 9,992
|
import hmac, base64
from django import forms
from django.conf import settings
class Form(forms.Form):
pass
class ModelForm(forms.ModelForm):
"""
Subclass of `forms.ModelForm` which makes sure
that the initial values are present in the form
data, so you don't have to send all old values
for the form to actually validate. Django does not
do this on its own, which is really annoying.
"""
def merge_from_initial(self):
self.data._mutable = True
filt = lambda v: v not in self.data.keys()
for field in filter(filt, getattr(self.Meta, 'fields', ())):
self.data[field] = self.initial.get(field, None)
class OAuthAuthenticationForm(forms.Form):
oauth_token = forms.CharField(widget=forms.HiddenInput)
oauth_callback = forms.URLField(widget=forms.HiddenInput)
authorize_access = forms.BooleanField(required=True)
csrf_signature = forms.CharField(widget=forms.HiddenInput)
def __init__(self, *args, **kwargs):
forms.Form.__init__(self, *args, **kwargs)
self.fields['csrf_signature'].initial = self.initial_csrf_signature
def clean_csrf_signature(self):
sig = self.cleaned_data['csrf_signature']
token = self.cleaned_data['oauth_token']
sig1 = OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
if sig != sig1:
raise forms.ValidationError("CSRF signature is not valid")
return sig
def initial_csrf_signature(self):
token = self.initial['oauth_token']
return OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
@staticmethod
def get_csrf_signature(key, token):
# Check signature...
try:
import hashlib # 2.5
hashed = hmac.new(key, token, hashlib.sha1)
except:
import sha # deprecated
hashed = hmac.new(key, token, sha)
# calculate the digest base 64
return base64.b64encode(hashed.digest())
|
zzz-game-prototype
|
trunk/django-piston/piston/forms.py
|
Python
|
bsd
| 2,020
|
"""
Decorator module, see
http://www.phyast.pitt.edu/~micheles/python/documentation.html
for the documentation and below for the licence.
"""
## The basic trick is to generate the source code for the decorated function
## with the right signature and to evaluate it.
## Uncomment the statement 'print >> sys.stderr, func_src' in _decorator
## to understand what is going on.
__all__ = ["decorator", "new_wrapper", "getinfo"]
import inspect, sys
try:
set
except NameError:
from sets import Set as set
def getinfo(func):
"""
Returns an info dictionary containing:
- name (the name of the function : str)
- argnames (the names of the arguments : list)
- defaults (the values of the default arguments : tuple)
- signature (the signature : str)
- doc (the docstring : str)
- module (the module name : str)
- dict (the function __dict__ : str)
>>> def f(self, x=1, y=2, *args, **kw): pass
>>> info = getinfo(f)
>>> info["name"]
'f'
>>> info["argnames"]
['self', 'x', 'y', 'args', 'kw']
>>> info["defaults"]
(1, 2)
>>> info["signature"]
'self, x, y, *args, **kw'
"""
assert inspect.ismethod(func) or inspect.isfunction(func)
regargs, varargs, varkwargs, defaults = inspect.getargspec(func)
argnames = list(regargs)
if varargs:
argnames.append(varargs)
if varkwargs:
argnames.append(varkwargs)
signature = inspect.formatargspec(regargs, varargs, varkwargs, defaults,
formatvalue=lambda value: "")[1:-1]
return dict(name=func.__name__, argnames=argnames, signature=signature,
defaults = func.func_defaults, doc=func.__doc__,
module=func.__module__, dict=func.__dict__,
globals=func.func_globals, closure=func.func_closure)
# akin to functools.update_wrapper
def update_wrapper(wrapper, model, infodict=None):
infodict = infodict or getinfo(model)
try:
wrapper.__name__ = infodict['name']
except: # Python version < 2.4
pass
wrapper.__doc__ = infodict['doc']
wrapper.__module__ = infodict['module']
wrapper.__dict__.update(infodict['dict'])
wrapper.func_defaults = infodict['defaults']
wrapper.undecorated = model
return wrapper
def new_wrapper(wrapper, model):
"""
An improvement over functools.update_wrapper. The wrapper is a generic
callable object. It works by generating a copy of the wrapper with the
right signature and by updating the copy, not the original.
Moreovoer, 'model' can be a dictionary with keys 'name', 'doc', 'module',
'dict', 'defaults'.
"""
if isinstance(model, dict):
infodict = model
else: # assume model is a function
infodict = getinfo(model)
assert not '_wrapper_' in infodict["argnames"], (
'"_wrapper_" is a reserved argument name!')
src = "lambda %(signature)s: _wrapper_(%(signature)s)" % infodict
funcopy = eval(src, dict(_wrapper_=wrapper))
return update_wrapper(funcopy, model, infodict)
# helper used in decorator_factory
def __call__(self, func):
infodict = getinfo(func)
for name in ('_func_', '_self_'):
assert not name in infodict["argnames"], (
'%s is a reserved argument name!' % name)
src = "lambda %(signature)s: _self_.call(_func_, %(signature)s)"
new = eval(src % infodict, dict(_func_=func, _self_=self))
return update_wrapper(new, func, infodict)
def decorator_factory(cls):
"""
Take a class with a ``.caller`` method and return a callable decorator
object. It works by adding a suitable __call__ method to the class;
it raises a TypeError if the class already has a nontrivial __call__
method.
"""
attrs = set(dir(cls))
if '__call__' in attrs:
raise TypeError('You cannot decorate a class with a nontrivial '
'__call__ method')
if 'call' not in attrs:
raise TypeError('You cannot decorate a class without a '
'.call method')
cls.__call__ = __call__
return cls
def decorator(caller):
"""
General purpose decorator factory: takes a caller function as
input and returns a decorator with the same attributes.
A caller function is any function like this::
def caller(func, *args, **kw):
# do something
return func(*args, **kw)
Here is an example of usage:
>>> @decorator
... def chatty(f, *args, **kw):
... print "Calling %r" % f.__name__
... return f(*args, **kw)
>>> chatty.__name__
'chatty'
>>> @chatty
... def f(): pass
...
>>> f()
Calling 'f'
decorator can also take in input a class with a .caller method; in this
case it converts the class into a factory of callable decorator objects.
See the documentation for an example.
"""
if inspect.isclass(caller):
return decorator_factory(caller)
def _decorator(func): # the real meat is here
infodict = getinfo(func)
argnames = infodict['argnames']
assert not ('_call_' in argnames or '_func_' in argnames), (
'You cannot use _call_ or _func_ as argument names!')
src = "lambda %(signature)s: _call_(_func_, %(signature)s)" % infodict
# import sys; print >> sys.stderr, src # for debugging purposes
dec_func = eval(src, dict(_func_=func, _call_=caller))
return update_wrapper(dec_func, func, infodict)
return update_wrapper(_decorator, caller)
if __name__ == "__main__":
import doctest; doctest.testmod()
########################## LEGALESE ###############################
## Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## Redistributions in bytecode form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
## INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
## BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
## OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
## ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
## TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
## USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
## DAMAGE.
|
zzz-game-prototype
|
trunk/django-piston/piston/decorator.py
|
Python
|
bsd
| 6,890
|
from utils import rc
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
typemapper = { }
class HandlerMetaClass(type):
"""
Metaclass that keeps a registry of class -> handler
mappings.
"""
def __new__(cls, name, bases, attrs):
new_cls = type.__new__(cls, name, bases, attrs)
if hasattr(new_cls, 'model'):
typemapper[new_cls] = (new_cls.model, new_cls.is_anonymous)
return new_cls
class BaseHandler(object):
"""
Basehandler that gives you CRUD for free.
You are supposed to subclass this for specific
functionality.
All CRUD methods (`read`/`update`/`create`/`delete`)
receive a request as the first argument from the
resource. Use this for checking `request.user`, etc.
"""
__metaclass__ = HandlerMetaClass
allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')
anonymous = is_anonymous = False
exclude = ( 'id', )
fields = ( )
def flatten_dict(self, dct):
return dict([ (str(k), dct.get(k)) for k in dct.keys() ])
def has_model(self):
return hasattr(self, 'model')
def value_from_tuple(tu, name):
for int_, n in tu:
if n == name:
return int_
return None
def exists(self, **kwargs):
if not self.has_model():
raise NotImplementedError
try:
self.model.objects.get(**kwargs)
return True
except self.model.DoesNotExist:
return False
def read(self, request, *args, **kwargs):
if not self.has_model():
return rc.NOT_IMPLEMENTED
pkfield = self.model._meta.pk.name
if pkfield in kwargs:
try:
return self.model.objects.get(pk=kwargs.get(pkfield))
except ObjectDoesNotExist:
return rc.NOT_FOUND
except MultipleObjectsReturned: # should never happen, since we're using a PK
return rc.BAD_REQUEST
else:
return self.model.objects.filter(*args, **kwargs)
def create(self, request, *args, **kwargs):
if not self.has_model():
return rc.NOT_IMPLEMENTED
attrs = self.flatten_dict(request.POST)
try:
inst = self.model.objects.get(**attrs)
return rc.DUPLICATE_ENTRY
except self.model.DoesNotExist:
inst = self.model(**attrs)
inst.save()
return inst
except self.model.MultipleObjectsReturned:
return rc.DUPLICATE_ENTRY
def update(self, request, *args, **kwargs):
# TODO: This doesn't work automatically yet.
return rc.NOT_IMPLEMENTED
def delete(self, request, *args, **kwargs):
if not self.has_model():
raise NotImplementedError
try:
inst = self.model.objects.get(*args, **kwargs)
inst.delete()
return rc.DELETED
except self.model.MultipleObjectsReturned:
return rc.DUPLICATE_ENTRY
except self.model.DoesNotExist:
return rc.NOT_HERE
class AnonymousBaseHandler(BaseHandler):
"""
Anonymous handler.
"""
is_anonymous = True
allowed_methods = ('GET',)
|
zzz-game-prototype
|
trunk/django-piston/piston/handler.py
|
Python
|
bsd
| 3,340
|
import sys, inspect
from django.http import (HttpResponse, Http404, HttpResponseNotAllowed,
HttpResponseForbidden, HttpResponseServerError)
from django.views.debug import ExceptionReporter
from django.views.decorators.vary import vary_on_headers
from django.conf import settings
from django.core.mail import send_mail, EmailMessage
from emitters import Emitter
from handler import typemapper
from doc import HandlerMethod
from authentication import NoAuthentication
from utils import coerce_put_post, FormValidationError, HttpStatusCode
from utils import rc, format_error, translate_mime, MimerDataException
class Resource(object):
"""
Resource. Create one for your URL mappings, just
like you would with Django. Takes one argument,
the handler. The second argument is optional, and
is an authentication handler. If not specified,
`NoAuthentication` will be used by default.
"""
callmap = { 'GET': 'read', 'POST': 'create',
'PUT': 'update', 'DELETE': 'delete' }
def __init__(self, handler, authentication=None):
if not callable(handler):
raise AttributeError, "Handler not callable."
self.handler = handler()
if not authentication:
self.authentication = NoAuthentication()
else:
self.authentication = authentication
# Erroring
self.email_errors = getattr(settings, 'PISTON_EMAIL_ERRORS', True)
self.display_errors = getattr(settings, 'PISTON_DISPLAY_ERRORS', True)
self.stream = getattr(settings, 'PISTON_STREAM_OUTPUT', False)
def determine_emitter(self, request, *args, **kwargs):
"""
Function for determening which emitter to use
for output. It lives here so you can easily subclass
`Resource` in order to change how emission is detected.
You could also check for the `Accept` HTTP header here,
since that pretty much makes sense. Refer to `Mimer` for
that as well.
"""
em = kwargs.pop('emitter_format', None)
if not em:
em = request.GET.get('format', 'json')
return em
@vary_on_headers('Authorization')
def __call__(self, request, *args, **kwargs):
"""
NB: Sends a `Vary` header so we don't cache requests
that are different (OAuth stuff in `Authorization` header.)
"""
rm = request.method.upper()
# Django's internal mechanism doesn't pick up
# PUT request, so we trick it a little here.
if rm == "PUT":
coerce_put_post(request)
if not self.authentication.is_authenticated(request):
if hasattr(self.handler, 'anonymous') and \
callable(self.handler.anonymous) and \
rm in self.handler.anonymous.allowed_methods:
handler = self.handler.anonymous()
anonymous = True
else:
return self.authentication.challenge()
else:
handler = self.handler
anonymous = handler.is_anonymous
# Translate nested datastructs into `request.data` here.
if rm in ('POST', 'PUT'):
try:
translate_mime(request)
except MimerDataException:
return rc.BAD_REQUEST
if not rm in handler.allowed_methods:
return HttpResponseNotAllowed(handler.allowed_methods)
meth = getattr(handler, self.callmap.get(rm), None)
if not meth:
raise Http404
# Support emitter both through (?P<emitter_format>) and ?format=emitter.
em_format = self.determine_emitter(request, *args, **kwargs)
kwargs.pop('emitter_format', None)
# Clean up the request object a bit, since we might
# very well have `oauth_`-headers in there, and we
# don't want to pass these along to the handler.
request = self.cleanup_request(request)
try:
result = meth(request, *args, **kwargs)
except FormValidationError, e:
# TODO: Use rc.BAD_REQUEST here
return HttpResponse("Bad Request: %s" % e.form.errors, status=400)
except TypeError, e:
result = rc.BAD_REQUEST
hm = HandlerMethod(meth)
sig = hm.get_signature()
msg = 'Method signature does not match.\n\n'
if sig:
msg += 'Signature should be: %s' % sig
else:
msg += 'Resource does not expect any parameters.'
if self.display_errors:
msg += '\n\nException was: %s' % str(e)
result.content = format_error(msg)
except HttpStatusCode, e:
#result = e ## why is this being passed on and not just dealt with now?
return e.response
except Exception, e:
"""
On errors (like code errors), we'd like to be able to
give crash reports to both admins and also the calling
user. There's two setting parameters for this:
Parameters::
- `PISTON_EMAIL_ERRORS`: Will send a Django formatted
error email to people in `settings.ADMINS`.
- `PISTON_DISPLAY_ERRORS`: Will return a simple traceback
to the caller, so he can tell you what error they got.
If `PISTON_DISPLAY_ERRORS` is not enabled, the caller will
receive a basic "500 Internal Server Error" message.
"""
exc_type, exc_value, tb = sys.exc_info()
rep = ExceptionReporter(request, exc_type, exc_value, tb.tb_next)
if self.email_errors:
self.email_exception(rep)
if self.display_errors:
return HttpResponseServerError(
format_error('\n'.join(rep.format_exception())))
else:
raise
emitter, ct = Emitter.get(em_format)
srl = emitter(result, typemapper, handler, handler.fields, anonymous)
try:
"""
Decide whether or not we want a generator here,
or we just want to buffer up the entire result
before sending it to the client. Won't matter for
smaller datasets, but larger will have an impact.
"""
if self.stream: stream = srl.stream_render(request)
else: stream = srl.render(request)
resp = HttpResponse(stream, mimetype=ct)
resp.streaming = self.stream
return resp
except HttpStatusCode, e:
return e.response
@staticmethod
def cleanup_request(request):
"""
Removes `oauth_` keys from various dicts on the
request object, and returns the sanitized version.
"""
for method_type in ('GET', 'PUT', 'POST', 'DELETE'):
block = getattr(request, method_type, { })
if True in [ k.startswith("oauth_") for k in block.keys() ]:
sanitized = block.copy()
for k in sanitized.keys():
if k.startswith("oauth_"):
sanitized.pop(k)
setattr(request, method_type, sanitized)
return request
# --
def email_exception(self, reporter):
subject = "Piston crash report"
html = reporter.get_traceback_html()
message = EmailMessage(settings.EMAIL_SUBJECT_PREFIX+subject,
html, settings.SERVER_EMAIL,
[ admin[1] for admin in settings.ADMINS ])
message.content_subtype = 'html'
message.send(fail_silently=True)
|
zzz-game-prototype
|
trunk/django-piston/piston/resource.py
|
Python
|
bsd
| 7,911
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Authorize Token</title>
</head>
<body>
<h1>Authorize Token</h1>
<form action="{% url piston.authentication.oauth_user_auth %}" method="POST">
{{ form.as_table }}
</form>
</body>
</html>
|
zzz-game-prototype
|
trunk/django-piston/piston/templates/piston/authorize_token.html
|
HTML
|
bsd
| 338
|
{% load markup %}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
Piston generated documentation
</title>
<style type="text/css">
body {
background: #fffff0;
font: 1em "Helvetica Neue", Verdana;
padding: 0 0 0 25px;
}
</style>
</head>
<body>
<h1>API Documentation</h1>
{% for doc in docs %}
<h3>{{ doc.name|cut:"Handler" }}:</h3>
<p>
{{ doc.get_doc|default:""|restructuredtext }}
</p>
<p>
URL: <b>{{ doc.get_resource_uri_template }}</b>
</p>
<p>
Accepted methods: {% for meth in doc.allowed_methods %}<b>{{ meth }}</b>{% if not forloop.last %}, {% endif %}{% endfor %}
</p>
<dl>
{% for method in doc.get_all_methods %}
<dt>
method <i>{{ method.name }}</i>({{ method.signature }}){% if method.stale %} <i>- inherited</i>{% else %}:{% endif %}
</dt>
{% if method.get_doc %}
<dd>
{{ method.get_doc|default:""|restructuredtext }}
<dd>
{% endif %}
{% endfor %}
</dl>
{% endfor %}
</body>
</html>
|
zzz-game-prototype
|
trunk/django-piston/piston/templates/documentation.html
|
HTML
|
bsd
| 1,143
|
from __future__ import generators
import decimal, re, inspect
try:
# yaml isn't standard with python. It shouldn't be required if it
# isn't used.
import yaml
except ImportError:
yaml = None
# Fallback since `any` isn't in Python <2.5
try:
any
except NameError:
def any(iterable):
for element in iterable:
if element:
return True
return False
from django.db.models.query import QuerySet
from django.db.models import Model, permalink
from django.utils import simplejson
from django.utils.xmlutils import SimplerXMLGenerator
from django.utils.encoding import smart_unicode
from django.core.serializers.json import DateTimeAwareJSONEncoder
from django.http import HttpResponse
from django.core import serializers
from utils import HttpStatusCode, Mimer
try:
import cStringIO as StringIO
except ImportError:
import StringIO
try:
import cPickle as pickle
except ImportError:
import pickle
class Emitter(object):
"""
Super emitter. All other emitters should subclass
this one. It has the `construct` method which
conveniently returns a serialized `dict`. This is
usually the only method you want to use in your
emitter. See below for examples.
"""
EMITTERS = { }
def __init__(self, payload, typemapper, handler, fields=(), anonymous=True):
self.typemapper = typemapper
self.data = payload
self.handler = handler
self.fields = fields
self.anonymous = anonymous
if isinstance(self.data, Exception):
raise
def method_fields(self, data, fields):
if not data:
return { }
has = dir(data)
ret = dict()
for field in fields:
if field in has:
ret[field] = getattr(data, field)
return ret
def construct(self):
"""
Recursively serialize a lot of types, and
in cases where it doesn't recognize the type,
it will fall back to Django's `smart_unicode`.
Returns `dict`.
"""
def _any(thing, fields=()):
"""
Dispatch, all types are routed through here.
"""
ret = None
if isinstance(thing, QuerySet):
ret = _qs(thing, fields=fields)
elif isinstance(thing, (tuple, list)):
ret = _list(thing)
elif isinstance(thing, dict):
ret = _dict(thing)
elif isinstance(thing, decimal.Decimal):
ret = str(thing)
elif isinstance(thing, Model):
ret = _model(thing, fields=fields)
elif isinstance(thing, HttpResponse):
raise HttpStatusCode(thing)
elif inspect.isfunction(thing):
if not inspect.getargspec(thing)[0]:
ret = _any(thing())
elif hasattr(thing, '__emittable__'):
f = thing.__emittable__
if inspect.ismethod(f) and len(inspect.getargspec(f)[0]) == 1:
ret = _any(f())
else:
ret = smart_unicode(thing, strings_only=True)
return ret
def _fk(data, field):
"""
Foreign keys.
"""
return _any(getattr(data, field.name))
def _related(data, fields=()):
"""
Foreign keys.
"""
return [ _model(m, fields) for m in data.iterator() ]
def _m2m(data, field, fields=()):
"""
Many to many (re-route to `_model`.)
"""
return [ _model(m, fields) for m in getattr(data, field.name).iterator() ]
def _model(data, fields=()):
"""
Models. Will respect the `fields` and/or
`exclude` on the handler (see `typemapper`.)
"""
ret = { }
handler = self.in_typemapper(type(data), self.anonymous)
get_absolute_uri = False
if handler or fields:
v = lambda f: getattr(data, f.attname)
if not fields:
"""
Fields was not specified, try to find teh correct
version in the typemapper we were sent.
"""
mapped = self.in_typemapper(type(data), self.anonymous)
get_fields = set(mapped.fields)
exclude_fields = set(mapped.exclude).difference(get_fields)
if 'absolute_uri' in get_fields:
get_absolute_uri = True
if not get_fields:
get_fields = set([ f.attname.replace("_id", "", 1)
for f in data._meta.fields ])
# sets can be negated.
for exclude in exclude_fields:
if isinstance(exclude, basestring):
get_fields.discard(exclude)
elif isinstance(exclude, re._pattern_type):
for field in get_fields.copy():
if exclude.match(field):
get_fields.discard(field)
else:
get_fields = set(fields)
met_fields = self.method_fields(handler, get_fields)
for f in data._meta.local_fields:
if f.serialize and not any([ p in met_fields for p in [ f.attname, f.name ]]):
if not f.rel:
if f.attname in get_fields:
ret[f.attname] = _any(v(f))
get_fields.remove(f.attname)
else:
if f.attname[:-3] in get_fields:
ret[f.name] = _fk(data, f)
get_fields.remove(f.name)
for mf in data._meta.many_to_many:
if mf.serialize and mf.attname not in met_fields:
if mf.attname in get_fields:
ret[mf.name] = _m2m(data, mf)
get_fields.remove(mf.name)
# try to get the remainder of fields
for maybe_field in get_fields:
if isinstance(maybe_field, (list, tuple)):
model, fields = maybe_field
inst = getattr(data, model, None)
if inst:
if hasattr(inst, 'all'):
ret[model] = _related(inst, fields)
elif callable(inst):
if len(inspect.getargspec(inst)[0]) == 1:
ret[model] = _any(inst(), fields)
else:
ret[model] = _model(inst, fields)
elif maybe_field in met_fields:
# Overriding normal field which has a "resource method"
# so you can alter the contents of certain fields without
# using different names.
ret[maybe_field] = _any(met_fields[maybe_field](data))
else:
maybe = getattr(data, maybe_field, None)
if maybe:
if callable(maybe):
if len(inspect.getargspec(maybe)[0]) == 1:
ret[maybe_field] = _any(maybe())
else:
ret[maybe_field] = _any(maybe)
else:
handler_f = getattr(handler or self.handler, maybe_field, None)
if handler_f:
ret[maybe_field] = _any(handler_f(data))
else:
for f in data._meta.fields:
ret[f.attname] = _any(getattr(data, f.attname))
fields = dir(data.__class__) + ret.keys()
add_ons = [k for k in dir(data) if k not in fields]
for k in add_ons:
ret[k] = _any(getattr(data, k))
# resouce uri
if self.in_typemapper(type(data), self.anonymous):
handler = self.in_typemapper(type(data), self.anonymous)
if hasattr(handler, 'resource_uri'):
url_id, fields = handler.resource_uri()
ret['resource_uri'] = permalink( lambda: (url_id,
(getattr(data, f) for f in fields) ) )()
if hasattr(data, 'get_api_url') and 'resource_uri' not in ret:
try: ret['resource_uri'] = data.get_api_url()
except: pass
# absolute uri
if hasattr(data, 'get_absolute_url') and get_absolute_uri:
try: ret['absolute_uri'] = data.get_absolute_url()
except: pass
return ret
def _qs(data, fields=()):
"""
Querysets.
"""
return [ _any(v, fields) for v in data ]
def _list(data):
"""
Lists.
"""
return [ _any(v) for v in data ]
def _dict(data):
"""
Dictionaries.
"""
return dict([ (k, _any(v)) for k, v in data.iteritems() ])
# Kickstart the seralizin'.
return _any(self.data, self.fields)
def in_typemapper(self, model, anonymous):
for klass, (km, is_anon) in self.typemapper.iteritems():
if model is km and is_anon is anonymous:
return klass
def render(self):
"""
This super emitter does not implement `render`,
this is a job for the specific emitter below.
"""
raise NotImplementedError("Please implement render.")
def stream_render(self, request, stream=True):
"""
Tells our patched middleware not to look
at the contents, and returns a generator
rather than the buffered string. Should be
more memory friendly for large datasets.
"""
yield self.render(request)
@classmethod
def get(cls, format):
"""
Gets an emitter, returns the class and a content-type.
"""
if cls.EMITTERS.has_key(format):
return cls.EMITTERS.get(format)
raise ValueError("No emitters found for type %s" % format)
@classmethod
def register(cls, name, klass, content_type='text/plain'):
"""
Register an emitter.
Parameters::
- `name`: The name of the emitter ('json', 'xml', 'yaml', ...)
- `klass`: The emitter class.
- `content_type`: The content type to serve response as.
"""
cls.EMITTERS[name] = (klass, content_type)
@classmethod
def unregister(cls, name):
"""
Remove an emitter from the registry. Useful if you don't
want to provide output in one of the built-in emitters.
"""
return cls.EMITTERS.pop(name, None)
class XMLEmitter(Emitter):
def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
xml.startElement("resource", {})
self._to_xml(xml, item)
xml.endElement("resource")
elif isinstance(data, dict):
for key, value in data.iteritems():
xml.startElement(key, {})
self._to_xml(xml, value)
xml.endElement(key)
else:
xml.characters(smart_unicode(data))
def render(self, request):
stream = StringIO.StringIO()
xml = SimplerXMLGenerator(stream, "utf-8")
xml.startDocument()
xml.startElement("response", {})
self._to_xml(xml, self.construct())
xml.endElement("response")
xml.endDocument()
return stream.getvalue()
Emitter.register('xml', XMLEmitter, 'text/xml; charset=utf-8')
Mimer.register(lambda *a: None, ('text/xml',))
class JSONEmitter(Emitter):
"""
JSON emitter, understands timestamps.
"""
def render(self, request):
cb = request.GET.get('callback')
seria = simplejson.dumps(self.construct(), cls=DateTimeAwareJSONEncoder, ensure_ascii=False, indent=4)
# Callback
if cb:
return '%s(%s)' % (cb, seria)
return seria
Emitter.register('json', JSONEmitter, 'application/json; charset=utf-8')
Mimer.register(simplejson.loads, ('application/json',))
class YAMLEmitter(Emitter):
"""
YAML emitter, uses `safe_dump` to omit the
specific types when outputting to non-Python.
"""
def render(self, request):
return yaml.safe_dump(self.construct())
if yaml: # Only register yaml if it was import successfully.
Emitter.register('yaml', YAMLEmitter, 'application/x-yaml; charset=utf-8')
Mimer.register(yaml.load, ('application/x-yaml',))
class PickleEmitter(Emitter):
"""
Emitter that returns Python pickled.
"""
def render(self, request):
return pickle.dumps(self.construct())
Emitter.register('pickle', PickleEmitter, 'application/python-pickle')
Mimer.register(pickle.loads, ('application/python-pickle',))
class DjangoEmitter(Emitter):
"""
Emitter for the Django serialized format.
"""
def render(self, request, format='xml'):
if isinstance(self.data, HttpResponse):
return self.data
elif isinstance(self.data, (int, str)):
response = self.data
else:
response = serializers.serialize(format, self.data, indent=True)
return response
Emitter.register('django', DjangoEmitter, 'text/xml; charset=utf-8')
|
zzz-game-prototype
|
trunk/django-piston/piston/emitters.py
|
Python
|
bsd
| 14,442
|
import urllib
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from django.conf import settings
from django.core.mail import send_mail, mail_admins
from django.template import loader
from managers import TokenManager, ConsumerManager, ResourceManager
KEY_SIZE = 18
SECRET_SIZE = 32
CONSUMER_STATES = (
('pending', 'Pending approval'),
('accepted', 'Accepted'),
('canceled', 'Canceled'),
)
class Nonce(models.Model):
token_key = models.CharField(max_length=KEY_SIZE)
consumer_key = models.CharField(max_length=KEY_SIZE)
key = models.CharField(max_length=255)
def __unicode__(self):
return u"Nonce %s for %s" % (self.key, self.consumer_key)
admin.site.register(Nonce)
class Resource(models.Model):
name = models.CharField(max_length=255)
url = models.TextField(max_length=2047)
is_readonly = models.BooleanField(default=True)
objects = ResourceManager()
def __unicode__(self):
return u"Resource %s with url %s" % (self.name, self.url)
admin.site.register(Resource)
class Consumer(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
key = models.CharField(max_length=KEY_SIZE)
secret = models.CharField(max_length=SECRET_SIZE)
status = models.CharField(max_length=16, choices=CONSUMER_STATES, default='pending')
user = models.ForeignKey(User, null=True, blank=True, related_name='consumers')
objects = ConsumerManager()
def __unicode__(self):
return u"Consumer %s with key %s" % (self.name, self.key)
def generate_random_codes(self):
key = User.objects.make_random_password(length=KEY_SIZE)
secret = User.objects.make_random_password(length=SECRET_SIZE)
while Consumer.objects.filter(key__exact=key, secret__exact=secret).count():
secret = User.objects.make_random_password(length=SECRET_SIZE)
self.key = key
self.secret = secret
self.save()
# --
def save(self, **kwargs):
super(Consumer, self).save(**kwargs)
if self.id and self.user:
subject = "API Consumer"
rcpt = [ self.user.email, ]
if self.status == "accepted":
template = "api/mails/consumer_accepted.txt"
subject += " was accepted!"
elif self.status == "canceled":
template = "api/mails/consumer_canceled.txt"
subject += " has been canceled"
else:
template = "api/mails/consumer_pending.txt"
subject += " application received"
for admin in settings.ADMINS:
bcc.append(admin[1])
body = loader.render_to_string(template,
{ 'consumer': self, 'user': self.user })
send_mail(subject, body, settings.DEFAULT_FROM_EMAIL,
rcpt, fail_silently=True)
if self.status == 'pending':
mail_admins(subject, body, fail_silently=True)
if settings.DEBUG:
print "Mail being sent, to=%s" % rcpt
print "Subject: %s" % subject
print body
admin.site.register(Consumer)
class Token(models.Model):
REQUEST = 1
ACCESS = 2
TOKEN_TYPES = ((REQUEST, u'Request'), (ACCESS, u'Access'))
key = models.CharField(max_length=KEY_SIZE)
secret = models.CharField(max_length=SECRET_SIZE)
token_type = models.IntegerField(choices=TOKEN_TYPES)
timestamp = models.IntegerField()
is_approved = models.BooleanField(default=False)
user = models.ForeignKey(User, null=True, blank=True, related_name='tokens')
consumer = models.ForeignKey(Consumer)
objects = TokenManager()
def __unicode__(self):
return u"%s Token %s for %s" % (self.get_token_type_display(), self.key, self.consumer)
def to_string(self, only_key=False):
token_dict = {
'oauth_token': self.key,
'oauth_token_secret': self.secret
}
if only_key:
del token_dict['oauth_token_secret']
return urllib.urlencode(token_dict)
def generate_random_codes(self):
key = User.objects.make_random_password(length=KEY_SIZE)
secret = User.objects.make_random_password(length=SECRET_SIZE)
while Token.objects.filter(key__exact=key, secret__exact=secret).count():
secret = User.objects.make_random_password(length=SECRET_SIZE)
self.key = key
self.secret = secret
self.save()
admin.site.register(Token)
|
zzz-game-prototype
|
trunk/django-piston/piston/models.py
|
Python
|
bsd
| 4,747
|
import cgi
import urllib
import time
import random
import urlparse
import hmac
import base64
VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
# Generic exception class
class OAuthError(RuntimeError):
def get_message(self):
return self._message
def set_message(self, message):
self._message = message
message = property(get_message, set_message)
def __init__(self, message='OAuth error occured.'):
self.message = message
# optional WWW-Authenticate header (401 error)
def build_authenticate_header(realm=''):
return { 'WWW-Authenticate': 'OAuth realm="%s"' % realm }
# url escape
def escape(s):
# escape '/' too
return urllib.quote(s, safe='~')
# util function: current timestamp
# seconds since epoch (UTC)
def generate_timestamp():
return int(time.time())
# util function: nonce
# pseudorandom number
def generate_nonce(length=8):
return ''.join(str(random.randint(0, 9)) for i in range(length))
# OAuthConsumer is a data type that represents the identity of the Consumer
# via its shared secret with the Service Provider.
class OAuthConsumer(object):
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
# OAuthToken is a data type that represents an End User via either an access
# or request token.
class OAuthToken(object):
# access tokens and request tokens
key = None
secret = None
'''
key = the token
secret = the token secret
'''
def __init__(self, key, secret):
self.key = key
self.secret = secret
def to_string(self):
return urllib.urlencode({'oauth_token': self.key, 'oauth_token_secret': self.secret})
# return a token from something like:
# oauth_token_secret=digg&oauth_token=digg
@staticmethod
def from_string(s):
params = cgi.parse_qs(s, keep_blank_values=False)
key = params['oauth_token'][0]
secret = params['oauth_token_secret'][0]
return OAuthToken(key, secret)
def __str__(self):
return self.to_string()
# OAuthRequest represents the request and can be serialized
class OAuthRequest(object):
'''
OAuth parameters:
- oauth_consumer_key
- oauth_token
- oauth_signature_method
- oauth_signature
- oauth_timestamp
- oauth_nonce
- oauth_version
... any additional parameters, as defined by the Service Provider.
'''
parameters = None # oauth parameters
http_method = HTTP_METHOD
http_url = None
version = VERSION
def __init__(self, http_method=HTTP_METHOD, http_url=None, parameters=None):
self.http_method = http_method
self.http_url = http_url
self.parameters = parameters or {}
def set_parameter(self, parameter, value):
self.parameters[parameter] = value
def get_parameter(self, parameter):
try:
return self.parameters[parameter]
except:
raise OAuthError('Parameter not found: %s' % parameter)
def _get_timestamp_nonce(self):
return self.get_parameter('oauth_timestamp'), self.get_parameter('oauth_nonce')
# get any non-oauth parameters
def get_nonoauth_parameters(self):
parameters = {}
for k, v in self.parameters.iteritems():
# ignore oauth parameters
if k.find('oauth_') < 0:
parameters[k] = v
return parameters
# serialize as a header for an HTTPAuth request
def to_header(self, realm=''):
auth_header = 'OAuth realm="%s"' % realm
# add the oauth parameters
if self.parameters:
for k, v in self.parameters.iteritems():
auth_header += ', %s="%s"' % (k, escape(str(v)))
return {'Authorization': auth_header}
# serialize as post data for a POST request
def to_postdata(self):
return '&'.join('%s=%s' % (escape(str(k)), escape(str(v))) for k, v in self.parameters.iteritems())
# serialize as a url for a GET request
def to_url(self):
return '%s?%s' % (self.get_normalized_http_url(), self.to_postdata())
# return a string that consists of all the parameters that need to be signed
def get_normalized_parameters(self):
params = self.parameters
try:
# exclude the signature if it exists
del params['oauth_signature']
except:
pass
key_values = params.items()
# sort lexicographically, first after key, then after value
key_values.sort()
# combine key value pairs in string and escape
return '&'.join('%s=%s' % (escape(str(k)), escape(str(v))) for k, v in key_values)
# just uppercases the http method
def get_normalized_http_method(self):
return self.http_method.upper()
# parses the url and rebuilds it to be scheme://host/path
def get_normalized_http_url(self):
parts = urlparse.urlparse(self.http_url)
url_string = '%s://%s%s' % (parts[0], parts[1], parts[2]) # scheme, netloc, path
return url_string
# set the signature parameter to the result of build_signature
def sign_request(self, signature_method, consumer, token):
# set the signature method
self.set_parameter('oauth_signature_method', signature_method.get_name())
# set the signature
self.set_parameter('oauth_signature', self.build_signature(signature_method, consumer, token))
def build_signature(self, signature_method, consumer, token):
# call the build signature method within the signature method
return signature_method.build_signature(self, consumer, token)
@staticmethod
def from_request(http_method, http_url, headers=None, parameters=None, query_string=None):
# combine multiple parameter sources
if parameters is None:
parameters = {}
# headers
if headers and 'HTTP_AUTHORIZATION' in headers:
auth_header = headers['HTTP_AUTHORIZATION']
# check that the authorization header is OAuth
if auth_header.index('OAuth') > -1:
try:
# get the parameters from the header
header_params = OAuthRequest._split_header(auth_header)
parameters.update(header_params)
except:
raise OAuthError('Unable to parse OAuth parameters from Authorization header.')
# GET or POST query string
if query_string:
query_params = OAuthRequest._split_url_string(query_string)
parameters.update(query_params)
# URL parameters
param_str = urlparse.urlparse(http_url)[4] # query
url_params = OAuthRequest._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return OAuthRequest(http_method, http_url, parameters)
return None
@staticmethod
def from_consumer_and_token(oauth_consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': oauth_consumer.key,
'oauth_timestamp': generate_timestamp(),
'oauth_nonce': generate_nonce(),
'oauth_version': OAuthRequest.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
return OAuthRequest(http_method, http_url, parameters)
@staticmethod
def from_token_and_callback(token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = escape(callback)
return OAuthRequest(http_method, http_url, parameters)
# util function: turn Authorization: header into parameters, has to do some unescaping
@staticmethod
def _split_header(header):
params = {}
parts = header.split(',')
for param in parts:
# ignore realm parameter
if param.find('OAuth realm') > -1:
continue
# remove whitespace
param = param.strip()
# split key-value
param_parts = param.split('=', 1)
# remove quotes and unescape the value
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
# util function: turn url string into parameters, has to do some unescaping
@staticmethod
def _split_url_string(param_str):
parameters = cgi.parse_qs(param_str, keep_blank_values=False)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
# OAuthServer is a worker to check a requests validity against a data store
class OAuthServer(object):
timestamp_threshold = 300 # in seconds, five minutes
version = VERSION
signature_methods = None
data_store = None
def __init__(self, data_store=None, signature_methods=None):
self.data_store = data_store
self.signature_methods = signature_methods or {}
def set_data_store(self, oauth_data_store):
self.data_store = data_store
def get_data_store(self):
return self.data_store
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.get_name()] = signature_method
return self.signature_methods
# process a request_token request
# returns the request token on success
def fetch_request_token(self, oauth_request):
try:
# get the request token for authorization
token = self._get_token(oauth_request, 'request')
except OAuthError:
# no token required for the initial token request
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
self._check_signature(oauth_request, consumer, None)
# fetch a new token
token = self.data_store.fetch_request_token(consumer)
return token
# process an access_token request
# returns the access token on success
def fetch_access_token(self, oauth_request):
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
# get the request token
token = self._get_token(oauth_request, 'request')
self._check_signature(oauth_request, consumer, token)
new_token = self.data_store.fetch_access_token(consumer, token)
return new_token
# verify an api call, checks all the parameters
def verify_request(self, oauth_request):
# -> consumer and token
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
# get the access token
token = self._get_token(oauth_request, 'access')
self._check_signature(oauth_request, consumer, token)
parameters = oauth_request.get_nonoauth_parameters()
return consumer, token, parameters
# authorize a request token
def authorize_token(self, token, user):
return self.data_store.authorize_request_token(token, user)
# get the callback url
def get_callback(self, oauth_request):
return oauth_request.get_parameter('oauth_callback')
# optional support for the authenticate header
def build_authenticate_header(self, realm=''):
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
# verify the correct version request for this server
def _get_version(self, oauth_request):
try:
version = oauth_request.get_parameter('oauth_version')
except:
version = VERSION
if version and version != self.version:
raise OAuthError('OAuth version %s not supported.' % str(version))
return version
# figure out the signature with some defaults
def _get_signature_method(self, oauth_request):
try:
signature_method = oauth_request.get_parameter('oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# get the signature method object
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise OAuthError('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_consumer(self, oauth_request):
consumer_key = oauth_request.get_parameter('oauth_consumer_key')
if not consumer_key:
raise OAuthError('Invalid consumer key.')
consumer = self.data_store.lookup_consumer(consumer_key)
if not consumer:
raise OAuthError('Invalid consumer.')
return consumer
# try to find the token for the provided request token key
def _get_token(self, oauth_request, token_type='access'):
token_field = oauth_request.get_parameter('oauth_token')
token = self.data_store.lookup_token(token_type, token_field)
if not token:
raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
return token
def _check_signature(self, oauth_request, consumer, token):
timestamp, nonce = oauth_request._get_timestamp_nonce()
self._check_timestamp(timestamp)
self._check_nonce(consumer, token, nonce)
signature_method = self._get_signature_method(oauth_request)
try:
signature = oauth_request.get_parameter('oauth_signature')
except:
raise OAuthError('Missing signature.')
# validate the signature
valid_sig = signature_method.check_signature(oauth_request, consumer, token, signature)
if not valid_sig:
key, base = signature_method.build_signature_base_string(oauth_request, consumer, token)
raise OAuthError('Invalid signature. Expected signature base string: %s' % base)
built = signature_method.build_signature(oauth_request, consumer, token)
def _check_timestamp(self, timestamp):
# verify that timestamp is recentish
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise OAuthError('Expired timestamp: given %d and now %s has a greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold))
def _check_nonce(self, consumer, token, nonce):
# verify that the nonce is uniqueish
nonce = self.data_store.lookup_nonce(consumer, token, nonce)
if nonce:
raise OAuthError('Nonce already used: %s' % str(nonce))
# OAuthClient is a worker to attempt to execute a request
class OAuthClient(object):
consumer = None
token = None
def __init__(self, oauth_consumer, oauth_token):
self.consumer = oauth_consumer
self.token = oauth_token
def get_consumer(self):
return self.consumer
def get_token(self):
return self.token
def fetch_request_token(self, oauth_request):
# -> OAuthToken
raise NotImplementedError
def fetch_access_token(self, oauth_request):
# -> OAuthToken
raise NotImplementedError
def access_resource(self, oauth_request):
# -> some protected resource
raise NotImplementedError
# OAuthDataStore is a database abstraction used to lookup consumers and tokens
class OAuthDataStore(object):
def lookup_consumer(self, key):
# -> OAuthConsumer
raise NotImplementedError
def lookup_token(self, oauth_consumer, token_type, token_token):
# -> OAuthToken
raise NotImplementedError
def lookup_nonce(self, oauth_consumer, oauth_token, nonce, timestamp):
# -> OAuthToken
raise NotImplementedError
def fetch_request_token(self, oauth_consumer):
# -> OAuthToken
raise NotImplementedError
def fetch_access_token(self, oauth_consumer, oauth_token):
# -> OAuthToken
raise NotImplementedError
def authorize_request_token(self, oauth_token, user):
# -> OAuthToken
raise NotImplementedError
# OAuthSignatureMethod is a strategy class that implements a signature method
class OAuthSignatureMethod(object):
def get_name(self):
# -> str
raise NotImplementedError
def build_signature_base_string(self, oauth_request, oauth_consumer, oauth_token):
# -> str key, str raw
raise NotImplementedError
def build_signature(self, oauth_request, oauth_consumer, oauth_token):
# -> str
raise NotImplementedError
def check_signature(self, oauth_request, consumer, token, signature):
built = self.build_signature(oauth_request, consumer, token)
return built == signature
class OAuthSignatureMethod_HMAC_SHA1(OAuthSignatureMethod):
def get_name(self):
return 'HMAC-SHA1'
def build_signature_base_string(self, oauth_request, consumer, token):
sig = (
escape(oauth_request.get_normalized_http_method()),
escape(oauth_request.get_normalized_http_url()),
escape(oauth_request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
raw = '&'.join(sig)
return key, raw
def build_signature(self, oauth_request, consumer, token):
# build the base signature string
key, raw = self.build_signature_base_string(oauth_request, consumer, token)
# hmac object
try:
import hashlib # 2.5
hashed = hmac.new(key, raw, hashlib.sha1)
except:
import sha # deprecated
hashed = hmac.new(key, raw, sha)
# calculate the digest base 64
return base64.b64encode(hashed.digest())
class OAuthSignatureMethod_PLAINTEXT(OAuthSignatureMethod):
def get_name(self):
return 'PLAINTEXT'
def build_signature_base_string(self, oauth_request, consumer, token):
# concatenate the consumer key and secret
sig = escape(consumer.secret) + '&'
if token:
sig = sig + escape(token.secret)
return sig
def build_signature(self, oauth_request, consumer, token):
return self.build_signature_base_string(oauth_request, consumer, token)
|
zzz-game-prototype
|
trunk/django-piston/piston/oauth.py
|
Python
|
bsd
| 18,804
|
from django.db import models
from django.contrib.auth.models import User
KEY_SIZE = 16
SECRET_SIZE = 16
class ConsumerManager(models.Manager):
def create_consumer(self, name, description=None, user=None):
"""
Shortcut to create a consumer with random key/secret.
"""
consumer, created = self.get_or_create(name=name)
if user:
consumer.user = user
if description:
consumer.description = description
if created:
consumer.generate_random_codes()
return consumer
_default_consumer = None
class ResourceManager(models.Manager):
_default_resource = None
def get_default_resource(self, name):
"""
Add cache if you use a default resource.
"""
if not self._default_resource:
self._default_resource = self.get(name=name)
return self._default_resource
class TokenManager(models.Manager):
def create_token(self, consumer, token_type, timestamp, user=None):
"""
Shortcut to create a token with random key/secret.
"""
token, created = self.get_or_create(consumer=consumer,
token_type=token_type,
timestamp=timestamp,
user=user)
if created:
token.generate_random_codes()
return token
|
zzz-game-prototype
|
trunk/django-piston/piston/managers.py
|
Python
|
bsd
| 1,459
|
import oauth
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.auth.decorators import login_required
from django.template import loader
from django.contrib.auth import authenticate
from django.conf import settings
from django.core.urlresolvers import get_callable
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import render_to_response
from django.template import RequestContext
from piston import forms
class NoAuthentication(object):
"""
Authentication handler that always returns
True, so no authentication is needed, nor
initiated (`challenge` is missing.)
"""
def is_authenticated(self, request):
return True
class HttpBasicAuthentication(object):
"""
Basic HTTP authenticater. Synopsis:
Authentication handlers must implement two methods:
- `is_authenticated`: Will be called when checking for
authentication. Receives a `request` object, please
set your `User` object on `request.user`, otherwise
return False (or something that evaluates to False.)
- `challenge`: In cases where `is_authenticated` returns
False, the result of this method will be returned.
This will usually be a `HttpResponse` object with
some kind of challenge headers and 401 code on it.
"""
def __init__(self, auth_func=authenticate, realm='API'):
self.auth_func = auth_func
self.realm = realm
def is_authenticated(self, request):
auth_string = request.META.get('HTTP_AUTHORIZATION', None)
if not auth_string:
return False
(authmeth, auth) = auth_string.split(" ", 1)
if not authmeth.lower() == 'basic':
return False
auth = auth.strip().decode('base64')
(username, password) = auth.split(':', 1)
request.user = self.auth_func(username=username, password=password) \
or AnonymousUser()
return not request.user in (False, None, AnonymousUser())
def challenge(self):
resp = HttpResponse("Authorization Required")
resp['WWW-Authenticate'] = 'Basic realm="%s"' % self.realm
resp.status_code = 401
return resp
def load_data_store():
'''Load data store for OAuth Consumers, Tokens, Nonces and Resources
'''
path = getattr(settings, 'OAUTH_DATA_STORE', 'piston.store.DataStore')
# stolen from django.contrib.auth.load_backend
i = path.rfind('.')
module, attr = path[:i], path[i+1:]
try:
mod = __import__(module, {}, {}, attr)
except ImportError, e:
raise ImproperlyConfigured, 'Error importing OAuth data store %s: "%s"' % (module, e)
try:
cls = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured, 'Module %s does not define a "%s" OAuth data store' % (module, attr)
return cls
# Set the datastore here.
oauth_datastore = load_data_store()
def initialize_server_request(request):
"""
Shortcut for initialization.
"""
oauth_request = oauth.OAuthRequest.from_request(
request.method, request.build_absolute_uri(),
headers=request.META, parameters=dict(request.REQUEST.items()),
query_string=request.environ.get('QUERY_STRING', ''))
if oauth_request:
oauth_server = oauth.OAuthServer(oauth_datastore(oauth_request))
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
else:
oauth_server = None
return oauth_server, oauth_request
def send_oauth_error(err=None):
"""
Shortcut for sending an error.
"""
response = HttpResponse(err.message.encode('utf-8'))
response.status_code = 401
realm = 'OAuth'
header = oauth.build_authenticate_header(realm=realm)
for k, v in header.iteritems():
response[k] = v
return response
def oauth_request_token(request):
oauth_server, oauth_request = initialize_server_request(request)
if oauth_server is None:
return INVALID_PARAMS_RESPONSE
try:
token = oauth_server.fetch_request_token(oauth_request)
response = HttpResponse(token.to_string())
except oauth.OAuthError, err:
response = send_oauth_error(err)
return response
def oauth_auth_view(request, token, callback, params):
form = forms.OAuthAuthenticationForm(initial={
'oauth_token': token.key,
'oauth_callback': callback,
})
return render_to_response('piston/authorize_token.html',
{ 'form': form }, RequestContext(request))
@login_required
def oauth_user_auth(request):
oauth_server, oauth_request = initialize_server_request(request)
if oauth_request is None:
return INVALID_PARAMS_RESPONSE
try:
token = oauth_server.fetch_request_token(oauth_request)
except oauth.OAuthError, err:
return send_oauth_error(err)
try:
callback = oauth_server.get_callback(oauth_request)
except:
callback = None
if request.method == "GET":
params = oauth_request.get_normalized_parameters()
oauth_view = getattr(settings, 'OAUTH_AUTH_VIEW', None)
if oauth_view is None:
return oauth_auth_view(request, token, callback, params)
else:
return get_callable(oauth_view)(request, token, callback, params)
elif request.method == "POST":
try:
form = forms.OAuthAuthenticationForm(request.POST)
if form.is_valid():
token = oauth_server.authorize_token(token, request.user)
args = '?'+token.to_string(only_key=True)
else:
args = '?error=%s' % 'Access not granted by user.'
if not callback:
callback = getattr(settings, 'OAUTH_CALLBACK_VIEW')
return get_callable(callback)(request, token)
response = HttpResponseRedirect(callback+args)
except oauth.OAuthError, err:
response = send_oauth_error(err)
else:
response = HttpResponse('Action not allowed.')
return response
def oauth_access_token(request):
oauth_server, oauth_request = initialize_server_request(request)
if oauth_request is None:
return INVALID_PARAMS_RESPONSE
try:
token = oauth_server.fetch_access_token(oauth_request)
return HttpResponse(token.to_string())
except oauth.OAuthError, err:
return send_oauth_error(err)
INVALID_PARAMS_RESPONSE = send_oauth_error(oauth.OAuthError('Invalid request parameters.'))
class OAuthAuthentication(object):
"""
OAuth authentication. Based on work by Leah Culver.
"""
def __init__(self, realm='API'):
self.realm = realm
self.builder = oauth.build_authenticate_header
def is_authenticated(self, request):
"""
Checks whether a means of specifying authentication
is provided, and if so, if it is a valid token.
Read the documentation on `HttpBasicAuthentication`
for more information about what goes on here.
"""
if self.is_valid_request(request):
try:
consumer, token, parameters = self.validate_token(request)
except oauth.OAuthError, err:
print send_oauth_error(err)
return False
if consumer and token:
request.user = token.user
request.throttle_extra = token.consumer.id
return True
return False
def challenge(self):
"""
Returns a 401 response with a small bit on
what OAuth is, and where to learn more about it.
When this was written, browsers did not understand
OAuth authentication on the browser side, and hence
the helpful template we render. Maybe some day in the
future, browsers will take care of this stuff for us
and understand the 401 with the realm we give it.
"""
response = HttpResponse()
response.status_code = 401
realm = 'API'
for k, v in self.builder(realm=realm).iteritems():
response[k] = v
tmpl = loader.render_to_string('oauth/challenge.html',
{ 'MEDIA_URL': settings.MEDIA_URL })
response.content = tmpl
return response
@staticmethod
def is_valid_request(request):
"""
Checks whether the required parameters are either in
the http-authorization header sent by some clients,
which is by the way the preferred method according to
OAuth spec, but otherwise fall back to `GET` and `POST`.
"""
must_have = [ 'oauth_'+s for s in [
'consumer_key', 'token', 'signature',
'signature_method', 'timestamp', 'nonce' ] ]
is_in = lambda l: all([ (p in l) for p in must_have ])
auth_params = request.META.get("HTTP_AUTHORIZATION", "")
req_params = request.REQUEST
return is_in(auth_params) or is_in(req_params)
@staticmethod
def validate_token(request, check_timestamp=True, check_nonce=True):
oauth_server, oauth_request = initialize_server_request(request)
return oauth_server.verify_request(oauth_request)
|
zzz-game-prototype
|
trunk/django-piston/piston/authentication.py
|
Python
|
bsd
| 9,667
|
from django.middleware.http import ConditionalGetMiddleware
from django.middleware.common import CommonMiddleware
def compat_middleware_factory(klass):
"""
Class wrapper that only executes `process_response`
if `streaming` is not set on the `HttpResponse` object.
Django has a bad habbit of looking at the content,
which will prematurely exhaust the data source if we're
using generators or buffers.
"""
class compatwrapper(klass):
def process_response(self, req, resp):
if not hasattr(resp, 'streaming'):
return klass.process_response(self, req, resp)
return resp
return compatwrapper
ConditionalMiddlewareCompatProxy = compat_middleware_factory(ConditionalGetMiddleware)
CommonMiddlewareCompatProxy = compat_middleware_factory(CommonMiddleware)
|
zzz-game-prototype
|
trunk/django-piston/piston/middleware.py
|
Python
|
bsd
| 833
|
from django.http import HttpResponseNotAllowed, HttpResponseForbidden, HttpResponse, HttpResponseBadRequest
from django.core.urlresolvers import reverse
from django.core.cache import cache
from django import get_version as django_version
from decorator import decorator
from datetime import datetime, timedelta
__version__ = '0.2.2'
def get_version():
return __version__
def format_error(error):
return u"Piston/%s (Django %s) crash report:\n\n%s" % \
(get_version(), django_version(), error)
class rc_factory(object):
"""
Status codes.
"""
CODES = dict(ALL_OK = ('OK', 200),
CREATED = ('Created', 201),
DELETED = ('', 204), # 204 says "Don't send a body!"
BAD_REQUEST = ('Bad Request', 400),
FORBIDDEN = ('Forbidden', 401),
NOT_FOUND = ('Not Found', 404),
DUPLICATE_ENTRY = ('Conflict/Duplicate', 409),
NOT_HERE = ('Gone', 410),
NOT_IMPLEMENTED = ('Not Implemented', 501),
THROTTLED = ('Throttled', 503))
def __getattr__(self, attr):
"""
Returns a fresh `HttpResponse` when getting
an "attribute". This is backwards compatible
with 0.2, which is important.
"""
try:
(r, c) = self.CODES.get(attr)
except TypeError:
raise AttributeError(attr)
return HttpResponse(r, content_type='text/plain', status=c)
rc = rc_factory()
class FormValidationError(Exception):
def __init__(self, form):
self.form = form
class HttpStatusCode(Exception):
def __init__(self, response):
self.response = response
def validate(v_form, operation='POST'):
@decorator
def wrap(f, self, request, *a, **kwa):
form = v_form(getattr(request, operation))
if form.is_valid():
return f(self, request, *a, **kwa)
else:
raise FormValidationError(form)
return wrap
def throttle(max_requests, timeout=60*60, extra=''):
"""
Simple throttling decorator, caches
the amount of requests made in cache.
If used on a view where users are required to
log in, the username is used, otherwise the
IP address of the originating request is used.
Parameters::
- `max_requests`: The maximum number of requests
- `timeout`: The timeout for the cache entry (default: 1 hour)
"""
@decorator
def wrap(f, self, request, *args, **kwargs):
if request.user.is_authenticated():
ident = request.user.username
else:
ident = request.META.get('REMOTE_ADDR', None)
if hasattr(request, 'throttle_extra'):
"""
Since we want to be able to throttle on a per-
application basis, it's important that we realize
that `throttle_extra` might be set on the request
object. If so, append the identifier name with it.
"""
ident += ':%s' % str(request.throttle_extra)
if ident:
"""
Preferrably we'd use incr/decr here, since they're
atomic in memcached, but it's in django-trunk so we
can't use it yet. If someone sees this after it's in
stable, you can change it here.
"""
ident += ':%s' % extra
now = datetime.now()
ts_key = 'throttle:ts:%s' % ident
timestamp = cache.get(ts_key)
offset = now + timedelta(seconds=timeout)
if timestamp and timestamp < offset:
t = rc.THROTTLED
wait = timeout - (offset-timestamp).seconds
t.content = 'Throttled, wait %d seconds.' % wait
return t
count = cache.get(ident, 1)
cache.set(ident, count+1)
if count >= max_requests:
cache.set(ts_key, offset, timeout)
cache.set(ident, 1)
return f(self, request, *args, **kwargs)
return wrap
def coerce_put_post(request):
"""
Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.
The try/except abominiation here is due to a bug
in mod_python. This should fix it.
"""
if request.method == "PUT":
try:
request.method = "POST"
request._load_post_and_files()
request.method = "PUT"
except AttributeError:
request.META['REQUEST_METHOD'] = 'POST'
request._load_post_and_files()
request.META['REQUEST_METHOD'] = 'PUT'
request.PUT = request.POST
class MimerDataException(Exception):
"""
Raised if the content_type and data don't match
"""
pass
class Mimer(object):
TYPES = dict()
def __init__(self, request):
self.request = request
def is_multipart(self):
content_type = self.content_type()
if content_type is not None:
return content_type.lstrip().startswith('multipart')
return False
def loader_for_type(self, ctype):
"""
Gets a function ref to deserialize content
for a certain mimetype.
"""
for loadee, mimes in Mimer.TYPES.iteritems():
if ctype in mimes:
return loadee
def content_type(self):
"""
Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded
"""
type_formencoded = "application/x-www-form-urlencoded"
ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)
if ctype == type_formencoded:
return None
return ctype
def translate(self):
"""
Will look at the `Content-type` sent by the client, and maybe
deserialize the contents into the format they sent. This will
work for JSON, YAML, XML and Pickle. Since the data is not just
key-value (and maybe just a list), the data will be placed on
`request.data` instead, and the handler will have to read from
there.
It will also set `request.content_type` so the handler has an easy
way to tell what's going on. `request.content_type` will always be
None for form-encoded and/or multipart form data (what your browser sends.)
"""
ctype = self.content_type()
self.request.content_type = ctype
if not self.is_multipart() and ctype:
loadee = self.loader_for_type(ctype)
try:
self.request.data = loadee(self.request.raw_post_data)
# Reset both POST and PUT from request, as its
# misleading having their presence around.
self.request.POST = self.request.PUT = dict()
except (TypeError, ValueError):
raise MimerDataException
return self.request
@classmethod
def register(cls, loadee, types):
cls.TYPES[loadee] = types
@classmethod
def unregister(cls, loadee):
return cls.TYPES.pop(loadee)
def translate_mime(request):
request = Mimer(request).translate()
def require_mime(*mimes):
"""
Decorator requiring a certain mimetype. There's a nifty
helper called `require_extended` below which requires everything
we support except for post-data via form.
"""
@decorator
def wrap(f, self, request, *args, **kwargs):
m = Mimer(request)
realmimes = set()
rewrite = { 'json': 'application/json',
'yaml': 'application/x-yaml',
'xml': 'text/xml',
'pickle': 'application/python-pickle' }
for idx, mime in enumerate(mimes):
realmimes.add(rewrite.get(mime, mime))
if not m.content_type() in realmimes:
return rc.BAD_REQUEST
return f(self, request, *args, **kwargs)
return wrap
require_extended = require_mime('json', 'yaml', 'xml', 'pickle')
|
zzz-game-prototype
|
trunk/django-piston/piston/utils.py
|
Python
|
bsd
| 8,373
|
import inspect, handler
from piston.handler import typemapper
from django.core.urlresolvers import get_resolver, get_callable, get_script_prefix
from django.shortcuts import render_to_response
from django.template import RequestContext
def generate_doc(handler_cls):
"""
Returns a `HandlerDocumentation` object
for the given handler. Use this to generate
documentation for your API.
"""
if not type(handler_cls) is handler.HandlerMetaClass:
raise ValueError("Give me handler, not %s" % type(handler_cls))
return HandlerDocumentation(handler_cls)
class HandlerMethod(object):
def __init__(self, method, stale=False):
self.method = method
self.stale = stale
def iter_args(self):
args, _, _, defaults = inspect.getargspec(self.method)
for idx, arg in enumerate(args):
if arg in ('self', 'request', 'form'):
continue
didx = len(args)-idx
if defaults and len(defaults) >= didx:
yield (arg, str(defaults[-didx]))
else:
yield (arg, None)
def get_signature(self, parse_optional=True):
spec = ""
for argn, argdef in self.iter_args():
spec += argn
if argdef:
spec += '=%s' % argdef
spec += ', '
spec = spec.rstrip(", ")
if parse_optional:
return spec.replace("=None", "=<optional>")
return spec
signature = property(get_signature)
def get_doc(self):
return inspect.getdoc(self.method)
doc = property(get_doc)
def get_name(self):
return self.method.__name__
name = property(get_name)
def __repr__(self):
return "<Method: %s>" % self.name
class HandlerDocumentation(object):
def __init__(self, handler):
self.handler = handler
def get_methods(self, include_default=False):
for method in "read create update delete".split():
met = getattr(self.handler, method)
stale = inspect.getmodule(met) is handler
if not self.handler.is_anonymous:
if met and (not stale or include_default):
yield HandlerMethod(met, stale)
else:
if not stale or met.__name__ == "read" \
and 'GET' in self.allowed_methods:
yield HandlerMethod(met, stale)
def get_all_methods(self):
return self.get_methods(include_default=True)
@property
def is_anonymous(self):
return handler.is_anonymous
def get_model(self):
return getattr(self, 'model', None)
def get_doc(self):
return self.handler.__doc__
doc = property(get_doc)
@property
def name(self):
return self.handler.__name__
@property
def allowed_methods(self):
return self.handler.allowed_methods
def get_resource_uri_template(self):
"""
URI template processor.
See http://bitworking.org/projects/URI-Templates/
"""
def _convert(template, params=[]):
"""URI template converter"""
paths = template % dict([p, "{%s}" % p] for p in params)
return u'%s%s' % (get_script_prefix(), paths)
try:
resource_uri = self.handler.resource_uri()
components = [None, [], {}]
for i, value in enumerate(resource_uri):
components[i] = value
lookup_view, args, kwargs = components
lookup_view = get_callable(lookup_view, True)
possibilities = get_resolver(None).reverse_dict.getlist(lookup_view)
for possibility, pattern in possibilities:
for result, params in possibility:
if args:
if len(args) != len(params):
continue
return _convert(result, params)
else:
if set(kwargs.keys()) != set(params):
continue
return _convert(result, params)
except:
return None
resource_uri_template = property(get_resource_uri_template)
def __repr__(self):
return u'<Documentation for "%s">' % self.name
def documentation_view(request):
"""
Generic documentation view. Generates documentation
from the handlers you've defined.
"""
docs = [ ]
for handler, (model, anonymous) in typemapper.iteritems():
docs.append(generate_doc(handler))
return render_to_response('documentation.html',
{ 'docs': docs }, RequestContext(request))
|
zzz-game-prototype
|
trunk/django-piston/piston/doc.py
|
Python
|
bsd
| 4,950
|
import oauth
from models import Nonce, Token, Consumer
class DataStore(oauth.OAuthDataStore):
"""Layer between Python OAuth and Django database."""
def __init__(self, oauth_request):
self.signature = oauth_request.parameters.get('oauth_signature', None)
self.timestamp = oauth_request.parameters.get('oauth_timestamp', None)
self.scope = oauth_request.parameters.get('scope', 'all')
def lookup_consumer(self, key):
try:
self.consumer = Consumer.objects.get(key=key)
return self.consumer
except Consumer.DoesNotExist:
return None
def lookup_token(self, token_type, token):
if token_type == 'request':
token_type = Token.REQUEST
elif token_type == 'access':
token_type = Token.ACCESS
try:
self.request_token = Token.objects.get(key=token,
token_type=token_type)
return self.request_token
except Token.DoesNotExist:
return None
def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
if oauth_token is None:
return None
nonce, created = Nonce.objects.get_or_create(consumer_key=oauth_consumer.key,
token_key=oauth_token.key,
key=nonce)
if created:
return None
else:
return nonce.key
def fetch_request_token(self, oauth_consumer):
if oauth_consumer.key == self.consumer.key:
self.request_token = Token.objects.create_token(consumer=self.consumer,
token_type=Token.REQUEST,
timestamp=self.timestamp)
return self.request_token
return None
def fetch_access_token(self, oauth_consumer, oauth_token):
if oauth_consumer.key == self.consumer.key \
and oauth_token.key == self.request_token.key \
and self.request_token.is_approved:
self.access_token = Token.objects.create_token(consumer=self.consumer,
token_type=Token.ACCESS,
timestamp=self.timestamp,
user=self.request_token.user)
return self.access_token
return None
def authorize_request_token(self, oauth_token, user):
if oauth_token.key == self.request_token.key:
# authorize the request token in the store
self.request_token.is_approved = True
self.request_token.user = user
self.request_token.save()
return self.request_token
return None
|
zzz-game-prototype
|
trunk/django-piston/piston/store.py
|
Python
|
bsd
| 2,893
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Test</title>
<script type="text/javascript">
// Basic 64 of user password
var auth = "Basic dGVzdHVzZXI6Zm9vYmFy";
function success_callback() {
$("<h3>").text(this.title).appendTo("#content");
$("<div>").text(this.content).appendTo("#content");
$("<h4>").text(this.created_on).appendTo("#content");
};
$(function() {
var dict = {
url: "/api/posts.json",
beforeSend: function(request) {
request.setRequestHeader('Authorization', auth)
},
success: function(json, textStatus) {$.each(json, success_callback)},
dataType: "json"
};
$.ajax(dict);
});
function send_form() {
send_dict = {
url: "/api/posts.json",
beforeSend: function(request) {
request.setRequestHeader('Authorization', auth)
},
type: "POST",
data: $("#id_form").serialize(),
processData: false,
dataType: "json",
success: function(json, textStatus) {
$("<h3>").text(json.title).appendTo("#content");
$("<div>").text(json.content).appendTo("#content");
$("<h4>").text(json.created_on).appendTo("#content");
}
};
$.ajax(send_dict);
return false;
};
</script>
</head>
<body>
<h1>JS Test</h1>
<div id="content">
</div>
<form id="id_form" action="." method="post">
<label for="id_title">Title:</label>
<input type="text" id="id_title" name="title" />
<br />
<label for="id_content">Content:</label>
<textarea cols="40" rows="20" id="id_content" name="content"></textarea>
<br />
<input type="submit" onclick="return send_form();" value="Submit" />
</form>
</body>
</html>
|
zzz-game-prototype
|
trunk/django-piston/examples/blogserver/templates/test_js.html
|
HTML
|
bsd
| 1,809
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Blogposts</title>
</head>
<body>
<h1>Posts</h1>
{% for post in posts %}
<h3>{{ post.title }}</h3>
<div>
{{ post.content}}
</div>
<div>
Written on {{ post.created_on }} by {{ post.author.username }}.
</div>
{% endfor %}
</body>
</html>
|
zzz-game-prototype
|
trunk/django-piston/examples/blogserver/templates/posts.html
|
HTML
|
bsd
| 460
|
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
|
zzz-game-prototype
|
trunk/django-piston/examples/blogserver/manage.py
|
Python
|
bsd
| 546
|
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
|
zzz-game-prototype
|
trunk/django-piston/examples/blogserver/.svn/text-base/manage.py.svn-base
|
Python
|
bsd
| 546
|
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^', include('blogserver.blog.urls')),
(r'^api/', include('blogserver.api.urls')),
(r'^admin/(.*)', admin.site.root),
)
|
zzz-game-prototype
|
trunk/django-piston/examples/blogserver/urls.py
|
Python
|
bsd
| 257
|
import os, sys
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Fix up piston imports here. We would normally place piston in
# a directory accessible via the Django app, but this is an
# example and we ship it a couple of directories up.
sys.path.insert(0, os.path.join(BASE_DIR, '../../'))
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = os.path.join(BASE_DIR, 'db') # Or path to database file if using sqlite3.
#DATABASE_USER = '' # Not used with sqlite3.
#DATABASE_PASSWORD = '' # Not used with sqlite3.
#DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
#DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'f@vhy8vuq7w70v=cnynm(am1__*zt##i2--i2p-021@-qgws%g'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'blogserver.urls'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, '../../piston/templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.markup',
'blogserver.blog',
'blogserver.api',
)
FIXTURE_DIRS = (
os.path.join(BASE_DIR, 'fixtures'),
)
APPEND_SLASH = False
|
zzz-game-prototype
|
trunk/django-piston/examples/blogserver/settings.py
|
Python
|
bsd
| 3,155
|