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
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_CFLAGS := -O3 LOCAL_ARM_MODE := arm LOCAL_C_INCLUDES := $(LOCAL_PATH)/../mupdf $(LOCAL_PATH)/../fitz LOCAL_MODULE := fitzdraw LOCAL_SRC_FILES := \ draw_device.c \ arch_port.c \ arch_arm.c \ draw_blend.c \ draw_glyph.c \ draw_affine.c \ draw_scale.c \ draw_unpack.c \ draw_mesh.c \ draw_path.c \ draw_paint.c \ draw_edge.c include $(BUILD_STATIC_LIBRARY)
zzyangming-szyangming
pdfview/jni/mupdf/draw/Android.mk
Makefile
gpl3
478
font_files: font_misc.c font_mono.c font_serif.c font_sans.c font_cjk.c cmap_tounicode.c cmap_cns.c cmap_gb.c cmap_japan.c cmap_korea.c clean: @rm -v font_misc.c font_mono.c font_serif.c font_sans.c font_cjk.c cmap_tounicode.c cmap_cns.c cmap_gb.c cmap_japan.c cmap_korea.c \ fontdump cmapdump cmapdump: cmapdump.c pdf_debug.c gcc -o cmapdump cmapdump.c pdf_debug.c -I../fitz fontdump: fontdump.c gcc -o fontdump fontdump.c font_misc.c: fontdump ./fontdump font_misc.c \ ../fonts/Dingbats.cff \ ../fonts/StandardSymL.cff \ ../fonts/URWChanceryL-MediItal.cff font_mono.c: fontdump ./fontdump font_mono.c \ ../fonts/NimbusMonL-Regu.cff \ ../fonts/NimbusMonL-ReguObli.cff \ ../fonts/NimbusMonL-Bold.cff \ ../fonts/NimbusMonL-BoldObli.cff font_sans.c: fontdump ./fontdump font_sans.c \ ../fonts/NimbusSanL-Bold.cff \ ../fonts/NimbusSanL-BoldItal.cff \ ../fonts/NimbusSanL-Regu.cff \ ../fonts/NimbusSanL-ReguItal.cff font_serif.c: fontdump ./fontdump font_serif.c \ ../fonts/NimbusRomNo9L-Regu.cff \ ../fonts/NimbusRomNo9L-ReguItal.cff \ ../fonts/NimbusRomNo9L-Medi.cff \ ../fonts/NimbusRomNo9L-MediItal.cff font_cjk.c: fontdump ./fontdump font_cjk.c \ ../fonts/droid/DroidSansFallback.ttf cmap_tounicode.c: cmapdump ./cmapdump cmap_tounicode.c \ ../cmaps/Adobe-CNS1-UCS2 \ ../cmaps/Adobe-GB1-UCS2 \ ../cmaps/Adobe-Japan1-UCS2 \ ../cmaps/Adobe-Korea1-UCS2 cmap_cns.c: cmapdump ./cmapdump cmap_cns.c \ ../cmaps/Adobe-CNS1-0 ../cmaps/Adobe-CNS1-1 ../cmaps/Adobe-CNS1-2 ../cmaps/Adobe-CNS1-3 \ ../cmaps/Adobe-CNS1-4 ../cmaps/Adobe-CNS1-5 ../cmaps/Adobe-CNS1-6 ../cmaps/B5-H ../cmaps/B5-V ../cmaps/B5pc-H ../cmaps/B5pc-V \ ../cmaps/CNS-EUC-H ../cmaps/CNS-EUC-V ../cmaps/CNS1-H ../cmaps/CNS1-V ../cmaps/CNS2-H ../cmaps/CNS2-V ../cmaps/ETen-B5-H \ ../cmaps/ETen-B5-V ../cmaps/ETenms-B5-H ../cmaps/ETenms-B5-V ../cmaps/ETHK-B5-H ../cmaps/ETHK-B5-V \ ../cmaps/HKdla-B5-H ../cmaps/HKdla-B5-V ../cmaps/HKdlb-B5-H ../cmaps/HKdlb-B5-V ../cmaps/HKgccs-B5-H \ ../cmaps/HKgccs-B5-V ../cmaps/HKm314-B5-H ../cmaps/HKm314-B5-V ../cmaps/HKm471-B5-H ../cmaps/HKm471-B5-V \ ../cmaps/HKscs-B5-H ../cmaps/HKscs-B5-V ../cmaps/UniCNS-UCS2-H ../cmaps/UniCNS-UCS2-V \ ../cmaps/UniCNS-UTF16-H ../cmaps/UniCNS-UTF16-V cmap_gb.c: cmapdump ./cmapdump cmap_gb.c \ ../cmaps/Adobe-GB1-0 ../cmaps/Adobe-GB1-1 ../cmaps/Adobe-GB1-2 ../cmaps/Adobe-GB1-3 ../cmaps/Adobe-GB1-4 \ ../cmaps/Adobe-GB1-5 ../cmaps/GB-EUC-H ../cmaps/GB-EUC-V ../cmaps/GB-H ../cmaps/GB-V ../cmaps/GBK-EUC-H ../cmaps/GBK-EUC-V \ ../cmaps/GBK2K-H ../cmaps/GBK2K-V ../cmaps/GBKp-EUC-H ../cmaps/GBKp-EUC-V ../cmaps/GBpc-EUC-H ../cmaps/GBpc-EUC-V \ ../cmaps/GBT-EUC-H ../cmaps/GBT-EUC-V ../cmaps/GBT-H ../cmaps/GBT-V ../cmaps/GBTpc-EUC-H ../cmaps/GBTpc-EUC-V \ ../cmaps/UniGB-UCS2-H ../cmaps/UniGB-UCS2-V ../cmaps/UniGB-UTF16-H ../cmaps/UniGB-UTF16-V cmap_japan.c: cmapdump ./cmapdump cmap_japan.c \ ../cmaps/78-EUC-H ../cmaps/78-EUC-V ../cmaps/78-H ../cmaps/78-RKSJ-H ../cmaps/78-RKSJ-V ../cmaps/78-V ../cmaps/78ms-RKSJ-H \ ../cmaps/78ms-RKSJ-V ../cmaps/83pv-RKSJ-H ../cmaps/90ms-RKSJ-H ../cmaps/90ms-RKSJ-V ../cmaps/90msp-RKSJ-H \ ../cmaps/90msp-RKSJ-V ../cmaps/90pv-RKSJ-H ../cmaps/90pv-RKSJ-V ../cmaps/Add-H ../cmaps/Add-RKSJ-H \ ../cmaps/Add-RKSJ-V ../cmaps/Add-V ../cmaps/Adobe-Japan1-0 ../cmaps/Adobe-Japan1-1 ../cmaps/Adobe-Japan1-2 \ ../cmaps/Adobe-Japan1-3 ../cmaps/Adobe-Japan1-4 ../cmaps/Adobe-Japan1-5 ../cmaps/Adobe-Japan1-6 \ ../cmaps/EUC-H ../cmaps/EUC-V ../cmaps/Ext-H ../cmaps/Ext-RKSJ-H ../cmaps/Ext-RKSJ-V ../cmaps/Ext-V ../cmaps/H ../cmaps/Hankaku \ ../cmaps/Hiragana ../cmaps/Katakana ../cmaps/NWP-H ../cmaps/NWP-V ../cmaps/RKSJ-H ../cmaps/RKSJ-V ../cmaps/Roman \ ../cmaps/UniJIS-UCS2-H ../cmaps/UniJIS-UCS2-HW-H ../cmaps/UniJIS-UCS2-HW-V ../cmaps/UniJIS-UCS2-V \ ../cmaps/UniJISPro-UCS2-HW-V ../cmaps/UniJISPro-UCS2-V ../cmaps/V ../cmaps/WP-Symbol \ ../cmaps/Adobe-Japan2-0 ../cmaps/Hojo-EUC-H ../cmaps/Hojo-EUC-V ../cmaps/Hojo-H ../cmaps/Hojo-V \ ../cmaps/UniHojo-UCS2-H ../cmaps/UniHojo-UCS2-V ../cmaps/UniHojo-UTF16-H ../cmaps/UniHojo-UTF16-V \ ../cmaps/UniJIS-UTF16-H ../cmaps/UniJIS-UTF16-V cmap_korea.c: cmapdump ./cmapdump cmap_korea.c \ ../cmaps/Adobe-Korea1-0 ../cmaps/Adobe-Korea1-1 ../cmaps/Adobe-Korea1-2 ../cmaps/KSC-EUC-H \ ../cmaps/KSC-EUC-V ../cmaps/KSC-H ../cmaps/KSC-Johab-H ../cmaps/KSC-Johab-V ../cmaps/KSC-V ../cmaps/KSCms-UHC-H \ ../cmaps/KSCms-UHC-HW-H ../cmaps/KSCms-UHC-HW-V ../cmaps/KSCms-UHC-V ../cmaps/KSCpc-EUC-H \ ../cmaps/KSCpc-EUC-V ../cmaps/UniKS-UCS2-H ../cmaps/UniKS-UCS2-V ../cmaps/UniKS-UTF16-H ../cmaps/UniKS-UTF16-V # vim: set sts=8 ts=8 sw=8 noet:
zzyangming-szyangming
pdfview/jni/mupdf/pdf/APV.mk
Makefile
gpl3
4,661
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_ARM_MODE := arm LOCAL_C_INCLUDES := $(LOCAL_PATH)/../fitz $(LOCAL_PATH)/../../freetype-overtlay/include $(LOCAL_PATH)/../../freetype/include $(LOCAL_PATH)/.. LOCAL_MODULE := pdf LOCAL_CFLAGS := -DNOCJK -O3 LOCAL_SRC_FILES := \ apv_pdf_debug.c \ pdf_lex.c \ pdf_nametree.c \ pdf_parse.c \ pdf_repair.c \ pdf_stream.c \ pdf_xref.c \ pdf_annot.c \ pdf_outline.c \ pdf_cmap.c \ pdf_cmap_parse.c \ pdf_cmap_load.c \ pdf_cmap_table.c \ pdf_encoding.c \ pdf_unicode.c \ pdf_font.c \ pdf_type3.c \ pdf_metrics.c \ pdf_fontfile.c \ pdf_function.c \ pdf_colorspace.c \ pdf_image.c \ pdf_pattern.c \ pdf_shade.c \ pdf_xobject.c \ pdf_interpret.c \ pdf_page.c \ pdf_store.c \ pdf_crypt.c # cmap_tounicode.c \ # font_cjk.c \ # cmap_cns.c \ # cmap_gb.c cmap_japan.c cmap_korea.c include $(BUILD_STATIC_LIBRARY) # vim: set sts=8 sw=8 ts=8 noet:
zzyangming-szyangming
pdfview/jni/mupdf/pdf/Android.mk
Makefile
gpl3
930
/* * This is a modified version of pdf_debug.c file which is part of MuPDF * by Artifex Software, Inc. */ #include "fitz.h" #include "mupdf.h" static void (*pdf_loghandler)(const char *s) = NULL; static int reinit_pdflog = 0; /* * Enable logging by setting environment variable MULOG to: * (a)ll or a combination of * (x)ref (r)src (f)ont (i)mage (s)hade (p)age * * eg. MULOG=fis ./x11pdf mytestfile.pdf */ enum { PDF_LXREF = 1, PDF_LRSRC = 2, PDF_LFONT = 4, PDF_LIMAGE = 8, PDF_LSHADE = 16, PDF_LPAGE = 32 }; static inline void pdflog(int tag, char *name, char *fmt, va_list ap) { static int flags = 128; static int level = 0; static int push = 1; int i; if (flags == 128 || reinit_pdflog) { char *s = getenv("MULOG"); if (pdf_loghandler != NULL) s = "axrfisp"; flags = 0; if (s) { if (strstr(s, "a")) flags |= 0xffff; if (strstr(s, "x")) flags |= PDF_LXREF; if (strstr(s, "r")) flags |= PDF_LRSRC; if (strstr(s, "f")) flags |= PDF_LFONT; if (strstr(s, "i")) flags |= PDF_LIMAGE; if (strstr(s, "s")) flags |= PDF_LSHADE; if (strstr(s, "p")) flags |= PDF_LPAGE; } reinit_pdflog = 0; } if (!(flags & tag)) return; if (strchr(fmt, '}')) level --; if (push) { if (pdf_loghandler == NULL) { printf("%s: ", name); for (i = 0; i < level; i++) printf(" "); } } if (pdf_loghandler == NULL) { vprintf(fmt, ap); } else { char b[2048]; int ll = push ? level : 0; b[0] = 0; if (push) { strncat(b, name, 100); strncat(b, ": ", 100); } for(i = 0; i < ll; ++i) strncat(b, " ", 100); vsnprintf(b+strlen(b), 2048-strlen(b), fmt, ap); b[2047] = 0; pdf_loghandler(b); } if (strchr(fmt, '{')) level ++; push = !!strchr(fmt, '\n'); if (pdf_loghandler == NULL) fflush(stdout); } void pdf_logxref(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LXREF,"xref",fmt,ap);va_end(ap);} void pdf_logrsrc(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LRSRC,"rsrc",fmt,ap);va_end(ap);} void pdf_logfont(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LFONT,"font",fmt,ap);va_end(ap);} void pdf_logimage(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LIMAGE,"imag",fmt,ap);va_end(ap);} void pdf_logshade(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LSHADE,"shad",fmt,ap);va_end(ap);} void pdf_logpage(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LPAGE,"page",fmt,ap);va_end(ap);} void pdf_setloghandler(void (*newloghandler)(const char *)) { pdf_loghandler = newloghandler; reinit_pdflog = 1; }
zzyangming-szyangming
pdfview/jni/mupdf/pdf/apv_pdf_debug.c
C
gpl3
2,748
#include "fitz.h" #include <libgen.h> #include "android/log.h" char fz_errorbuf[150*20] = {0}; static int fz_errorlen = 0; static int fz_errorclear = 1; static void fz_printerror(int type, const char *file, int line, const char *func, char *msg) { char buf[150]; int len; char *s; s = strrchr(file, '\\'); if (s) file = s + 1; __android_log_print(ANDROID_LOG_INFO, "mupdf", "%c %s:%d: %s(): %s\n", type, basename(file), line, func, msg); snprintf(buf, sizeof buf, "%s:%d: %s(): %s", basename(file), line, func, msg); buf[sizeof(buf)-1] = 0; len = strlen(buf); if (fz_errorclear) { fz_errorclear = 0; fz_errorlen = 0; memset(fz_errorbuf, 0, sizeof fz_errorbuf); } if (fz_errorlen + len + 2 < sizeof fz_errorbuf) { memcpy(fz_errorbuf + fz_errorlen, buf, len); fz_errorlen += len; fz_errorbuf[fz_errorlen++] = '\n'; fz_errorbuf[fz_errorlen] = 0; } } void fz_warn(char *fmt, ...) { va_list ap; fprintf(stderr, "warning: "); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); } fz_error fz_throwimp(const char *file, int line, const char *func, char *fmt, ...) { char buf[150]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); buf[sizeof(buf)-1] = 0; fz_printerror('+', file, line, func, buf); return -1; } fz_error fz_rethrowimp(const char *file, int line, const char *func, fz_error cause, char *fmt, ...) { char buf[150]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); buf[sizeof(buf)-1] = 0; fz_printerror('|', file, line, func, buf); return cause; } void fz_catchimp(const char *file, int line, const char *func, fz_error cause, char *fmt, ...) { char buf[150]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); buf[sizeof(buf)-1] = 0; fz_printerror('\\', file, line, func, buf); fz_errorclear = 1; }
zzyangming-szyangming
pdfview/jni/mupdf/fitz/apv_base_error.c
C
gpl3
1,899
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_CFLAGS := -O3 ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) LOCAL_CFLAGS += -DJDCT_FASTEST=JDCT_FLOAT endif LOCAL_ARM_MODE := arm LOCAL_C_INCLUDES := $(LOCAL_PATH)/../mupdf $(LOCAL_PATH)/../../jpeg \ $(LOCAL_PATH)/../../freetype-overlay/include $(LOCAL_PATH)/../../freetype/include \ $(LOCAL_PATH)/../../jbig2dec $(LOCAL_PATH)/../../openjpeg LOCAL_MODULE := fitz LOCAL_SRC_FILES := \ base_error.c \ base_object.c \ base_hash.c \ base_memory.c \ base_string.c \ base_geometry.c \ \ crypt_aes.c \ crypt_arc4.c \ crypt_md5.c \ crypt_sha2.c \ \ obj_print.c \ \ stm_buffer.c \ stm_open.c \ stm_read.c \ \ filt_basic.c \ \ filt_dctd.c \ filt_faxd.c \ filt_flate.c \ filt_lzwd.c \ filt_predict.c \ filt_jbig2d.c \ filt_jpxd.c \ \ res_colorspace.c \ res_font.c \ res_pixmap.c \ res_shade.c \ res_text.c \ res_path.c \ \ dev_list.c \ dev_text.c \ dev_bbox.c \ dev_null.c include $(BUILD_STATIC_LIBRARY) # vim: set sts=8 sw=8 ts=8 noet:
zzyangming-szyangming
pdfview/jni/mupdf/fitz/Android.mk
Makefile
gpl3
1,028
include $(call all-subdir-makefiles)
zzyangming-szyangming
pdfview/jni/mupdf/Android.mk
Makefile
gpl3
37
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_ARM_MODE := arm LOCAL_MODULE := jbig2dec LOCAL_CFLAGS := -O3 -DHAVE_CONFIG_H LOCAL_SRC_FILES := \ jbig2.c \ jbig2_arith.c \ jbig2_arith_iaid.c \ jbig2_arith_int.c \ jbig2_generic.c \ jbig2_halftone.c \ jbig2_huffman.c \ jbig2_image.c \ jbig2_image_pbm.c \ jbig2_metadata.c \ jbig2_mmr.c \ jbig2_page.c \ jbig2_refinement.c \ jbig2_segment.c \ jbig2_symbol_dict.c \ jbig2_text.c \ jbig2dec.c \ sha1.c # getopt.c # getopt1.c # memcmp.c # snprintf.c # jbig2_image_png.c include $(BUILD_STATIC_LIBRARY)
zzyangming-szyangming
pdfview/jni/jbig2dec/Android.mk
Makefile
gpl3
582
/* config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ #undef AC_APPLE_UNIVERSAL_BUILD /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H /* Define if the local libc includes getopt_long() */ #define HAVE_GETOPT_LONG /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H /* Define to 1 if you have the <libintl.h> header file. */ #undef HAVE_LIBINTL_H /* Define if libpng is available (-lpng) */ #undef HAVE_LIBPNG /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H /* Define to 1 if you have the `memset' function. */ #define HAVE_MEMSET /* Define to 1 if you have the `snprintf' function. */ #define HAVE_SNPRINTF /* Define to 1 if you have the <stddef.h> header file. */ #define HAVE_STDDEF_H /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H /* Define to 1 if you have the `strdup' function. */ #define HAVE_STRDUP /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H /* set by configure if an alternate header with the stdint.h types is found */ #undef JBIG2_REPLACE_STDINT_H /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* Define to 1 if your C compiler doesn't accept -c and -o together. */ #undef NO_MINUS_C_MINUS_O /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the version of this package. */ #undef PACKAGE_VERSION /* The size of `char', as computed by sizeof. */ #undef SIZEOF_CHAR /* The size of `int', as computed by sizeof. */ #undef SIZEOF_INT /* The size of `long', as computed by sizeof. */ #undef SIZEOF_LONG /* The size of `short', as computed by sizeof. */ #undef SIZEOF_SHORT /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Version number of package */ #undef VERSION /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif #endif /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `unsigned int' if <sys/types.h> does not define. */ #undef size_t
zzyangming-szyangming
pdfview/jni/jbig2dec/config.h
C
gpl3
3,143
# # Makefile # # Author: Lasse Collin <lasse.collin@tukaani.org> # # This file has been put into the public domain. # You can do whatever you want with this file. # CC = gcc -std=gnu89 BCJ_CPPFLAGS = -DXZ_DEC_X86 -DXZ_DEC_POWERPC -DXZ_DEC_IA64 \ -DXZ_DEC_ARM -DXZ_DEC_ARMTHUMB -DXZ_DEC_SPARC CFLAGS = -ggdb3 -O2 -pedantic -Wall -Wextra RM = rm -f VPATH = ../linux/include/linux ../linux/lib/xz COMMON_SRCS = xz_crc32.c xz_dec_stream.c xz_dec_lzma2.c xz_dec_bcj.c COMMON_OBJS = $(COMMON_SRCS:.c=.o) XZMINIDEC_OBJS = xzminidec.o BUFTEST_OBJS = buftest.o BOOTTEST_OBJS = boottest.o XZ_HEADERS = xz.h xz_private.h xz_stream.h xz_lzma2.h xz_config.h PROGRAMS = xzminidec buftest boottest ALL_CPPFLAGS = -I../linux/include/linux -I. $(BCJ_CPPFLAGS) $(CPPFLAGS) all: $(PROGRAMS) %.o: %.c $(XZ_HEADERS) $(CC) $(ALL_CPPFLAGS) $(CFLAGS) -c -o $@ $< xzminidec: $(COMMON_OBJS) $(XZMINIDEC_OBJS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(COMMON_OBJS) $(XZMINIDEC_OBJS) buftest: $(COMMON_OBJS) $(BUFTEST_OBJS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(COMMON_OBJS) $(BUFTEST_OBJS) boottest: $(BOOTTEST_OBJS) $(COMMON_SRCS) $(CC) $(ALL_CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $(BOOTTEST_OBJS) .PHONY: clean clean: -$(RM) $(COMMON_OBJS) $(XZMINIDEC_OBJS) $(BUFTEST_OBJS) \ $(BOOTTEST_OBJS) $(PROGRAMS)
zzyangming-szyangming
pdfview/jni/xzx/Makefile
Makefile
gpl3
1,286
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_LDLIBS := -llog LOCAL_MODULE := xzx LOCAL_SRC_FILES := jnixz.c xz_crc32.c xz_dec_stream.c xz_dec_lzma2.c xz_dec_bcj.c LOCAL_CFLAGS := -DXZ_DEC_X86 -DXZ_DEC_POWERPC -DXZ_DEC_IA64 -DXZ_DEC_ARM -DXZ_DEC_ARMTHUMB -DXZ_DEC_SPARC include $(BUILD_SHARED_LIBRARY)
zzyangming-szyangming
pdfview/jni/xzx/Android.mk
Makefile
gpl3
317
APP_MODULES := pdf fitz fitzdraw jpeg pdfview2 jbig2dec openjpeg APP_OPTIM := release APP_ABI := armeabi-v7a armeabi
zzyangming-szyangming
pdfview/jni/Application.mk
Makefile
gpl3
117
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_ARM_MODE := arm LOCAL_MODULE := freetype LOCAL_C_INCLUDES := $(LOCAL_PATH)/../freetype-overlay/include $(LOCAL_PATH)/include LOCAL_LDLIBS := -lz LOCAL_CFLAGS := -DFT2_BUILD_LIBRARY -O3 LOCAL_SRC_FILES := \ src/base/ftsystem.c \ src/base/ftinit.c \ src/base/ftdebug.c \ src/base/ftbase.c \ src/base/ftbbox.c \ src/base/ftglyph.c \ src/base/ftbitmap.c \ src/base/ftcid.c \ src/base/ftfstype.c \ src/base/ftgasp.c \ src/base/ftgxval.c \ src/base/ftlcdfil.c \ src/base/ftmm.c \ src/base/ftotval.c \ src/base/ftpatent.c \ src/base/ftstroke.c \ src/base/ftsynth.c \ src/base/fttype1.c \ src/base/ftxf86.c \ src/cff/cff.c \ src/cid/type1cid.c \ src/sfnt/sfnt.c \ src/truetype/truetype.c \ src/type1/type1.c \ src/raster/raster.c \ src/smooth/smooth.c \ src/autofit/autofit.c \ src/cache/ftcache.c \ src/gxvalid/gxvalid.c \ src/otvalid/otvalid.c \ src/psaux/psaux.c \ src/pshinter/pshinter.c \ src/psnames/psnames.c include $(BUILD_STATIC_LIBRARY)
zzyangming-szyangming
pdfview/jni/freetype/Android.mk
Makefile
gpl3
1,268
/* * jconfig.txt * * Copyright (C) 1991-1994, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file documents the configuration options that are required to * customize the JPEG software for a particular system. * * The actual configuration options for a particular installation are stored * in jconfig.h. On many machines, jconfig.h can be generated automatically * or copied from one of the "canned" jconfig files that we supply. But if * you need to generate a jconfig.h file by hand, this file tells you how. * * DO NOT EDIT THIS FILE --- IT WON'T ACCOMPLISH ANYTHING. * EDIT A COPY NAMED JCONFIG.H. */ /* * These symbols indicate the properties of your machine or compiler. * #define the symbol if yes, #undef it if no. */ /* Does your compiler support function prototypes? * (If not, you also need to use ansi2knr, see install.txt) */ #define HAVE_PROTOTYPES /* Does your compiler support the declaration "unsigned char" ? * How about "unsigned short" ? */ #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* Define "void" as "char" if your compiler doesn't know about type void. * NOTE: be sure to define void such that "void *" represents the most general * pointer type, e.g., that returned by malloc(). */ /* #define void char */ /* Define "const" as empty if your compiler doesn't know the "const" keyword. */ /* #define const */ /* Define this if an ordinary "char" type is unsigned. * If you're not sure, leaving it undefined will work at some cost in speed. * If you defined HAVE_UNSIGNED_CHAR then the speed difference is minimal. */ #undef CHAR_IS_UNSIGNED /* Define this if your system has an ANSI-conforming <stddef.h> file. */ #define HAVE_STDDEF_H /* Define this if your system has an ANSI-conforming <stdlib.h> file. */ #define HAVE_STDLIB_H /* Define this if your system does not have an ANSI/SysV <string.h>, * but does have a BSD-style <strings.h>. */ #undef NEED_BSD_STRINGS /* Define this if your system does not provide typedef size_t in any of the * ANSI-standard places (stddef.h, stdlib.h, or stdio.h), but places it in * <sys/types.h> instead. */ #undef NEED_SYS_TYPES_H /* For 80x86 machines, you need to define NEED_FAR_POINTERS, * unless you are using a large-data memory model or 80386 flat-memory mode. * On less brain-damaged CPUs this symbol must not be defined. * (Defining this symbol causes large data structures to be referenced through * "far" pointers and to be allocated with a special version of malloc.) */ #undef NEED_FAR_POINTERS /* Define this if your linker needs global names to be unique in less * than the first 15 characters. */ #undef NEED_SHORT_EXTERNAL_NAMES /* Although a real ANSI C compiler can deal perfectly well with pointers to * unspecified structures (see "incomplete types" in the spec), a few pre-ANSI * and pseudo-ANSI compilers get confused. To keep one of these bozos happy, * define INCOMPLETE_TYPES_BROKEN. This is not recommended unless you * actually get "missing structure definition" warnings or errors while * compiling the JPEG code. */ #undef INCOMPLETE_TYPES_BROKEN /* * The following options affect code selection within the JPEG library, * but they don't need to be visible to applications using the library. * To minimize application namespace pollution, the symbols won't be * defined unless JPEG_INTERNALS has been defined. */ #ifdef JPEG_INTERNALS /* Define this if your compiler implements ">>" on signed values as a logical * (unsigned) shift; leave it undefined if ">>" is a signed (arithmetic) shift, * which is the normal and rational definition. */ #undef RIGHT_SHIFT_IS_UNSIGNED #endif /* JPEG_INTERNALS */ /* * The remaining options do not affect the JPEG library proper, * but only the sample applications cjpeg/djpeg (see cjpeg.c, djpeg.c). * Other applications can ignore these. */ #ifdef JPEG_CJPEG_DJPEG /* These defines indicate which image (non-JPEG) file formats are allowed. */ #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ /* Define this if you want to name both input and output files on the command * line, rather than using stdout and optionally stdin. You MUST do this if * your system can't cope with binary I/O to stdin/stdout. See comments at * head of cjpeg.c or djpeg.c. */ #undef TWO_FILE_COMMANDLINE /* Define this if your system needs explicit cleanup of temporary files. * This is crucial under MS-DOS, where the temporary "files" may be areas * of extended memory; on most other systems it's not as important. */ #undef NEED_SIGNAL_CATCHER /* By default, we open image files with fopen(...,"rb") or fopen(...,"wb"). * This is necessary on systems that distinguish text files from binary files, * and is harmless on most systems that don't. If you have one of the rare * systems that complains about the "b" spec, define this symbol. */ #undef DONT_USE_B_MODE /* Define this if you want percent-done progress reports from cjpeg/djpeg. */ #undef PROGRESS_REPORT #endif /* JPEG_CJPEG_DJPEG */
zzyangming-szyangming
pdfview/jni/jpeg/jconfig.h
C
gpl3
5,372
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_ARM_MODE := arm ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) LOCAL_CFLAGS := -DJDCT_DEFAULT=JDCT_FLOAT else LOCAL_CFLAGS:= -DJDCT_DEFAULT=JDCT_IFAST endif LOCAL_MODULE := jpeg LOCAL_SRC_FILES := jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c \ jmemnobs.c include $(BUILD_STATIC_LIBRARY)
zzyangming-szyangming
pdfview/jni/jpeg/Android.mk
Makefile
gpl3
844
include $(call all-subdir-makefiles)
zzyangming-szyangming
pdfview/jni/Android.mk
Makefile
gpl3
38
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>GNU General Public License v3.0 - GNU Project - Free Software Foundation (FSF)</title> <link rel="alternate" type="application/rdf+xml" href="http://www.gnu.org/licenses/gpl-3.0.rdf" /> </head> <body> <h3 style="text-align: center;">GNU GENERAL PUBLIC LICENSE</h3> <p style="text-align: center;">Version 3, 29 June 2007</p> <p>Copyright &copy; 2007 Free Software Foundation, Inc. &lt;<a href="http://fsf.org/">http://fsf.org/</a>&gt;</p><p> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.</p> <h3><a name="preamble"></a>Preamble</h3> <p>The GNU General Public License is a free, copyleft license for software and other kinds of works.</p> <p>The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.</p> <p>When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.</p> <p>To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.</p> <p>For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.</p> <p>Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.</p> <p>For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.</p> <p>Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.</p> <p>Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.</p> <p>The precise terms and conditions for copying, distribution and modification follow.</p> <h3><a name="terms"></a>TERMS AND CONDITIONS</h3> <h4><a name="section0"></a>0. Definitions.</h4> <p>&ldquo;This License&rdquo; refers to version 3 of the GNU General Public License.</p> <p>&ldquo;Copyright&rdquo; also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.</p> <p>&ldquo;The Program&rdquo; refers to any copyrightable work licensed under this License. Each licensee is addressed as &ldquo;you&rdquo;. &ldquo;Licensees&rdquo; and &ldquo;recipients&rdquo; may be individuals or organizations.</p> <p>To &ldquo;modify&rdquo; a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a &ldquo;modified version&rdquo; of the earlier work or a work &ldquo;based on&rdquo; the earlier work.</p> <p>A &ldquo;covered work&rdquo; means either the unmodified Program or a work based on the Program.</p> <p>To &ldquo;propagate&rdquo; a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.</p> <p>To &ldquo;convey&rdquo; a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.</p> <p>An interactive user interface displays &ldquo;Appropriate Legal Notices&rdquo; to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.</p> <h4><a name="section1"></a>1. Source Code.</h4> <p>The &ldquo;source code&rdquo; for a work means the preferred form of the work for making modifications to it. &ldquo;Object code&rdquo; means any non-source form of a work.</p> <p>A &ldquo;Standard Interface&rdquo; means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.</p> <p>The &ldquo;System Libraries&rdquo; of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A &ldquo;Major Component&rdquo;, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.</p> <p>The &ldquo;Corresponding Source&rdquo; for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.</p> <p>The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.</p> <p>The Corresponding Source for a work in source code form is that same work.</p> <h4><a name="section2"></a>2. Basic Permissions.</h4> <p>All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.</p> <p>You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.</p> <p>Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.</p> <h4><a name="section3"></a>3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4> <p>No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.</p> <p>When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.</p> <h4><a name="section4"></a>4. Conveying Verbatim Copies.</h4> <p>You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.</p> <p>You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.</p> <h4><a name="section5"></a>5. Conveying Modified Source Versions.</h4> <p>You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:</p> <ul> <li>a) The work must carry prominent notices stating that you modified it, and giving a relevant date.</li> <li>b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to &ldquo;keep intact all notices&rdquo;.</li> <li>c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.</li> <li>d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.</li> </ul> <p>A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an &ldquo;aggregate&rdquo; if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.</p> <h4><a name="section6"></a>6. Conveying Non-Source Forms.</h4> <p>You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:</p> <ul> <li>a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.</li> <li>b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.</li> <li>c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.</li> <li>d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.</li> <li>e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.</li> </ul> <p>A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.</p> <p>A &ldquo;User Product&rdquo; is either (1) a &ldquo;consumer product&rdquo;, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, &ldquo;normally used&rdquo; refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.</p> <p>&ldquo;Installation Information&rdquo; for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.</p> <p>If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).</p> <p>The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.</p> <p>Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.</p> <h4><a name="section7"></a>7. Additional Terms.</h4> <p>&ldquo;Additional permissions&rdquo; are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.</p> <p>When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.</p> <p>Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:</p> <ul> <li>a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or</li> <li>b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or</li> <li>c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or</li> <li>d) Limiting the use for publicity purposes of names of licensors or authors of the material; or</li> <li>e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or</li> <li>f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.</li> </ul> <p>All other non-permissive additional terms are considered &ldquo;further restrictions&rdquo; within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.</p> <p>If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.</p> <p>Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.</p> <h4><a name="section8"></a>8. Termination.</h4> <p>You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).</p> <p>However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.</p> <p>Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.</p> <p>Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.</p> <h4><a name="section9"></a>9. Acceptance Not Required for Having Copies.</h4> <p>You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.</p> <h4><a name="section10"></a>10. Automatic Licensing of Downstream Recipients.</h4> <p>Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.</p> <p>An &ldquo;entity transaction&rdquo; is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.</p> <p>You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.</p> <h4><a name="section11"></a>11. Patents.</h4> <p>A &ldquo;contributor&rdquo; is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's &ldquo;contributor version&rdquo;.</p> <p>A contributor's &ldquo;essential patent claims&rdquo; are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, &ldquo;control&rdquo; includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.</p> <p>Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.</p> <p>In the following three paragraphs, a &ldquo;patent license&rdquo; is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To &ldquo;grant&rdquo; such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.</p> <p>If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. &ldquo;Knowingly relying&rdquo; means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.</p> <p>If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.</p> <p>A patent license is &ldquo;discriminatory&rdquo; if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.</p> <p>Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.</p> <h4><a name="section12"></a>12. No Surrender of Others' Freedom.</h4> <p>If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.</p> <h4><a name="section13"></a>13. Use with the GNU Affero General Public License.</h4> <p>Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.</p> <h4><a name="section14"></a>14. Revised Versions of this License.</h4> <p>The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.</p> <p>Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License &ldquo;or any later version&rdquo; applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.</p> <p>If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.</p> <p>Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.</p> <h4><a name="section15"></a>15. Disclaimer of Warranty.</h4> <p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM &ldquo;AS IS&rdquo; WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p> <h4><a name="section16"></a>16. Limitation of Liability.</h4> <p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p> <h4><a name="section17"></a>17. Interpretation of Sections 15 and 16.</h4> <p>If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.</p> <p>END OF TERMS AND CONDITIONS</p> <h3><a name="howto"></a>How to Apply These Terms to Your New Programs</h3> <p>If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.</p> <p>To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the &ldquo;copyright&rdquo; line and a pointer to where the full notice is found.</p> <pre> &lt;one line to give the program's name and a brief idea of what it does.&gt; Copyright (C) &lt;year&gt; &lt;name of author&gt; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see &lt;http://www.gnu.org/licenses/&gt;. </pre> <p>Also add information on how to contact you by electronic and paper mail.</p> <p>If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:</p> <pre> &lt;program&gt; Copyright (C) &lt;year&gt; &lt;name of author&gt; This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. </pre> <p>The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an &ldquo;about box&rdquo;.</p> <p>You should also get your employer (if you work as a programmer) or school, if any, to sign a &ldquo;copyright disclaimer&rdquo; for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see &lt;<a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>&gt;.</p> <p>The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read &lt;<a href="http://www.gnu.org/philosophy/why-not-lgpl.html">http://www.gnu.org/philosophy/why-not-lgpl.html</a>&gt;.</p> </body></html>
zzyangming-szyangming
license.html
HTML
gpl3
38,296
#!/bin/bash set -e # fail early VERS="$1" [ -n "$VERS" ] && VERS="${VERS}_" function die() { echo "Error: " $* echo echo "USage: $0 <version>" echo "Automatically sign [A-Z].apk" exit 1 } [ -z "$1" ] && die shopt -s extglob # extended glob pattern function process() { SRC="$1" BASE="${SRC/.apk/}" DATE=`date +%Y%m%d` N=1 while /bin/true; do EXT=`python -c "print chr(96+$N)"` DEST="${BASE}_${VERS}${DATE}${EXT}.apk" [ ! -e "$DEST" ] && break N=$((N+1)) [ "$N" == "27" ] && die "$DEST exists, can't generate higher letter." done ALIAS="${USER/p*/lf}2" echo "Signing $SRC => $DEST with alias $ALIAS" jarsigner -verbose -keystore `cygpath -w ~/*-release-*.keystore` "$SRC" $ALIAS SIZE1=`stat -c "%s" "$SRC"` for z in ~/{usdk,sdk}/tools/zipalign.exe; do if [[ -x "$z" && -e "$SRC" ]]; then echo "Using $z" "$z" -f -v 4 "$SRC" "$DEST" && rm -v "$SRC" fi done [[ -e "$SRC" ]] && mv -v "$SRC" "$DEST" SIZE2=`stat -c "%s" "$DEST"` echo "$DEST has been signed and zipaligned (added $((SIZE2-SIZE1)) bytes)" } function update() { F="$1" K="Key" I="i" U="u" if ! unzip -l $F | grep -qs $K$I ; then echo "Missing file $K$I in $F" exit 2 else echo "Verified $K$I" fi if unzip -l $F | grep -qs $K$U ; then N=`unzip -l $F | grep $K$U | awk '{ print $4 }'` echo "Extra file $N found in $F" zip -d $F $N else echo "Verified !$K$U" fi } for i in [2]+([^_]).apk ; do if [ -f "$i" ]; then [[ "${i:0:1}" == "2" ]] && update "$i" process "$i" fi done
zzacharjasz-asd
distrib/_sign.sh
Shell
gpl3
1,533
<!-- * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. --> <!-- Language: default. Regions: any. --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style type="text/css"> body { color: white; } a:link { color: orange; } a:visited { color: green; } a:hover { color: yellow; } </style> </head> <body> <table width="100%" border="0"><tr> <td align="left"> <a href="/#new">What's New</a> </td> <td align="right"> <a href="/#known">Known Issues</a> </td> </tr></table> <hr> <!-- .............. --> <img src="file:///android_asset/icon24.png" width="48" height="48" align="right" /> <em> Everyday is a thrill ride. Manage that ride with the 24 clock. <br/> Jack your homescreen. A stylish widget clock where every second counts. <br/> The action never stops with hourly, 1/2 and 1/4 hour chimes. Full of options<!-- and integrated with Timeriffic -->. <br/> The following widget takes place on your desktop. Events occur in real time. </em> <p/> <!-- .............. --> <hr/> <a name="new"><h2>Features</h2></a> Day 1 features: <ul> <li>To create a new stylish 24 clock widget, <i>long-press</i> in Home and select <b>Widget &gt; 24 Clock</b>. </li> You can then configure widget specific options before installing your widget. <li>Use the "24" icon in the all-apps drawer to configure global settings such as hourly chime or global mute. </li> <li>Hourly chime and other sounds will <b>not</b> play when your device is muted, in vibrate-only or during a phone call. </li> <li>Battery saver: clock stops updating when the screen is off or after 30 seconds when you're not in the Home app. </li> </ul> <!-- .............. --> <hr/> <a name="known"><h2>Known Issues</h2></a> <ul> <li>The <em>24 Clock</em> widget has been tested with the default Android Home app. It may not work properly with alternate home apps. </li> <li>If you use a custom home app and the clock never updates in home, try to uncheck "Detect Home is Active" in the global options. </li> </ul> <!-- .............. --> <hr/> <h2>Credits</h2> Idea, artwork: <a href="http://dkworldwide.com/">Dave Kaufman</a>. <br/> Code: <a href="http://www.alfray.com/">Ralf</a>. <p/> <center><font size="-2"> Dave and Ralf have a master plan,<br/> but it's so cool they won't tell you.<br/> Version: <script type="text/javascript"> document.write(JSVersion.longVersion()); </script> </font></center> </body> </html>
zzacharjasz-asd
24ClockWidget/assets/intro.html
HTML
gpl3
3,250
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.alfray.a24clock.stats; import java.io.InputStream; import java.lang.reflect.Method; import android.content.Context; import android.util.Log; /** * Wrapper so that we don't depend directly on the agent lib. */ public class AgentWrapper { private static final boolean DEBUG = true; public static final String TAG = "TFC-Agent"; private static Class<?> mAgentClazz; private static String mK; public enum Event { GlobalOptions, WidgetOptions, WidgetAdded, OpenIntroUI } public AgentWrapper() { } public void start(Context context) { if (mAgentClazz == null) { String ks[] = null; try { InputStream is = null; try { is = context.getResources().getAssets().open("Keyi.txt"); } catch (Exception e) { is = context.getResources().getAssets().open("Keyu.txt"); } try { byte[] buf = new byte[255]; is.read(buf); String k = new String(buf); ks = k.trim().split(" "); } finally { if (is != null) is.close(); } if (ks == null || ks.length != 2) { if (DEBUG) Log.d(TAG, "startk failed"); return; } ClassLoader cl = context.getClassLoader(); Class<?> clazz = cl.loadClass(ks[0]); // start ok, keep the class mAgentClazz = clazz; mK = ks[1]; } catch (Exception e) { // ignore silently } } if (mAgentClazz != null) { try { Method m = mAgentClazz.getMethod("onStartSession", new Class<?>[] { Context.class, String.class }); m.invoke(null, new Object[] { context, mK }); } catch (Exception e) { // ignore silently } } } public void event(Event event) { if (mAgentClazz != null) { try { Method m = mAgentClazz.getMethod("onEvent", new Class<?>[] { String.class }); m.invoke(null, new Object[] { event.toString() }); } catch (Exception e) { // ignore silently } } } public void stop(Context context) { if (mAgentClazz != null) { try { Method m = mAgentClazz.getMethod("onEndSession", new Class<?>[] { Context.class }); m.invoke(null, new Object[] { context }); } catch (Exception e) { // ignore silently } } } }
zzacharjasz-asd
24ClockWidget/src/com/alfray/a24clock/stats/AgentWrapper.java
Java
gpl3
3,646
/* * Project: 24ClockWidget * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.alfray.a24clock.prefs; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.alfray.a24clock.R; /** * Access to pref values. * Some of the prefs (well currently all of them) depend on the current * widget ids. Some other prefs (currently none) are global to the app. */ public class PrefsValues { // Widget prefs public static final String KEY_USE_12_HOURS_MODE = "use_12_hours_mode"; public static final String KEY_USE_SOUND_TOUCH = "use_sound_touch"; // Global prefs public static final String KEY_USE_HOUR_CHIME = "use_hour_chime"; public static final String KEY_USE_CHIME_30 = "use_hour_chime_30"; public static final String KEY_USE_CHIME_15_45 = "use_hour_chime_15_45"; public static final String KEY_USE_OPTIONS_SOUND = "use_option_screen_sound"; public static final String KEY_USE_GLOBAL_MUTE = "use_global_mute"; public static final String KEY_DETECT_HOME = "detect_home"; public static final String KEY_DISMISS_INTRO = "dismiss_intro"; private SharedPreferences mWidgetPrefs; private SharedPreferences mGlobalPrefs; private final Context mContext; private final int mWidgetId; /** * Creates a {@link PrefsValues} to access widget-specific prefs * as well as global ones. */ public PrefsValues(Context context, int widgetId) { mContext = context; mWidgetId = widgetId; mGlobalPrefs = PreferenceManager.getDefaultSharedPreferences(context); if (widgetId >= 0) { // This does String.format("clock_%02d", widgetId) with a bit of an optim StringBuilder sb = new StringBuilder("clock_00000"); for (int i = widgetId, n = sb.length() - 1; i > 0; i /= 10, n--) { sb.setCharAt(n, (char) ('0' + (i % 10))); } mWidgetPrefs = context.getSharedPreferences(sb.toString(), Context.MODE_PRIVATE); } } public int getWidgetId() { return mWidgetId; } public boolean getDefault(String key) { if (key.equals(KEY_USE_12_HOURS_MODE)) { return Boolean.valueOf(mContext.getString(R.string.default_use_12_hours_mode)); } return key.equals(KEY_USE_SOUND_TOUCH) || key.equals(KEY_USE_OPTIONS_SOUND) || key.equals(KEY_DETECT_HOME); } public boolean getWidget(String key) { if (mWidgetPrefs != null && mWidgetPrefs.contains(key)) { return mWidgetPrefs.getBoolean(key, false); } return getDefault(key); } public boolean getGlobal(String key) { if (mGlobalPrefs != null && mGlobalPrefs.contains(key)) { return mGlobalPrefs.getBoolean(key, false); } return getDefault(key); } public boolean isWidgetPref(String key) { return key.equals(KEY_USE_12_HOURS_MODE) || key.equals(KEY_USE_SOUND_TOUCH); } public boolean get(String key) { if (isWidgetPref(key)) return getWidget(key); return getGlobal(key); } public boolean set(String key, boolean value) { if (isWidgetPref(key)) return setWidget(key, value); return setGlobal(key, value); } public boolean setWidget(String key, boolean value) { return mWidgetPrefs.edit().putBoolean(key, value).commit(); } public boolean setGlobal(String key, boolean value) { return mGlobalPrefs.edit().putBoolean(key, value).commit(); } public boolean use12HoursMode() { return getWidget(KEY_USE_12_HOURS_MODE); } public boolean useSoundTouch() { return getWidget(KEY_USE_SOUND_TOUCH); } public boolean useGlobalMute() { return getGlobal(KEY_USE_GLOBAL_MUTE); } public boolean useOptionsSound() { return getGlobal(KEY_USE_OPTIONS_SOUND); } public boolean useHourChime() { return getGlobal(KEY_USE_HOUR_CHIME); } public boolean useChime30() { return getGlobal(KEY_USE_CHIME_30); } public boolean useChime15_45() { return getGlobal(KEY_USE_CHIME_15_45); } public boolean detectHome() { return getGlobal(KEY_DETECT_HOME); } public void setIntroDismissed(boolean isChecked) { setGlobal(KEY_DISMISS_INTRO, isChecked); } public boolean isIntroDismissed() { return getGlobal(KEY_DISMISS_INTRO); } }
zzacharjasz-asd
24ClockWidget/src/com/alfray/a24clock/prefs/PrefsValues.java
Java
gpl3
5,312
/* * Project: 24ClockWidget * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.alfray.a24clock.prefs; import java.util.ArrayList; import java.util.Random; import android.app.Activity; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.database.DataSetObservable; import android.database.DataSetObserver; import android.media.AudioManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.os.Handler.Callback; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.View.OnClickListener; import android.view.ViewTreeObserver.OnPreDrawListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.RemoteViews; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import com.alfray.a24clock.ClockApp; import com.alfray.a24clock.IntroActivity; import com.alfray.a24clock.R; import com.alfray.a24clock.stats.AgentWrapper; import com.alfray.a24clock.stats.AgentWrapper.Event; /** * Activity to configure a new clock widget. * It's displayed when a new widget is created. The user must accept the * widget or it won't be dropped on home. * <p/> * Use {@link PrefsValues} to access the prefs later. * <p/> * TODO: * - Prefs are not coded in yet. * - No live preview */ public class ClockPrefsUI extends Activity { private static final String TAG = "ClockConfig"; //private static final boolean DEBUG = true; private static final int GLOBALS_ONLY = -1; private static final int MSG_REFRESH = 42; private int mWidgetId; private ClockApp mApp; private View mClockView; private PrefsValues mPrefValues; private Handler mHandler; private static class EntryViews { public ViewGroup mGroup; public TextView mSummary; public TextView mVTitle; public CheckBox mCheckBox; } private static class Entry { public final String mKey; public final String mStringOn; public final String mStringOff; public final String mTitle; public Entry mParent; public final ArrayList<Entry> mChildren = new ArrayList<Entry>(); public boolean mChildIsEnabled; public boolean mNegativeLogic; public boolean mCurrentState; public EntryViews mViews; private final int mType; public Entry(int type, String header) { mType = type; mKey = null; mStringOn = null; mStringOff = null; mTitle = header; mParent = null; } public Entry(int type, String key, String title, String stringOn, String stringOff, Entry parent) { mType = type; mKey = key; mTitle = title; mStringOn = stringOn; mStringOff = stringOff; mParent = parent; } } private final ArrayList<Entry> mEntries = new ArrayList<Entry>(); private ListView mList; private EntriesListAdapter mAdapter; private AgentWrapper mAgent; /** Called when the activity is first created. */ @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); mWidgetId = GLOBALS_ONLY; mApp = (ClockApp) getApplicationContext(); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, GLOBALS_ONLY); } // default result is to cancel creation setResult(Activity.RESULT_CANCELED); // This signals we only want to display global options // and no widget options. if (mWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { mWidgetId = GLOBALS_ONLY; } setContentView(R.layout.clock_prefs); setVolumeControlStream(AudioManager.STREAM_MUSIC); mPrefValues = mApp.getPrefsValues(mWidgetId); initGlobalOrWidget(); initPrefs(); initPrefList(); initDisplayClock(); } @Override public void onStart() { super.onStart(); // Play the initial sound if requested by the prefs and if this // is a real start, not a configuration change if (getLastNonConfigurationInstance() == null) { if (mPrefValues.useOptionsSound() && !mPrefValues.useGlobalMute()) { playSound(); } } displayIntroDelayed(); mAgent = new AgentWrapper(); mAgent.start(this); if (mWidgetId == GLOBALS_ONLY) { mAgent.event(Event.GlobalOptions); } else { mAgent.event(Event.WidgetOptions); } } @Override public void onStop() { super.onStop(); mAgent.stop(this); } @Override public Object onRetainNonConfigurationInstance() { // We return a random object, just to detect the next start // will be due to a config change (and avoid playing the sound) return new Object(); } @Override public void onResume() { super.onResume(); // start the refresh mHandler = new Handler(new RefreshCallback()); //--DEBUG-- mHandler.sendEmptyMessageDelayed(MSG_REFRESH, 900 /* ms */); } @Override public void onPause() { super.onPause(); // Stop the refresh if (mHandler != null) { mHandler.removeMessages(MSG_REFRESH); mHandler = null; } } // --- prefs private void playSound() { final View v = findViewById(R.id.prefs_ui_root); if (v != null) { final ViewTreeObserver obs = v.getViewTreeObserver(); obs.addOnPreDrawListener(new OnPreDrawListener() { @Override public boolean onPreDraw() { mApp.playSound(R.raw.startup_low); ViewTreeObserver obs2 = v.getViewTreeObserver(); obs2.removeOnPreDrawListener(this); return true; } }); } } private void initGlobalOrWidget() { if (mWidgetId == GLOBALS_ONLY) { // Globals only // Remove the clock+install part findViewById(R.id.clock_install).setVisibility(View.GONE); } else { // Widgets + Globals... with clock & install button // Remove the no_clock part findViewById(R.id.no_clock).setVisibility(View.GONE); Button b = (Button) findViewById(R.id.install); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onAccept(); } }); } for (int i = 0; i < 2; i++) { Button b = (Button) findViewById(i == 0 ? R.id.more : R.id.more2); if (b != null) { b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { displayIntro(); } }); } } } private void displayIntroDelayed() { if (mWidgetId == GLOBALS_ONLY && mApp.isFirstStart()) { final View v = findViewById(R.id.no_clock); if (v != null) { final ViewTreeObserver obs = v.getViewTreeObserver(); obs.addOnPreDrawListener(new OnPreDrawListener() { @Override public boolean onPreDraw() { displayIntro(); mApp.setFirstStart(false); ViewTreeObserver obs2 = v.getViewTreeObserver(); obs2.removeOnPreDrawListener(this); return true; } }); } } } private void displayIntro() { Intent i = new Intent(this, IntroActivity.class); startActivityForResult(i, 0); } private void initPrefs() { Entry pe1 = null; Entry pe2, pe3, pe4; if (mWidgetId != GLOBALS_ONLY) { mEntries.add(new Entry(EntriesListAdapter.TYPE_HEADER, "Widget Options")); addEntry(null, EntriesListAdapter.TYPE_PREF, PrefsValues.KEY_USE_12_HOURS_MODE, "Jack BHour Mode", "Displays 12 hour mode with AM/PM", "Displays Jack 24 Hour mode, no AM/PM"); pe1 = addEntry(null, EntriesListAdapter.TYPE_PREF, PrefsValues.KEY_USE_SOUND_TOUCH, "Physical Interrogation Mode", "Plays sound on touch, be gentle", "Does not play sound on touch"); mEntries.add(new Entry(EntriesListAdapter.TYPE_HEADER, "Global Options")); } pe2 = addEntry(null, EntriesListAdapter.TYPE_PREF, PrefsValues.KEY_USE_HOUR_CHIME, "Hour's Up Mode", "Plays hourly chime", "Does not play hourly chime"); addEntry(pe2, EntriesListAdapter.TYPE_PREF_CHILD, PrefsValues.KEY_USE_CHIME_30, "Time to panic", "Plays chime on 30 min mark", "Does not play chime on 30 min mark"); addEntry(pe2, EntriesListAdapter.TYPE_PREF_CHILD, PrefsValues.KEY_USE_CHIME_15_45, "Chloe checks in", "Plays chime on 15 and 45 min mark", "Does not play chime on 15 and 45 min mark"); pe3 = addEntry(null, EntriesListAdapter.TYPE_PREF, PrefsValues.KEY_USE_OPTIONS_SOUND, "Mood Setter Mode", "Plays sound on options screen", "Does not play sound on options screen"); pe4 = addEntry(null, EntriesListAdapter.TYPE_PREF, PrefsValues.KEY_USE_GLOBAL_MUTE, "Radio Silence Mode", "Mutes all sounds", "Sound settings as shown"); pe4.mNegativeLogic = true; addEntryChild(pe4, pe1); addEntryChild(pe4, pe2); addEntryChild(pe4, pe3); addEntry(null, EntriesListAdapter.TYPE_PREF, PrefsValues.KEY_DETECT_HOME, "Detect Home is Active", "Only update clock when Home is active", "Always update clock"); } private Entry addEntry( Entry parent, int type, final String key, String title, final String on, final String off) { final Entry pe = new Entry(type, key, title, on, off, parent); mEntries.add(pe); pe.mCurrentState = mPrefValues.get(key); if (parent != null) { addEntryChild(parent, pe); } return pe; } private void addEntryChild(Entry parent, Entry child) { if (parent != null && child != null) { parent.mChildren.add(child); child.mParent = parent; // the child is enabled only if all its parents are enabled too boolean enabled = true; while (enabled && parent != null) { enabled = parent.mNegativeLogic ? !parent.mCurrentState : parent.mCurrentState; parent = parent.mParent; } child.mChildIsEnabled = enabled; } } private void initPrefList() { mAdapter = new EntriesListAdapter(); mList = (ListView) findViewById(R.id.list); mList.setAdapter(mAdapter); mList.setClickable(true); mList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); mList.setDrawSelectorOnTop(false); mList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id) { Entry e = mEntries.get(position); String key = e.mKey; if (key == null || e.mViews.mCheckBox == null) return; boolean state = !e.mViews.mCheckBox.isChecked(); mPrefValues.set(key, state); e.mCurrentState = state; setState(e); if (e.mChildren.size() > 0) { mAdapter.notifyDataSetChanged(); } if (!mPrefValues.isWidgetPref(key)) { mApp.onGlobalPrefChanged(key, state); } } }); } private class EntriesListAdapter implements ListAdapter { public static final int TYPE_HEADER = 0; public static final int TYPE_PREF = 1; public static final int TYPE_PREF_CHILD = 2; private LayoutInflater mInflater; private final DataSetObservable mDataSetObservable = new DataSetObservable(); public EntriesListAdapter() { mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { Entry e = mEntries.get(position); if (e.mKey == null) return false; // headers are always disabled // if it has a parent (thus it's a child), Entry has the child state if (e.mParent != null) return e.mChildIsEnabled; return true; } @Override public int getCount() { return mEntries.size(); } @Override public Object getItem(int position) { return mEntries.get(position); } @Override public long getItemId(int position) { return position; } @Override public int getViewTypeCount() { return 3; } @Override public int getItemViewType(int position) { Entry e = mEntries.get(position); return e.mType; } @Override public boolean hasStableIds() { return true; } @Override public boolean isEmpty() { return false; } public void registerDataSetObserver(DataSetObserver observer) { mDataSetObservable.registerObserver(observer); } public void unregisterDataSetObserver(DataSetObserver observer) { mDataSetObservable.unregisterObserver(observer); } /** * Notifies the attached View that the underlying data has been changed * and it should refresh itself. */ public void notifyDataSetChanged() { mDataSetObservable.notifyChanged(); } @SuppressWarnings("unused") public void notifyDataSetInvalidated() { mDataSetObservable.notifyInvalidated(); } @Override public View getView(int position, View convertView, ViewGroup parent) { // We never use the old convertView (we don't recycle them anyway) Entry e = mEntries.get(position); EntryViews views = null; if (convertView != null && convertView.getTag() instanceof EntryViews) { views = (EntryViews) convertView.getTag(); } if (e.mType != TYPE_HEADER) { int resId = e.mType == TYPE_PREF ? R.layout.prefs15_entry : R.layout.prefs15_entry_child; if (views == null || views.mGroup == null || e.mViews != views) { ViewGroup group = (ViewGroup) mInflater.inflate(resId, parent, false); views = new EntryViews(); group.setTag(views); e.mViews = views; // IMPORTANT! The group must be set non-focusable so that the // the ListView Selector (which is located behind) can receive // the clicks and the focus. group.setFocusable(false); group.setFocusableInTouchMode(false); group.setClickable(false); views.mGroup = group; views.mVTitle = (TextView) group.findViewById(R.id.pref_title); views.mSummary = (TextView) group.findViewById(R.id.pref_summary); views.mCheckBox = (CheckBox) group.findViewById(R.id.pref_checkbox); } TextView vtitle = views.mVTitle; if (vtitle != null) vtitle.setText(e.mTitle); setState(e); return views.mGroup; } else { if (views == null || views.mGroup == null) { ViewGroup group = (ViewGroup) mInflater.inflate(R.layout.prefs_header, parent, false); views = new EntryViews(); group.setTag(views); views.mGroup = group; views.mVTitle = (TextView) group.findViewById(R.id.header); } if (e.mViews != views) { e.mViews = views; TextView vtitle = views.mVTitle; if (vtitle != null) vtitle.setText(e.mTitle); } return views.mGroup; } } } private void setState(Entry e) { EntryViews v = e.mViews; if (v == null) return; boolean state = e.mCurrentState; if (v.mSummary != null) v.mSummary.setText(state ? e.mStringOn : e.mStringOff); if (v.mCheckBox != null) v.mCheckBox.setChecked(state); if (e.mParent != null) { // the child is enabled only if all its parents are enabled too boolean enabled = true; Entry parent = e.mParent; while (enabled && parent != null) { enabled = parent.mNegativeLogic ? !parent.mCurrentState : parent.mCurrentState; parent = parent.mParent; } e.mChildIsEnabled = enabled; enableViewGroup(v.mGroup, enabled); } else { enableViewGroup(v.mGroup, true); } } private void enableViewGroup(View v, boolean enabled) { if (v == null) return; v.setEnabled(enabled); if (v instanceof ViewGroup) { ViewGroup g = (ViewGroup) v; for (int n = g.getChildCount() - 1; n >= 0; n--) { enableViewGroup(g.getChildAt(n), enabled); } } } // --- clock display private void initDisplayClock() { if (mWidgetId == GLOBALS_ONLY) return; ViewGroup clockRoot = (ViewGroup) findViewById(R.id.clock_root); if (clockRoot == null) return; try { RemoteViews rviews = mApp.configureRemoteView(mWidgetId, false /*enableTouch*/); mClockView = rviews.apply(this, clockRoot); clockRoot.addView(mClockView); mClockView.setClickable(false); mClockView.setFocusable(true); clockRoot.setClickable(true); clockRoot.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Bundle extras = new Bundle(1); extras.putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId); mApp.triggerUserAction(extras); } }); } catch (Exception e) { Log.d(TAG, "Inflate clock failed", e); } } private class RefreshCallback implements Callback { private long mMeanUpdateTime; @Override public boolean handleMessage(Message msg) { if (msg.what == MSG_REFRESH && mHandler != null) { long now = SystemClock.uptimeMillis(); if (hasWindowFocus()) { refreshClockDisplay(); } // DEBUG long timeToUpdate = SystemClock.uptimeMillis() - now; if (mMeanUpdateTime == 0) { mMeanUpdateTime = timeToUpdate; } else { mMeanUpdateTime = (mMeanUpdateTime + timeToUpdate) / 2; } Log.d(TAG, String.format("Time to update: %d / %d", timeToUpdate, mMeanUpdateTime)); if (Long.MAX_VALUE - now > 1000) { now += 1000; } else { now = Long.MAX_VALUE; } mHandler.sendEmptyMessageAtTime(MSG_REFRESH, now); } return false; } } private void refreshClockDisplay() { if (mClockView != null) { try { RemoteViews rviews = mApp.configureRemoteView(mWidgetId, false /*enableTouch*/); rviews.reapply(this, mClockView); } catch (Exception e) { Log.d(TAG, "Inflate clock failed", e); } } } // --- accept & finish private void onAccept() { // stop the refresh if (mHandler != null) { mHandler.removeMessages(MSG_REFRESH); mHandler = null; } AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); RemoteViews rviews = mApp.configureRemoteView(mWidgetId, true /*enableTouch*/); appWidgetManager.updateAppWidget(mWidgetId, rviews); Intent resultValue = new Intent(); resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId); setResult(RESULT_OK, resultValue); if (mAgent != null) { mAgent.event(Event.WidgetAdded); } Random rnd = new Random(); if (rnd.nextFloat() < .3) { // 30% chance to get the effect mApp.playSound(R.raw.easter); } finish(); } }
zzacharjasz-asd
24ClockWidget/src/com/alfray/a24clock/prefs/ClockPrefsUI.java
Java
gpl3
23,930
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.alfray.a24clock; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ProgressBar; import android.widget.CompoundButton.OnCheckedChangeListener; import com.alfray.a24clock.prefs.PrefsValues; import com.alfray.a24clock.stats.AgentWrapper; /** * Screen with the introduction text. */ public class IntroActivity extends Activity { private static final boolean DEBUG = true; public static final String TAG = "24Clock-IntroUI"; public static final String EXTRA_NO_CONTROLS = "no-controls"; private AgentWrapper mAgentWrapper; private class JSVersion { private String mVersion; public String longVersion() { if (mVersion == null) { PackageManager pm = getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(getPackageName(), 0); mVersion = pi.versionName; if (mVersion == null) mVersion = ""; } catch (NameNotFoundException e) { mVersion = ""; // failed, ignored } } return mVersion; } public String shortVersion() { String v = longVersion(); if (v != null) { int pos = v.lastIndexOf('.'); if (pos > 0) v = v.substring(0, pos); } return v; } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intro); JSVersion jsVersion = new JSVersion(); String title = getString(R.string.intro_title, jsVersion.shortVersion()); setTitle(title); final WebView wv = (WebView) findViewById(R.id.web); if (wv == null) { if (DEBUG) Log.d(TAG, "Missing web view"); finish(); } // Make the webview transparent (for background gradient) wv.setBackgroundColor(0x00000000); // Inject a JS method to set the version wv.getSettings().setJavaScriptEnabled(true); wv.addJavascriptInterface(jsVersion, "JSVersion"); String file = selectFile("intro"); loadFile(wv, file); setupProgressBar(wv); setupWebViewClient(wv); setupButtons(); } @Override protected void onResume() { super.onResume(); mAgentWrapper = new AgentWrapper(); mAgentWrapper.start(this); mAgentWrapper.event(AgentWrapper.Event.OpenIntroUI); } @Override protected void onPause() { super.onPause(); mAgentWrapper.stop(this); } private String selectFile(String baseName) { // Compute which file we want to display, i.e. try to select // one that matches baseName-LocaleCountryName.html or default // to intro.html String file = baseName + ".html"; Locale lo = Locale.getDefault(); String lang = lo.getLanguage(); if (lang != null && lang.length() == 2) { InputStream is = null; String file2 = baseName + "-" + lang + ".html"; try { AssetManager am = getResources().getAssets(); is = am.open(file2); if (is != null) { file = file2; } } catch (IOException e) { if (!"en".equals(lang)) { if (DEBUG) Log.d(TAG, "Language not found: " + lang); } } finally { if (is != null) { try { is.close(); } catch (IOException e) { // pass } } } } return file; } private void loadFile(final WebView wv, String file) { wv.loadUrl("file:///android_asset/" + file); wv.setFocusable(true); wv.setFocusableInTouchMode(true); wv.requestFocus(); } private void setupProgressBar(final WebView wv) { final ProgressBar progress = (ProgressBar) findViewById(R.id.progress); if (progress != null) { wv.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { progress.setProgress(newProgress); progress.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE); } }); } } private void setupWebViewClient(final WebView wv) { wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.endsWith("/#new")) { wv.loadUrl("javascript:location.href=\"#new\""); return true; } else if (url.endsWith("/#known")) { wv.loadUrl("javascript:location.href=\"#known\""); return true; } else if (url.startsWith("market://")) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); try { startActivity(intent); } catch (ActivityNotFoundException e) { // ignore. just means this device has no Market app // so maybe it's an emulator. } return true; } return false; } }); } private void setupButtons() { boolean hideControls = false; Intent i = getIntent(); if (i != null) { Bundle e = i.getExtras(); if (e != null) hideControls = e.getBoolean(EXTRA_NO_CONTROLS); } CheckBox dismiss = (CheckBox) findViewById(R.id.dismiss); if (dismiss != null) { if (hideControls) { dismiss.setVisibility(View.GONE); } else { final PrefsValues pv = new PrefsValues(this, -1); dismiss.setChecked(pv.isIntroDismissed()); dismiss.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { pv.setIntroDismissed(isChecked); } }); } } Button cont = (Button) findViewById(R.id.cont); if (cont != null) { if (hideControls) { cont.setVisibility(View.GONE); } else { cont.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // close activity finish(); } }); } } } }
zzacharjasz-asd
24ClockWidget/src/com/alfray/a24clock/IntroActivity.java
Java
gpl3
8,813
/* * Project: 24ClockWidget * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.alfray.a24clock; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import android.app.ActivityManager; import android.app.AlarmManager; import android.app.Application; import android.app.PendingIntent; import android.app.ActivityManager.RunningTaskInfo; import android.appwidget.AppWidgetManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; import android.view.View; import android.widget.RemoteViews; import com.alfray.a24clock.prefs.PrefsValues; public class ClockApp extends Application { private static boolean DEBUG = true; private static String TAG = "ClockApp"; /** * Bitmaps for the digits: 0-9. * The index {@link #kColonIndex} (10) is the colon. */ private Bitmap[] mDigits = null; private static final int kColonIndex = 10; private static final int kDigitsViewIds[] = { R.id.bmp0, R.id.bmp1, R.id.bmp2, R.id.bmp3, R.id.bmp4, R.id.bmp5, R.id.bmp6, R.id.bmp7 }; private BroadcastReceiver mStickyReceiver; private final SimpleDateFormat mSimpleDateFormat[] = new SimpleDateFormat[2]; private static Object sLock = new Object(); /** Assume screen is on unless told it's not */ private boolean mScreenOn = true; /** Media player, playing the current sound (we don't play more than 1 sound at once) */ private MediaPlayer mPlayer; /** Telephony manager. Could be null. */ private TelephonyManager mTelephonyMan; /** The last PrefsValues accessed, cached for a given widget id. * This is an obvious optim since most of the time we'll access the same * prefs over and over. */ private PrefsValues mLastPrefValues; private boolean mFirstStart = true; @Override public void onCreate() { super.onCreate(); mTelephonyMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); ClockService.start(getApplicationContext(), null); registerScreenStateReceiver(); initPeriodicAlarm(); } @Override public void onTerminate() { if (mPlayer != null) { MediaPlayer p; synchronized (sLock) { p = mPlayer; if (p != null) mPlayer = null; } if (p != null) p.release(); } removeScreenStateReceiver(); super.onTerminate(); } public boolean isFirstStart() { return mFirstStart; } public void setFirstStart(boolean firstStart) { mFirstStart = firstStart; } private void registerScreenStateReceiver() { IntentFilter ioff = new IntentFilter(Intent.ACTION_SCREEN_OFF); IntentFilter ion = new IntentFilter(Intent.ACTION_SCREEN_ON); mStickyReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_SCREEN_OFF.equals(action)) { setIsScreenOn(false); } else { setIsScreenOn(true); // start the service ClockService.start(getApplicationContext(), null); } } }; registerReceiver(mStickyReceiver, ioff); registerReceiver(mStickyReceiver, ion); } private void removeScreenStateReceiver() { if (mStickyReceiver != null) { unregisterReceiver(mStickyReceiver); } } /** * Returns all the bitmaps for the digits: 0-9. * The index 10 is the colon. */ public Bitmap[] getDigitsBmps() { if (mDigits == null) { mDigits = prepareDigitsBitmaps(); } return mDigits; } private Bitmap[] prepareDigitsBitmaps() { Bitmap bmp = getResBitmap(this, R.drawable.monotextstring_v3); // scan the top line to find start & size int start[] = new int[12]; int width[] = new int[12]; int index = -1; int w = bmp.getWidth(); for (int x = 0; x < w && index < 11; x++) { int c = bmp.getPixel(x, 0); if ((c & 0x0000FF00) < 0x0000AA00) { // not green: start new pixel. if (index >= 0) { // close last one first width[index] = x - start[index]; } start[++index] = x; } } // now split them assert index == 10; Bitmap[] dest = new Bitmap[index]; int h = bmp.getHeight(); for (int i = 0; i < index; i++) { dest[i] = Bitmap.createBitmap(bmp, start[i], 1, // x y width[i], h-1); // w h } return dest; } /** * Utility method to get a Bitmap from a resource id. */ private Bitmap getResBitmap(Context context, int bmpResId) { Options opts = new Options(); opts.inDither = false; // The Options.inScaled field is only available starting at API 4 // so let's use reflection to set it safely. try { Field f = opts.getClass().getField("inScaled"); try { f.setAccessible(true); } catch (SecurityException ignore) { } f.set(opts, Boolean.FALSE); } catch (Exception ignore) { if (DEBUG) Log.d(TAG, "Options.isScale=false failed", ignore); } Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), bmpResId, opts); if (DEBUG) Log.d(TAG, bmp == null ? "getResBitmap => NULL" : String.format("getResBitmap => %dx%d", bmp.getWidth(), bmp.getHeight())); return bmp; } public SimpleDateFormat getDateFormat(boolean use24) { int index = use24 ? 1 : 0; if (mSimpleDateFormat[index] == null) { mSimpleDateFormat[index] = new SimpleDateFormat( use24 ? "HH:mm:ss" // 8 chars : "hh:mm:ssa" // 10 chars (8 time + AM/PM) ); } return mSimpleDateFormat[index]; } /** * Updates the clock display for the given widget ids */ public void updateRemoteView(AppWidgetManager appWidgetManager, int[] appWidgetIds) { if (appWidgetIds == null || appWidgetManager == null) return; for (int widgetId : appWidgetIds) { RemoteViews rviews = configureRemoteView(widgetId, true /*enableTouch*/); appWidgetManager.updateAppWidget(new int[] { widgetId }, rviews); } } /** * Returns the PrefsValues, cached for a given widget id. * This is an obvious optim since most of the time we'll access the same * prefs over and over. * * widgetId can be -1 to get any prefs values for global prefs. */ public synchronized PrefsValues getPrefsValues(int widgetId) { PrefsValues prefs = mLastPrefValues; if (prefs != null && (widgetId == -1 || prefs.getWidgetId() == widgetId)) { return prefs; } prefs = mLastPrefValues = new PrefsValues(this, widgetId); return prefs; } /** * Configures an existing remote views mapping our clock widget * {@link R.layout#clock_widget} with the current state of that * widget id. * * TODO this calls for some serious optimizations, e.g. add flags to * only update what changed in the views (time, am/pm, intent, etc.) * and avoid the expensive date format. */ public RemoteViews configureRemoteView(int widgetId, boolean enableTouch) { PrefsValues prefs = getPrefsValues(widgetId); RemoteViews rviews = new RemoteViews(getPackageName(), R.layout.clock_widget); boolean use24 = !prefs.use12HoursMode(); // format time (TODO too heavy, need to replace by something lightweight) SimpleDateFormat sdf = getDateFormat(use24); // 8 or 10 chars Calendar now = Calendar.getInstance(); sdf.setCalendar(now); char[] digits = sdf.format(now.getTime()).toCharArray(); // get bitmaps from main app Bitmap[] digitsBmps = getDigitsBmps(); for (int i = 0; i < 8; i++) { char c = digits[i]; if (c >= '0' && c <= '9') { c -= '0'; rviews.setImageViewBitmap(kDigitsViewIds[i], digitsBmps[c]); } else { rviews.setImageViewBitmap(kDigitsViewIds[i], digitsBmps[ClockApp.kColonIndex]); } } if (use24) { rviews.setViewVisibility(R.id.am_pm_bmp, View.INVISIBLE); } else { rviews.setViewVisibility(R.id.am_pm_bmp, View.VISIBLE); boolean isAM = digits.length > 8 && digits[8] == 'A'; rviews.setImageViewResource(R.id.am_pm_bmp, isAM ? R.drawable.am : R.drawable.pm); } if (widgetId > 0 && enableTouch && prefs.useSoundTouch()) { // Create an intent for the sound trigger. Specific to the given class. Intent i = new Intent(this, ClockWidgetReceiver.class); // We need the action to filter in the receiver. i.setAction(ClockWidgetReceiver.ACTION_USER_CLOCK); // The data is just to make the intent unique for this widget. Uri uri = ContentUris.withAppendedId(ClockWidgetReceiver.CONTENT_URI, widgetId); i.setData(uri); // Values expected by triggerUserAction() below i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId); PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); rviews.setOnClickPendingIntent(R.id.outer, pi); } return rviews; } /** * Returns true if phone state is in "idle" mode -- not ringing, not in-call. */ public boolean isCallStateIdle() { if (mTelephonyMan != null) { return mTelephonyMan.getCallState() == TelephonyManager.CALL_STATE_IDLE; } return true; } public boolean currentTaskIsHome() { // get a pref values suitable for global prefs to check if we should // detect home PrefsValues pv = getPrefsValues(-1); if (!pv.detectHome()) { return true; } ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> runningTasks = am.getRunningTasks(2); for (RunningTaskInfo t : runningTasks) { if (t != null && t.numRunning > 0) { ComponentName cn = t.baseActivity; if (cn == null) continue; String clz = cn.getClassName(); // Workaround: this is a phantom activity that stays on the // top because it is killed in a weird way. if ("com.alfray.timeriffic.utils.ChangeBrightnessActivity".equals(clz)) { continue; } String pkg = cn.getPackageName(); // TODO make this configurable if (pkg != null && pkg.startsWith("com.android.launcher")) { return true; } return false; } } return false; } public void setIsScreenOn(boolean isScreenOn) { mScreenOn = isScreenOn; } public boolean isScreenOn() { return mScreenOn; } public void triggerUserAction(Bundle extras) { int wid = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); if (wid > -1) { // double check we can really play a sound for this widget PrefsValues pv = getPrefsValues(wid); if (pv.useSoundTouch() && !pv.useGlobalMute()) { playSound(R.raw.clockeffect_2sec); } } } public void triggerHourChime(Bundle extras) { // get a pref values suitable for global prefs PrefsValues pv = getPrefsValues(-1); if (pv.useGlobalMute() || !pv.useHourChime()) { // skip if global mute is off or hour chime got deactivated // in between. return; } int level = extras == null ? 0 : extras.getInt("level"); if (level == 15 && !pv.useChime15_45()) level = 0; if (level == 30 && !pv.useChime30()) level = 0; if (level > 0) { playSound(R.raw.clockeffect_2sec); } initPeriodicAlarm(); } public void playSound(int res_id) { // We never play sound during calls if (!isCallStateIdle()) return; AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (manager != null) { if (manager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) { // The phone is either set to silent+vibrate or // silent+no-vibrate, so don't playing sound. return; } if (manager.getStreamVolume(AudioManager.STREAM_RING) <= 0) { // Main ring volume is set to 0, respect that and avoid // making playing sound. } } // stop existing one, if any MediaPlayer p; if (mPlayer != null) { synchronized (sLock) { p = mPlayer; if (p != null) mPlayer = null; } if (p != null) p.release(); } mPlayer = p = MediaPlayer.create(this, res_id); if (DEBUG) Log.d(TAG, "New MediaPlayer: " + ((p == null)?"null":p.toString())); if (p != null) { try { // Sleep till the begining of the next second. // This will block this thread for at most 1 second. long now = System.currentTimeMillis(); now = 1100 - (now - 1000*(now / 1000)); if (now > 0) { try { Thread.sleep(now); // --debug-- Log.d(TAG, "Slept " + Long.toString(now)); } catch (InterruptedException e) { // ignore } } p.start(); if (DEBUG) Log.d(TAG, "MediaPlayer started"); } catch (IllegalStateException e) { Log.d(TAG, "MediaPlayer.start error", e); } } } public void onGlobalPrefChanged(String key, boolean state) { if (state) { if (key.equals(PrefsValues.KEY_USE_HOUR_CHIME) || key.equals(PrefsValues.KEY_USE_CHIME_30) || key.equals(PrefsValues.KEY_USE_CHIME_15_45)) { initPeriodicAlarm(); } } } private void initPeriodicAlarm() { // get a pref values suitable for global prefs PrefsValues pv = getPrefsValues(-1); if (pv.useGlobalMute() || !pv.useHourChime()) { // don't schedule anything if global mute is on or // hour chime is not activated. return; } // get current time Calendar c = Calendar.getInstance(); long now = c.getTimeInMillis(); int minutes = c.get(Calendar.MINUTE); // round it up to a quarter int quarter = minutes / 15; int intent_level = 0; if (pv.useChime15_45()) { quarter++; intent_level = 15; } else if (pv.useChime30()) { quarter /= 2; quarter = 2 * (quarter + 1); intent_level = 30; } else { // hour mode quarter /= 4; quarter = 4 * (quarter + 1); intent_level = 60; } // delta minutes = (quarter * 15) - minutes; c.set(Calendar.SECOND, 0); c.add(Calendar.MINUTE, minutes); // set alarm AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); if (manager != null) { long timeMs = c.getTimeInMillis(); Intent intent = new Intent(this, ClockWidgetReceiver.class); intent.setAction(ClockWidgetReceiver.ACTION_HOUR_CHIME); intent.putExtra("level", intent_level); PendingIntent op = PendingIntent.getBroadcast( this, 0 /*requestCode*/, intent, PendingIntent.FLAG_UPDATE_CURRENT); manager.set(AlarmManager.RTC_WAKEUP, timeMs, op); Log.d(TAG, String.format("Next chime alarm [%d]: %d (+%d)", intent_level, timeMs, timeMs - now)); } } }
zzacharjasz-asd
24ClockWidget/src/com/alfray/a24clock/ClockApp.java
Java
gpl3
18,804
/* * Project: 24ClockWidget * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.alfray.a24clock; import android.util.Log; //----------------------------------------------- public abstract class BaseThread extends Thread { private static final String TAG = "BaseThread"; protected boolean mContinue = true; public BaseThread(String name) { super(name); this.setPriority(Thread.currentThread().getPriority()+1); } /** * Called by the main activity when it's time to stop. * <p/> * Requirement: this MUST be called from another thread, not from GLBaseThread. * The activity thread is supposed to called this. * <p/> * This lets the thread complete it's render loop and wait for it * to fully stop using a join. */ public void waitForStop() { // Not synchronized. Setting one boolean is assumed to be atomic. mContinue = false; try { assert Thread.currentThread() != this; wakeUp(); join(); } catch (InterruptedException e) { Log.e(TAG, "Thread.join failed", e); } } /** * Starts the thread if it wasn't already started. * Does nothing if started. */ @Override public synchronized void start() { if (getState() == State.NEW) { super.start(); } } // ----------------- /** * Base implementation of the thread loop. * Derived classes can re-implement this, as long as they follow this * contract: * - the loop must continue whilst mContinue is true * - each iteration must invoke runIteration() when not paused. * - the loop must pause when mIsPaused is true by first waiting for * the pause barrier and do a waitForALongTime() until mIsPaused is * released. */ @Override public void run() { try { startRun(); while (mContinue) { runIteration(); } } catch (Exception e) { Log.e(TAG, "Run-Loop Exception, stopping thread", e); } finally { endRun(); } } protected void startRun() {} /** * Performs one iteration of the thread run loop. * Implementations must implement this and not throw exceptions from it. */ protected abstract void runIteration(); protected void endRun() {} protected void setCompleted() { mContinue = false; } protected void wakeUp() { this.interrupt(); } protected void waitFor(long time_ms) { try { synchronized(this) { if (time_ms > 0) wait(time_ms); } } catch (InterruptedException e) { // pass } } }
zzacharjasz-asd
24ClockWidget/src/com/alfray/a24clock/BaseThread.java
Java
gpl3
3,347
/* * Project: 24ClockWidget * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.alfray.a24clock; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; public class ClockWidgetReceiver extends AppWidgetProvider { /** Name of intent to broadcast to activate this receiver. */ public static final String ACTION_USER_CLOCK = "com.alfray.intent.action.ACTION_USER_CLOCK"; public static final String ACTION_HOUR_CHIME = "com.alfray.intent.action.ACTION_HOUR_CHIME"; public static final String AUTHORITY = "com.alfray.a24clock"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/wid"); private static boolean DEBUG = true; private static String TAG = "ClockWidgetReceiver"; private ClockApp mApp; public ClockWidgetReceiver() { // Nothing here. This is constructed for *each* call. } private ClockApp getApp(Context context) { if (mApp == null) { mApp = (ClockApp) context.getApplicationContext(); } return mApp; } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USER_CLOCK.equals(action)) { if (DEBUG) Log.d(TAG, "Receive: " + intent.toString()); getApp(context).triggerUserAction(intent.getExtras()); return; } else if (ACTION_HOUR_CHIME.equals(action)) { if (DEBUG) Log.d(TAG, "Receive: " + intent.toString()); getApp(context).triggerHourChime(intent.getExtras()); return; } super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // appWidgetIds contains the ids of the *new* updates. We need all // widgets, even existing ones. appWidgetIds = AppWidgetManager.getInstance(context).getAppWidgetIds( new ComponentName(context, this.getClass())); // Nothing to update? We shouldn't be here. if (appWidgetIds == null || appWidgetIds.length == 0) { if (DEBUG) Log.d(TAG, "onUpdate , *no* widgets!"); return; } if (DEBUG) Log.d(TAG, String.format("onUpdate, %d widgets", appWidgetIds.length)); ClockService.start(context, appWidgetIds); } @Override public void onEnabled(Context context) { if (DEBUG) Log.d(TAG, String.format("onEnabled")); } @Override public void onDisabled(Context context) { if (DEBUG) Log.d(TAG, String.format("onDisabled")); ClockService.stop(); } @Override public void onDeleted(Context context, int[] appWidgetIds) { if (DEBUG) Log.d(TAG, String.format("onDeleted")); super.onDeleted(context, appWidgetIds); } }
zzacharjasz-asd
24ClockWidget/src/com/alfray/a24clock/ClockWidgetReceiver.java
Java
gpl3
3,822
/* * Project: 24ClockWidget * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.alfray.a24clock; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class ClockService extends Service { private static boolean DEBUG = false; private static String TAG = "ClockService"; private static final Object kLock = new Object(); private static int[] sCachedIds = null; private static ClockThread sThread; private static final long DELAY_MS = 30 * 1000; @Override public IBinder onBind(Intent intent) { if (DEBUG) Log.d(TAG, "onBind"); return null; } public static void start(Context context, int[] appWidgetIds) { ClockThread ct; synchronized (kLock) { ct = sThread; ClockService.sCachedIds = appWidgetIds; } if (ct == null) { Intent i = new Intent(context, ClockService.class); context.startService(i); } else { ct.wakeUp(); } } public static void stop() { synchronized (kLock) { if (sThread != null) { sThread.setCompleted(); sThread = null; } } } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); if (DEBUG) Log.d(TAG, "onStart, thread=" + ((sThread==null)?"none":sThread.toString())); synchronized (kLock) { if (sThread == null) { sThread = new ClockThread((ClockApp) getApplicationContext()); sThread.start(); } else { sThread.wakeUp(); } } } private static class ClockThread extends BaseThread { private ClockApp mApp; private AppWidgetManager mAWMan; private int mNotHomeDelay = 0; private long mLastMinute; public ClockThread(ClockApp app) { super("ClockThread"); mApp = app; mAWMan = AppWidgetManager.getInstance(mApp); mLastMinute = 0; } @Override protected void runIteration() { long now = System.currentTimeMillis(); if (!mApp.isScreenOn()) { if (DEBUG) Log.d(TAG, "loop, screen on=>off, stopping"); // stop the thread if the screen is not running synchronized (kLock) { setCompleted(); sThread = null; return; } } long waitNext = 0; boolean needUpdate = false; if (mApp.currentTaskIsHome()) { mNotHomeDelay = 0; mLastMinute = 0; needUpdate = true; waitNext = 1000; } else { // check again in 10 seconds if not in home if (mNotHomeDelay < 30) mNotHomeDelay += 5; if (DEBUG) Log.d(TAG, "loop, not home, wait " + Integer.toString(mNotHomeDelay)); // however we still perform an update every minute long minute = now / DELAY_MS; long nextMinute = DELAY_MS - (now - (minute * DELAY_MS)); if (mLastMinute == 0) { mLastMinute = minute; } else if (mLastMinute != minute) { mLastMinute = minute; needUpdate = true; } waitNext = mNotHomeDelay * 1000 /*ms*/; if (nextMinute < waitNext) { if (DEBUG) Log.d(TAG, "minute wait: " + Long.toString(nextMinute)); waitNext = nextMinute; } } // perform an update if (needUpdate && mAWMan != null) { int[] ids; synchronized (kLock) { ids = sCachedIds; } if (ids == null) { ids = mAWMan.getAppWidgetIds(new ComponentName(mApp, ClockWidgetReceiver.class)); if (ids != null) { synchronized (kLock) { sCachedIds = ids; } } } if (ids != null && ids.length > 0) { // Update remote view mApp.updateRemoteView(mAWMan, ids); } } if (waitNext > 0) { waitNext -= System.currentTimeMillis() - now; if (DEBUG) Log.d(TAG, "waitNext: " + Long.toString(waitNext)); waitFor(waitNext); } } } }
zzacharjasz-asd
24ClockWidget/src/com/alfray/a24clock/ClockService.java
Java
gpl3
5,691
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #ifndef POLY2TRI_H #define POLY2TRI_H #include "common/shapes.h" #include "sweep/cdt.h" #endif
zzg0078426-betterperformance-v8
poly2tri/poly2tri.h
C
bsd
1,721
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #ifndef ADVANCED_FRONT_H #define ADVANCED_FRONT_H #include "../common/shapes.h" namespace p2t { struct Node; // Advancing front node struct Node { Point* point; Triangle* triangle; Node* next; Node* prev; double value; Node(Point& p) : point(&p), triangle(NULL), next(NULL), prev(NULL), value(p.x) { } Node(Point& p, Triangle& t) : point(&p), triangle(&t), next(NULL), prev(NULL), value(p.x) { } }; // Advancing front class AdvancingFront { public: AdvancingFront(Node& head, Node& tail); // Destructor ~AdvancingFront(); Node* head(); void set_head(Node* node); Node* tail(); void set_tail(Node* node); Node* search(); void set_search(Node* node); /// Locate insertion point along advancing front Node* LocateNode(const double& x); Node* LocatePoint(const Point* point); private: Node* head_, *tail_, *search_node_; Node* FindSearchNode(const double& x); }; inline Node* AdvancingFront::head() { return head_; } inline void AdvancingFront::set_head(Node* node) { head_ = node; } inline Node* AdvancingFront::tail() { return tail_; } inline void AdvancingFront::set_tail(Node* node) { tail_ = node; } inline Node* AdvancingFront::search() { return search_node_; } inline void AdvancingFront::set_search(Node* node) { search_node_ = node; } } #endif
zzg0078426-betterperformance-v8
poly2tri/sweep/advancing_front.h
C++
bsd
2,928
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #include "sweep_context.h" #include <algorithm> #include "advancing_front.h" namespace p2t { SweepContext::SweepContext(std::vector<Point*> polyline) { basin = Basin(); edge_event = EdgeEvent(); points_ = polyline; InitEdges(points_); } void SweepContext::AddHole(std::vector<Point*> polyline) { InitEdges(polyline); for(unsigned int i = 0; i < polyline.size(); i++) { points_.push_back(polyline[i]); } } void SweepContext::AddPoint(Point* point) { points_.push_back(point); } std::vector<Triangle*> SweepContext::GetTriangles() { return triangles_; } std::list<Triangle*> SweepContext::GetMap() { return map_; } void SweepContext::InitTriangulation() { double xmax(points_[0]->x), xmin(points_[0]->x); double ymax(points_[0]->y), ymin(points_[0]->y); // Calculate bounds. for (unsigned int i = 0; i < points_.size(); i++) { Point& p = *points_[i]; if (p.x > xmax) xmax = p.x; if (p.x < xmin) xmin = p.x; if (p.y > ymax) ymax = p.y; if (p.y < ymin) ymin = p.y; } double dx = kAlpha * (xmax - xmin); double dy = kAlpha * (ymax - ymin); head_ = new Point(xmax + dx, ymin - dy); tail_ = new Point(xmin - dx, ymin - dy); // Sort points along y-axis std::sort(points_.begin(), points_.end(), cmp); } void SweepContext::InitEdges(std::vector<Point*> polyline) { int num_points = polyline.size(); for (int i = 0; i < num_points; i++) { int j = i < num_points - 1 ? i + 1 : 0; edge_list.push_back(new Edge(*polyline[i], *polyline[j])); } } Point* SweepContext::GetPoint(const int& index) { return points_[index]; } void SweepContext::AddToMap(Triangle* triangle) { map_.push_back(triangle); } Node& SweepContext::LocateNode(Point& point) { // TODO implement search tree return *front_->LocateNode(point.x); } void SweepContext::CreateAdvancingFront(std::vector<Node*> nodes) { (void) nodes; // Initial triangle Triangle* triangle = new Triangle(*points_[0], *tail_, *head_); map_.push_back(triangle); af_head_ = new Node(*triangle->GetPoint(1), *triangle); af_middle_ = new Node(*triangle->GetPoint(0), *triangle); af_tail_ = new Node(*triangle->GetPoint(2)); front_ = new AdvancingFront(*af_head_, *af_tail_); // TODO: More intuitive if head is middles next and not previous? // so swap head and tail af_head_->next = af_middle_; af_middle_->next = af_tail_; af_middle_->prev = af_head_; af_tail_->prev = af_middle_; } void SweepContext::RemoveNode(Node* node) { delete node; } void SweepContext::MapTriangleToNodes(Triangle& t) { for (int i = 0; i < 3; i++) { if (!t.GetNeighbor(i)) { Node* n = front_->LocatePoint(t.PointCW(*t.GetPoint(i))); if (n) n->triangle = &t; } } } void SweepContext::RemoveFromMap(Triangle* triangle) { map_.remove(triangle); } void SweepContext::MeshClean(Triangle& triangle) { if (&triangle != NULL && !triangle.IsInterior()) { triangle.IsInterior(true); triangles_.push_back(&triangle); for (int i = 0; i < 3; i++) { if (!triangle.constrained_edge[i]) MeshClean(*triangle.GetNeighbor(i)); } } } SweepContext::~SweepContext() { // Clean up memory delete head_; delete tail_; delete front_; delete af_head_; delete af_middle_; delete af_tail_; typedef std::list<Triangle*> type_list; for(type_list::iterator iter = map_.begin(); iter != map_.end(); ++iter) { Triangle* ptr = *iter; delete ptr; } for(unsigned int i = 0; i < edge_list.size(); i++) { delete edge_list[i]; } } }
zzg0078426-betterperformance-v8
poly2tri/sweep/sweep_context.cc
C++
bsd
5,241
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #include <stdexcept> #include "sweep.h" #include "sweep_context.h" #include "advancing_front.h" #include "../common/utils.h" namespace p2t { // Triangulate simple polygon with holes void Sweep::Triangulate(SweepContext& tcx) { tcx.InitTriangulation(); tcx.CreateAdvancingFront(nodes_); // Sweep points; build mesh SweepPoints(tcx); // Clean up FinalizationPolygon(tcx); } void Sweep::SweepPoints(SweepContext& tcx) { for (int i = 1; i < tcx.point_count(); i++) { Point& point = *tcx.GetPoint(i); Node* node = &PointEvent(tcx, point); for (unsigned int i = 0; i < point.edge_list.size(); i++) { EdgeEvent(tcx, point.edge_list[i], node); } } } void Sweep::FinalizationPolygon(SweepContext& tcx) { // Get an Internal triangle to start with Triangle* t = tcx.front()->head()->next->triangle; Point* p = tcx.front()->head()->next->point; while (!t->GetConstrainedEdgeCW(*p)) { t = t->NeighborCCW(*p); } // Collect interior triangles constrained by edges tcx.MeshClean(*t); } Node& Sweep::PointEvent(SweepContext& tcx, Point& point) { Node& node = tcx.LocateNode(point); Node& new_node = NewFrontTriangle(tcx, point, node); // Only need to check +epsilon since point never have smaller // x value than node due to how we fetch nodes from the front if (point.x <= node.point->x + EPSILON) { Fill(tcx, node); } //tcx.AddNode(new_node); FillAdvancingFront(tcx, new_node); return new_node; } void Sweep::EdgeEvent(SweepContext& tcx, Edge* edge, Node* node) { tcx.edge_event.constrained_edge = edge; tcx.edge_event.right = (edge->p->x > edge->q->x); if (IsEdgeSideOfTriangle(*node->triangle, *edge->p, *edge->q)) { return; } // For now we will do all needed filling // TODO: integrate with flip process might give some better performance // but for now this avoid the issue with cases that needs both flips and fills FillEdgeEvent(tcx, edge, node); EdgeEvent(tcx, *edge->p, *edge->q, node->triangle, *edge->q); } void Sweep::EdgeEvent(SweepContext& tcx, Point& ep, Point& eq, Triangle* triangle, Point& point) { if (IsEdgeSideOfTriangle(*triangle, ep, eq)) { return; } Point* p1 = triangle->PointCCW(point); Orientation o1 = Orient2d(eq, *p1, ep); if (o1 == COLLINEAR) { if( triangle->Contains(&eq, p1)) { triangle->MarkConstrainedEdge(&eq, p1 ); // We are modifying the constraint maybe it would be better to // not change the given constraint and just keep a variable for the new constraint tcx.edge_event.constrained_edge->q = p1; triangle = &triangle->NeighborAcross(point); EdgeEvent( tcx, ep, *p1, triangle, *p1 ); } else { std::runtime_error("EdgeEvent - collinear points not supported"); assert(0); } return; } Point* p2 = triangle->PointCW(point); Orientation o2 = Orient2d(eq, *p2, ep); if (o2 == COLLINEAR) { if( triangle->Contains(&eq, p2)) { triangle->MarkConstrainedEdge(&eq, p2 ); // We are modifying the constraint maybe it would be better to // not change the given constraint and just keep a variable for the new constraint tcx.edge_event.constrained_edge->q = p2; triangle = &triangle->NeighborAcross(point); EdgeEvent( tcx, ep, *p2, triangle, *p2 ); } else { std::runtime_error("EdgeEvent - collinear points not supported"); assert(0); } return; } if (o1 == o2) { // Need to decide if we are rotating CW or CCW to get to a triangle // that will cross edge if (o1 == CW) { triangle = triangle->NeighborCCW(point); } else{ triangle = triangle->NeighborCW(point); } EdgeEvent(tcx, ep, eq, triangle, point); } else { // This triangle crosses constraint so lets flippin start! FlipEdgeEvent(tcx, ep, eq, triangle, point); } } bool Sweep::IsEdgeSideOfTriangle(Triangle& triangle, Point& ep, Point& eq) { int index = triangle.EdgeIndex(&ep, &eq); if (index != -1) { triangle.MarkConstrainedEdge(index); Triangle* t = triangle.GetNeighbor(index); if (t) { t->MarkConstrainedEdge(&ep, &eq); } return true; } return false; } Node& Sweep::NewFrontTriangle(SweepContext& tcx, Point& point, Node& node) { Triangle* triangle = new Triangle(point, *node.point, *node.next->point); triangle->MarkNeighbor(*node.triangle); tcx.AddToMap(triangle); Node* new_node = new Node(point); nodes_.push_back(new_node); new_node->next = node.next; new_node->prev = &node; node.next->prev = new_node; node.next = new_node; if (!Legalize(tcx, *triangle)) { tcx.MapTriangleToNodes(*triangle); } return *new_node; } void Sweep::Fill(SweepContext& tcx, Node& node) { Triangle* triangle = new Triangle(*node.prev->point, *node.point, *node.next->point); // TODO: should copy the constrained_edge value from neighbor triangles // for now constrained_edge values are copied during the legalize triangle->MarkNeighbor(*node.prev->triangle); triangle->MarkNeighbor(*node.triangle); tcx.AddToMap(triangle); // Update the advancing front node.prev->next = node.next; node.next->prev = node.prev; // If it was legalized the triangle has already been mapped if (!Legalize(tcx, *triangle)) { tcx.MapTriangleToNodes(*triangle); } } void Sweep::FillAdvancingFront(SweepContext& tcx, Node& n) { // Fill right holes Node* node = n.next; while (node->next) { double angle = HoleAngle(*node); if (angle > M_PI_2 || angle < -M_PI_2) break; Fill(tcx, *node); node = node->next; } // Fill left holes node = n.prev; while (node->prev) { double angle = HoleAngle(*node); if (angle > M_PI_2 || angle < -M_PI_2) break; Fill(tcx, *node); node = node->prev; } // Fill right basins if (n.next && n.next->next) { double angle = BasinAngle(n); if (angle < PI_3div4) { FillBasin(tcx, n); } } } double Sweep::BasinAngle(Node& node) { double ax = node.point->x - node.next->next->point->x; double ay = node.point->y - node.next->next->point->y; return atan2(ay, ax); } double Sweep::HoleAngle(Node& node) { /* Complex plane * ab = cosA +i*sinA * ab = (ax + ay*i)(bx + by*i) = (ax*bx + ay*by) + i(ax*by-ay*bx) * atan2(y,x) computes the principal value of the argument function * applied to the complex number x+iy * Where x = ax*bx + ay*by * y = ax*by - ay*bx */ double ax = node.next->point->x - node.point->x; double ay = node.next->point->y - node.point->y; double bx = node.prev->point->x - node.point->x; double by = node.prev->point->y - node.point->y; return atan2(ax * by - ay * bx, ax * bx + ay * by); } bool Sweep::Legalize(SweepContext& tcx, Triangle& t) { // To legalize a triangle we start by finding if any of the three edges // violate the Delaunay condition for (int i = 0; i < 3; i++) { if (t.delaunay_edge[i]) continue; Triangle* ot = t.GetNeighbor(i); if (ot) { Point* p = t.GetPoint(i); Point* op = ot->OppositePoint(t, *p); int oi = ot->Index(op); // If this is a Constrained Edge or a Delaunay Edge(only during recursive legalization) // then we should not try to legalize if (ot->constrained_edge[oi] || ot->delaunay_edge[oi]) { t.constrained_edge[i] = ot->constrained_edge[oi]; continue; } bool inside = Incircle(*p, *t.PointCCW(*p), *t.PointCW(*p), *op); if (inside) { // Lets mark this shared edge as Delaunay t.delaunay_edge[i] = true; ot->delaunay_edge[oi] = true; // Lets rotate shared edge one vertex CW to legalize it RotateTrianglePair(t, *p, *ot, *op); // We now got one valid Delaunay Edge shared by two triangles // This gives us 4 new edges to check for Delaunay // Make sure that triangle to node mapping is done only one time for a specific triangle bool not_legalized = !Legalize(tcx, t); if (not_legalized) { tcx.MapTriangleToNodes(t); } not_legalized = !Legalize(tcx, *ot); if (not_legalized) tcx.MapTriangleToNodes(*ot); // Reset the Delaunay edges, since they only are valid Delaunay edges // until we add a new triangle or point. // XXX: need to think about this. Can these edges be tried after we // return to previous recursive level? t.delaunay_edge[i] = false; ot->delaunay_edge[oi] = false; // If triangle have been legalized no need to check the other edges since // the recursive legalization will handles those so we can end here. return true; } } } return false; } bool Sweep::Incircle(Point& pa, Point& pb, Point& pc, Point& pd) { double adx = pa.x - pd.x; double ady = pa.y - pd.y; double bdx = pb.x - pd.x; double bdy = pb.y - pd.y; double adxbdy = adx * bdy; double bdxady = bdx * ady; double oabd = adxbdy - bdxady; if (oabd <= 0) return false; double cdx = pc.x - pd.x; double cdy = pc.y - pd.y; double cdxady = cdx * ady; double adxcdy = adx * cdy; double ocad = cdxady - adxcdy; if (ocad <= 0) return false; double bdxcdy = bdx * cdy; double cdxbdy = cdx * bdy; double alift = adx * adx + ady * ady; double blift = bdx * bdx + bdy * bdy; double clift = cdx * cdx + cdy * cdy; double det = alift * (bdxcdy - cdxbdy) + blift * ocad + clift * oabd; return det > 0; } void Sweep::RotateTrianglePair(Triangle& t, Point& p, Triangle& ot, Point& op) { Triangle* n1, *n2, *n3, *n4; n1 = t.NeighborCCW(p); n2 = t.NeighborCW(p); n3 = ot.NeighborCCW(op); n4 = ot.NeighborCW(op); bool ce1, ce2, ce3, ce4; ce1 = t.GetConstrainedEdgeCCW(p); ce2 = t.GetConstrainedEdgeCW(p); ce3 = ot.GetConstrainedEdgeCCW(op); ce4 = ot.GetConstrainedEdgeCW(op); bool de1, de2, de3, de4; de1 = t.GetDelunayEdgeCCW(p); de2 = t.GetDelunayEdgeCW(p); de3 = ot.GetDelunayEdgeCCW(op); de4 = ot.GetDelunayEdgeCW(op); t.Legalize(p, op); ot.Legalize(op, p); // Remap delaunay_edge ot.SetDelunayEdgeCCW(p, de1); t.SetDelunayEdgeCW(p, de2); t.SetDelunayEdgeCCW(op, de3); ot.SetDelunayEdgeCW(op, de4); // Remap constrained_edge ot.SetConstrainedEdgeCCW(p, ce1); t.SetConstrainedEdgeCW(p, ce2); t.SetConstrainedEdgeCCW(op, ce3); ot.SetConstrainedEdgeCW(op, ce4); // Remap neighbors // XXX: might optimize the markNeighbor by keeping track of // what side should be assigned to what neighbor after the // rotation. Now mark neighbor does lots of testing to find // the right side. t.ClearNeighbors(); ot.ClearNeighbors(); if (n1) ot.MarkNeighbor(*n1); if (n2) t.MarkNeighbor(*n2); if (n3) t.MarkNeighbor(*n3); if (n4) ot.MarkNeighbor(*n4); t.MarkNeighbor(ot); } void Sweep::FillBasin(SweepContext& tcx, Node& node) { if (Orient2d(*node.point, *node.next->point, *node.next->next->point) == CCW) { tcx.basin.left_node = node.next->next; } else { tcx.basin.left_node = node.next; } // Find the bottom and right node tcx.basin.bottom_node = tcx.basin.left_node; while (tcx.basin.bottom_node->next && tcx.basin.bottom_node->point->y >= tcx.basin.bottom_node->next->point->y) { tcx.basin.bottom_node = tcx.basin.bottom_node->next; } if (tcx.basin.bottom_node == tcx.basin.left_node) { // No valid basin return; } tcx.basin.right_node = tcx.basin.bottom_node; while (tcx.basin.right_node->next && tcx.basin.right_node->point->y < tcx.basin.right_node->next->point->y) { tcx.basin.right_node = tcx.basin.right_node->next; } if (tcx.basin.right_node == tcx.basin.bottom_node) { // No valid basins return; } tcx.basin.width = tcx.basin.right_node->point->x - tcx.basin.left_node->point->x; tcx.basin.left_highest = tcx.basin.left_node->point->y > tcx.basin.right_node->point->y; FillBasinReq(tcx, tcx.basin.bottom_node); } void Sweep::FillBasinReq(SweepContext& tcx, Node* node) { // if shallow stop filling if (IsShallow(tcx, *node)) { return; } Fill(tcx, *node); if (node->prev == tcx.basin.left_node && node->next == tcx.basin.right_node) { return; } else if (node->prev == tcx.basin.left_node) { Orientation o = Orient2d(*node->point, *node->next->point, *node->next->next->point); if (o == CW) { return; } node = node->next; } else if (node->next == tcx.basin.right_node) { Orientation o = Orient2d(*node->point, *node->prev->point, *node->prev->prev->point); if (o == CCW) { return; } node = node->prev; } else { // Continue with the neighbor node with lowest Y value if (node->prev->point->y < node->next->point->y) { node = node->prev; } else { node = node->next; } } FillBasinReq(tcx, node); } bool Sweep::IsShallow(SweepContext& tcx, Node& node) { double height; if (tcx.basin.left_highest) { height = tcx.basin.left_node->point->y - node.point->y; } else { height = tcx.basin.right_node->point->y - node.point->y; } // if shallow stop filling if (tcx.basin.width > height) { return true; } return false; } void Sweep::FillEdgeEvent(SweepContext& tcx, Edge* edge, Node* node) { if (tcx.edge_event.right) { FillRightAboveEdgeEvent(tcx, edge, node); } else { FillLeftAboveEdgeEvent(tcx, edge, node); } } void Sweep::FillRightAboveEdgeEvent(SweepContext& tcx, Edge* edge, Node* node) { while (node->next->point->x < edge->p->x) { // Check if next node is below the edge if (Orient2d(*edge->q, *node->next->point, *edge->p) == CCW) { FillRightBelowEdgeEvent(tcx, edge, *node); } else { node = node->next; } } } void Sweep::FillRightBelowEdgeEvent(SweepContext& tcx, Edge* edge, Node& node) { if (node.point->x < edge->p->x) { if (Orient2d(*node.point, *node.next->point, *node.next->next->point) == CCW) { // Concave FillRightConcaveEdgeEvent(tcx, edge, node); } else{ // Convex FillRightConvexEdgeEvent(tcx, edge, node); // Retry this one FillRightBelowEdgeEvent(tcx, edge, node); } } } void Sweep::FillRightConcaveEdgeEvent(SweepContext& tcx, Edge* edge, Node& node) { Fill(tcx, *node.next); if (node.next->point != edge->p) { // Next above or below edge? if (Orient2d(*edge->q, *node.next->point, *edge->p) == CCW) { // Below if (Orient2d(*node.point, *node.next->point, *node.next->next->point) == CCW) { // Next is concave FillRightConcaveEdgeEvent(tcx, edge, node); } else { // Next is convex } } } } void Sweep::FillRightConvexEdgeEvent(SweepContext& tcx, Edge* edge, Node& node) { // Next concave or convex? if (Orient2d(*node.next->point, *node.next->next->point, *node.next->next->next->point) == CCW) { // Concave FillRightConcaveEdgeEvent(tcx, edge, *node.next); } else{ // Convex // Next above or below edge? if (Orient2d(*edge->q, *node.next->next->point, *edge->p) == CCW) { // Below FillRightConvexEdgeEvent(tcx, edge, *node.next); } else{ // Above } } } void Sweep::FillLeftAboveEdgeEvent(SweepContext& tcx, Edge* edge, Node* node) { while (node->prev->point->x > edge->p->x) { // Check if next node is below the edge if (Orient2d(*edge->q, *node->prev->point, *edge->p) == CW) { FillLeftBelowEdgeEvent(tcx, edge, *node); } else { node = node->prev; } } } void Sweep::FillLeftBelowEdgeEvent(SweepContext& tcx, Edge* edge, Node& node) { if (node.point->x > edge->p->x) { if (Orient2d(*node.point, *node.prev->point, *node.prev->prev->point) == CW) { // Concave FillLeftConcaveEdgeEvent(tcx, edge, node); } else { // Convex FillLeftConvexEdgeEvent(tcx, edge, node); // Retry this one FillLeftBelowEdgeEvent(tcx, edge, node); } } } void Sweep::FillLeftConvexEdgeEvent(SweepContext& tcx, Edge* edge, Node& node) { // Next concave or convex? if (Orient2d(*node.prev->point, *node.prev->prev->point, *node.prev->prev->prev->point) == CW) { // Concave FillLeftConcaveEdgeEvent(tcx, edge, *node.prev); } else{ // Convex // Next above or below edge? if (Orient2d(*edge->q, *node.prev->prev->point, *edge->p) == CW) { // Below FillLeftConvexEdgeEvent(tcx, edge, *node.prev); } else{ // Above } } } void Sweep::FillLeftConcaveEdgeEvent(SweepContext& tcx, Edge* edge, Node& node) { Fill(tcx, *node.prev); if (node.prev->point != edge->p) { // Next above or below edge? if (Orient2d(*edge->q, *node.prev->point, *edge->p) == CW) { // Below if (Orient2d(*node.point, *node.prev->point, *node.prev->prev->point) == CW) { // Next is concave FillLeftConcaveEdgeEvent(tcx, edge, node); } else{ // Next is convex } } } } void Sweep::FlipEdgeEvent(SweepContext& tcx, Point& ep, Point& eq, Triangle* t, Point& p) { Triangle& ot = t->NeighborAcross(p); Point& op = *ot.OppositePoint(*t, p); if (&ot == NULL) { // If we want to integrate the fillEdgeEvent do it here // With current implementation we should never get here //throw new RuntimeException( "[BUG:FIXME] FLIP failed due to missing triangle"); assert(0); } if (InScanArea(p, *t->PointCCW(p), *t->PointCW(p), op)) { // Lets rotate shared edge one vertex CW RotateTrianglePair(*t, p, ot, op); tcx.MapTriangleToNodes(*t); tcx.MapTriangleToNodes(ot); if (p == eq && op == ep) { if (eq == *tcx.edge_event.constrained_edge->q && ep == *tcx.edge_event.constrained_edge->p) { t->MarkConstrainedEdge(&ep, &eq); ot.MarkConstrainedEdge(&ep, &eq); Legalize(tcx, *t); Legalize(tcx, ot); } else { // XXX: I think one of the triangles should be legalized here? } } else { Orientation o = Orient2d(eq, op, ep); t = &NextFlipTriangle(tcx, (int)o, *t, ot, p, op); FlipEdgeEvent(tcx, ep, eq, t, p); } } else { Point& newP = NextFlipPoint(ep, eq, ot, op); FlipScanEdgeEvent(tcx, ep, eq, *t, ot, newP); EdgeEvent(tcx, ep, eq, t, p); } } Triangle& Sweep::NextFlipTriangle(SweepContext& tcx, int o, Triangle& t, Triangle& ot, Point& p, Point& op) { if (o == CCW) { // ot is not crossing edge after flip int edge_index = ot.EdgeIndex(&p, &op); ot.delaunay_edge[edge_index] = true; Legalize(tcx, ot); ot.ClearDelunayEdges(); return t; } // t is not crossing edge after flip int edge_index = t.EdgeIndex(&p, &op); t.delaunay_edge[edge_index] = true; Legalize(tcx, t); t.ClearDelunayEdges(); return ot; } Point& Sweep::NextFlipPoint(Point& ep, Point& eq, Triangle& ot, Point& op) { Orientation o2d = Orient2d(eq, op, ep); if (o2d == CW) { // Right return *ot.PointCCW(op); } else if (o2d == CCW) { // Left return *ot.PointCW(op); } else{ //throw new RuntimeException("[Unsupported] Opposing point on constrained edge"); assert(0); } } void Sweep::FlipScanEdgeEvent(SweepContext& tcx, Point& ep, Point& eq, Triangle& flip_triangle, Triangle& t, Point& p) { Triangle& ot = t.NeighborAcross(p); Point& op = *ot.OppositePoint(t, p); if (&t.NeighborAcross(p) == NULL) { // If we want to integrate the fillEdgeEvent do it here // With current implementation we should never get here //throw new RuntimeException( "[BUG:FIXME] FLIP failed due to missing triangle"); assert(0); } if (InScanArea(eq, *flip_triangle.PointCCW(eq), *flip_triangle.PointCW(eq), op)) { // flip with new edge op->eq FlipEdgeEvent(tcx, eq, op, &ot, op); // TODO: Actually I just figured out that it should be possible to // improve this by getting the next ot and op before the the above // flip and continue the flipScanEdgeEvent here // set new ot and op here and loop back to inScanArea test // also need to set a new flip_triangle first // Turns out at first glance that this is somewhat complicated // so it will have to wait. } else{ Point& newP = NextFlipPoint(ep, eq, ot, op); FlipScanEdgeEvent(tcx, ep, eq, flip_triangle, ot, newP); } } Sweep::~Sweep() { // Clean up memory for(int i = 0; i < nodes_.size(); i++) { delete nodes_[i]; } } }
zzg0078426-betterperformance-v8
poly2tri/sweep/sweep.cc
C++
bsd
22,841
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #include "advancing_front.h" namespace p2t { AdvancingFront::AdvancingFront(Node& head, Node& tail) { head_ = &head; tail_ = &tail; search_node_ = &head; } Node* AdvancingFront::LocateNode(const double& x) { Node* node = search_node_; if (x < node->value) { while ((node = node->prev) != NULL) { if (x >= node->value) { search_node_ = node; return node; } } } else { while ((node = node->next) != NULL) { if (x < node->value) { search_node_ = node->prev; return node->prev; } } } return NULL; } Node* AdvancingFront::FindSearchNode(const double& x) { (void)x; // suppress compiler warnings "unused parameter 'x'" // TODO: implement BST index return search_node_; } Node* AdvancingFront::LocatePoint(const Point* point) { const double px = point->x; Node* node = FindSearchNode(px); const double nx = node->point->x; if (px == nx) { if (point != node->point) { // We might have two nodes with same x value for a short time if (point == node->prev->point) { node = node->prev; } else if (point == node->next->point) { node = node->next; } else { assert(0); } } } else if (px < nx) { while ((node = node->prev) != NULL) { if (point == node->point) { break; } } } else { while ((node = node->next) != NULL) { if (point == node->point) break; } } if(node) search_node_ = node; return node; } AdvancingFront::~AdvancingFront() { } }
zzg0078426-betterperformance-v8
poly2tri/sweep/advancing_front.cc
C++
bsd
3,182
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #ifndef CDT_H #define CDT_H #include "advancing_front.h" #include "sweep_context.h" #include "sweep.h" /** * * @author Mason Green <mason.green@gmail.com> * */ namespace p2t { class CDT { public: /** * Constructor - add polyline with non repeating points * * @param polyline */ CDT(std::vector<Point*> polyline); /** * Destructor - clean up memory */ ~CDT(); /** * Add a hole * * @param polyline */ void AddHole(std::vector<Point*> polyline); /** * Add a steiner point * * @param point */ void AddPoint(Point* point); /** * Triangulate - do this AFTER you've added the polyline, holes, and Steiner points */ void Triangulate(); /** * Get CDT triangles */ std::vector<Triangle*> GetTriangles(); /** * Get triangle map */ std::list<Triangle*> GetMap(); private: /** * Internals */ SweepContext* sweep_context_; Sweep* sweep_; }; } #endif
zzg0078426-betterperformance-v8
poly2tri/sweep/cdt.h
C++
bsd
2,709
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #ifndef SWEEP_CONTEXT_H #define SWEEP_CONTEXT_H #include <list> #include <vector> namespace p2t { // Inital triangle factor, seed triangle will extend 30% of // PointSet width to both left and right. const double kAlpha = 0.3; struct Point; class Triangle; struct Node; struct Edge; class AdvancingFront; class SweepContext { public: /// Constructor SweepContext(std::vector<Point*> polyline); /// Destructor ~SweepContext(); void set_head(Point* p1); Point* head(); void set_tail(Point* p1); Point* tail(); int point_count(); Node& LocateNode(Point& point); void RemoveNode(Node* node); void CreateAdvancingFront(std::vector<Node*> nodes); /// Try to map a node to all sides of this triangle that don't have a neighbor void MapTriangleToNodes(Triangle& t); void AddToMap(Triangle* triangle); Point* GetPoint(const int& index); Point* GetPoints(); void RemoveFromMap(Triangle* triangle); void AddHole(std::vector<Point*> polyline); void AddPoint(Point* point); AdvancingFront* front(); void MeshClean(Triangle& triangle); std::vector<Triangle*> GetTriangles(); std::list<Triangle*> GetMap(); std::vector<Edge*> edge_list; struct Basin { Node* left_node; Node* bottom_node; Node* right_node; double width; bool left_highest; Basin() : left_node(NULL), bottom_node(NULL), right_node(NULL), width(0.0), left_highest(false) { } void Clear() { left_node = NULL; bottom_node = NULL; right_node = NULL; width = 0.0; left_highest = false; } }; struct EdgeEvent { Edge* constrained_edge; bool right; EdgeEvent() : constrained_edge(NULL), right(false) { } }; Basin basin; EdgeEvent edge_event; private: friend class Sweep; std::vector<Triangle*> triangles_; std::list<Triangle*> map_; std::vector<Point*> points_; // Advancing front AdvancingFront* front_; // head point used with advancing front Point* head_; // tail point used with advancing front Point* tail_; Node *af_head_, *af_middle_, *af_tail_; void InitTriangulation(); void InitEdges(std::vector<Point*> polyline); }; inline AdvancingFront* SweepContext::front() { return front_; } inline int SweepContext::point_count() { return points_.size(); } inline void SweepContext::set_head(Point* p1) { head_ = p1; } inline Point* SweepContext::head() { return head_; } inline void SweepContext::set_tail(Point* p1) { tail_ = p1; } inline Point* SweepContext::tail() { return tail_; } } #endif
zzg0078426-betterperformance-v8
poly2tri/sweep/sweep_context.h
C++
bsd
4,255
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #include "cdt.h" namespace p2t { CDT::CDT(std::vector<Point*> polyline) { sweep_context_ = new SweepContext(polyline); sweep_ = new Sweep; } void CDT::AddHole(std::vector<Point*> polyline) { sweep_context_->AddHole(polyline); } void CDT::AddPoint(Point* point) { sweep_context_->AddPoint(point); } void CDT::Triangulate() { sweep_->Triangulate(*sweep_context_); } std::vector<p2t::Triangle*> CDT::GetTriangles() { return sweep_context_->GetTriangles(); } std::list<p2t::Triangle*> CDT::GetMap() { return sweep_context_->GetMap(); } CDT::~CDT() { delete sweep_context_; delete sweep_; } }
zzg0078426-betterperformance-v8
poly2tri/sweep/cdt.cc
C++
bsd
2,310
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ // Include guard #ifndef SHAPES_H #define SHAPES_H #include <vector> #include <cstddef> #include <assert.h> #include <cmath> namespace p2t { struct Edge; struct Point { double x, y; /// Default constructor does nothing (for performance). Point() { x = 0.0; y = 0.0; } /// The edges this point constitutes an upper ending point std::vector<Edge*> edge_list; /// Construct using coordinates. Point(double x, double y) : x(x), y(y) {} /// Set this point to all zeros. void set_zero() { x = 0.0; y = 0.0; } /// Set this point to some specified coordinates. void set(double x_, double y_) { x = x_; y = y_; } /// Negate this point. Point operator -() const { Point v; v.set(-x, -y); return v; } /// Add a point to this point. void operator +=(const Point& v) { x += v.x; y += v.y; } /// Subtract a point from this point. void operator -=(const Point& v) { x -= v.x; y -= v.y; } /// Multiply this point by a scalar. void operator *=(double a) { x *= a; y *= a; } /// Get the length of this point (the norm). double Length() const { return sqrt(x * x + y * y); } /// Convert this point into a unit point. Returns the Length. double Normalize() { double len = Length(); x /= len; y /= len; return len; } }; // Represents a simple polygon's edge struct Edge { Point* p, *q; /// Constructor Edge(Point& p1, Point& p2) : p(&p1), q(&p2) { if (p1.y > p2.y) { q = &p1; p = &p2; } else if (p1.y == p2.y) { if (p1.x > p2.x) { q = &p1; p = &p2; } else if (p1.x == p2.x) { // Repeat points assert(false); } } q->edge_list.push_back(this); } }; // Triangle-based data structures are know to have better performance than quad-edge structures // See: J. Shewchuk, "Triangle: Engineering a 2D Quality Mesh Generator and Delaunay Triangulator" // "Triangulations in CGAL" class Triangle { public: /// Constructor Triangle(Point& a, Point& b, Point& c); /// Flags to determine if an edge is a Constrained edge bool constrained_edge[3]; /// Flags to determine if an edge is a Delauney edge bool delaunay_edge[3]; Point* GetPoint(const int& index); Point* PointCW(Point& point); Point* PointCCW(Point& point); Point* OppositePoint(Triangle& t, Point& p); Triangle* GetNeighbor(const int& index); void MarkNeighbor(Point* p1, Point* p2, Triangle* t); void MarkNeighbor(Triangle& t); void MarkConstrainedEdge(const int index); void MarkConstrainedEdge(Edge& edge); void MarkConstrainedEdge(Point* p, Point* q); int Index(const Point* p); int EdgeIndex(const Point* p1, const Point* p2); Triangle* NeighborCW(Point& point); Triangle* NeighborCCW(Point& point); bool GetConstrainedEdgeCCW(Point& p); bool GetConstrainedEdgeCW(Point& p); void SetConstrainedEdgeCCW(Point& p, bool ce); void SetConstrainedEdgeCW(Point& p, bool ce); bool GetDelunayEdgeCCW(Point& p); bool GetDelunayEdgeCW(Point& p); void SetDelunayEdgeCCW(Point& p, bool e); void SetDelunayEdgeCW(Point& p, bool e); bool Contains(Point* p); bool Contains(const Edge& e); bool Contains(Point* p, Point* q); void Legalize(Point& point); void Legalize(Point& opoint, Point& npoint); /** * Clears all references to all other triangles and points */ void Clear(); void ClearNeighbor(Triangle *triangle ); void ClearNeighbors(); void ClearDelunayEdges(); inline bool IsInterior(); inline void IsInterior(bool b); Triangle& NeighborAcross(Point& opoint); void DebugPrint(); private: /// Triangle points Point* points_[3]; /// Neighbor list Triangle* neighbors_[3]; /// Has this triangle been marked as an interior triangle? bool interior_; }; inline bool cmp(const Point* a, const Point* b) { if (a->y < b->y) { return true; } else if (a->y == b->y) { // Make sure q is point with greater x value if (a->x < b->x) { return true; } } return false; } /// Add two points_ component-wise. inline Point operator +(const Point& a, const Point& b) { return Point(a.x + b.x, a.y + b.y); } /// Subtract two points_ component-wise. inline Point operator -(const Point& a, const Point& b) { return Point(a.x - b.x, a.y - b.y); } /// Multiply point by scalar inline Point operator *(double s, const Point& a) { return Point(s * a.x, s * a.y); } inline bool operator ==(const Point& a, const Point& b) { return a.x == b.x && a.y == b.y; } inline bool operator !=(const Point& a, const Point& b) { return a.x != b.x && a.y != b.y; } /// Peform the dot product on two vectors. inline double Dot(const Point& a, const Point& b) { return a.x * b.x + a.y * b.y; } /// Perform the cross product on two vectors. In 2D this produces a scalar. inline double Cross(const Point& a, const Point& b) { return a.x * b.y - a.y * b.x; } /// Perform the cross product on a point and a scalar. In 2D this produces /// a point. inline Point Cross(const Point& a, double s) { return Point(s * a.y, -s * a.x); } /// Perform the cross product on a scalar and a point. In 2D this produces /// a point. inline Point Cross(const double s, const Point& a) { return Point(-s * a.y, s * a.x); } inline Point* Triangle::GetPoint(const int& index) { return points_[index]; } inline Triangle* Triangle::GetNeighbor(const int& index) { return neighbors_[index]; } inline bool Triangle::Contains(Point* p) { return p == points_[0] || p == points_[1] || p == points_[2]; } inline bool Triangle::Contains(const Edge& e) { return Contains(e.p) && Contains(e.q); } inline bool Triangle::Contains(Point* p, Point* q) { return Contains(p) && Contains(q); } inline bool Triangle::IsInterior() { return interior_; } inline void Triangle::IsInterior(bool b) { interior_ = b; } } #endif
zzg0078426-betterperformance-v8
poly2tri/common/shapes.h
C++
bsd
7,456
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #include "shapes.h" #include <iostream> namespace p2t { Triangle::Triangle(Point& a, Point& b, Point& c) { points_[0] = &a; points_[1] = &b; points_[2] = &c; neighbors_[0] = NULL; neighbors_[1] = NULL; neighbors_[2] = NULL; constrained_edge[0] = constrained_edge[1] = constrained_edge[2] = false; delaunay_edge[0] = delaunay_edge[1] = delaunay_edge[2] = false; interior_ = false; } // Update neighbor pointers void Triangle::MarkNeighbor(Point* p1, Point* p2, Triangle* t) { if ((p1 == points_[2] && p2 == points_[1]) || (p1 == points_[1] && p2 == points_[2])) neighbors_[0] = t; else if ((p1 == points_[0] && p2 == points_[2]) || (p1 == points_[2] && p2 == points_[0])) neighbors_[1] = t; else if ((p1 == points_[0] && p2 == points_[1]) || (p1 == points_[1] && p2 == points_[0])) neighbors_[2] = t; else assert(0); } // Exhaustive search to update neighbor pointers void Triangle::MarkNeighbor(Triangle& t) { if (t.Contains(points_[1], points_[2])) { neighbors_[0] = &t; t.MarkNeighbor(points_[1], points_[2], this); } else if (t.Contains(points_[0], points_[2])) { neighbors_[1] = &t; t.MarkNeighbor(points_[0], points_[2], this); } else if (t.Contains(points_[0], points_[1])) { neighbors_[2] = &t; t.MarkNeighbor(points_[0], points_[1], this); } } /** * Clears all references to all other triangles and points */ void Triangle::Clear() { Triangle *t; for( int i=0; i<3; i++ ) { t = neighbors_[i]; if( t != NULL ) { t->ClearNeighbor( this ); } } ClearNeighbors(); points_[0]=points_[1]=points_[2] = NULL; } void Triangle::ClearNeighbor(Triangle *triangle ) { if( neighbors_[0] == triangle ) { neighbors_[0] = NULL; } else if( neighbors_[1] == triangle ) { neighbors_[1] = NULL; } else { neighbors_[2] = NULL; } } void Triangle::ClearNeighbors() { neighbors_[0] = NULL; neighbors_[1] = NULL; neighbors_[2] = NULL; } void Triangle::ClearDelunayEdges() { delaunay_edge[0] = delaunay_edge[1] = delaunay_edge[2] = false; } Point* Triangle::OppositePoint(Triangle& t, Point& p) { Point *cw = t.PointCW(p); double x = cw->x; double y = cw->y; x = p.x; y = p.y; return PointCW(*cw); } // Legalized triangle by rotating clockwise around point(0) void Triangle::Legalize(Point& point) { points_[1] = points_[0]; points_[0] = points_[2]; points_[2] = &point; } // Legalize triagnle by rotating clockwise around oPoint void Triangle::Legalize(Point& opoint, Point& npoint) { if (&opoint == points_[0]) { points_[1] = points_[0]; points_[0] = points_[2]; points_[2] = &npoint; } else if (&opoint == points_[1]) { points_[2] = points_[1]; points_[1] = points_[0]; points_[0] = &npoint; } else if (&opoint == points_[2]) { points_[0] = points_[2]; points_[2] = points_[1]; points_[1] = &npoint; } else { assert(0); } } int Triangle::Index(const Point* p) { if (p == points_[0]) { return 0; } else if (p == points_[1]) { return 1; } else if (p == points_[2]) { return 2; } assert(0); } int Triangle::EdgeIndex(const Point* p1, const Point* p2) { if (points_[0] == p1) { if (points_[1] == p2) { return 2; } else if (points_[2] == p2) { return 1; } } else if (points_[1] == p1) { if (points_[2] == p2) { return 0; } else if (points_[0] == p2) { return 2; } } else if (points_[2] == p1) { if (points_[0] == p2) { return 1; } else if (points_[1] == p2) { return 0; } } return -1; } void Triangle::MarkConstrainedEdge(const int index) { constrained_edge[index] = true; } void Triangle::MarkConstrainedEdge(Edge& edge) { MarkConstrainedEdge(edge.p, edge.q); } // Mark edge as constrained void Triangle::MarkConstrainedEdge(Point* p, Point* q) { if ((q == points_[0] && p == points_[1]) || (q == points_[1] && p == points_[0])) { constrained_edge[2] = true; } else if ((q == points_[0] && p == points_[2]) || (q == points_[2] && p == points_[0])) { constrained_edge[1] = true; } else if ((q == points_[1] && p == points_[2]) || (q == points_[2] && p == points_[1])) { constrained_edge[0] = true; } } // The point counter-clockwise to given point Point* Triangle::PointCW(Point& point) { if (&point == points_[0]) { return points_[2]; } else if (&point == points_[1]) { return points_[0]; } else if (&point == points_[2]) { return points_[1]; } assert(0); } // The point counter-clockwise to given point Point* Triangle::PointCCW(Point& point) { if (&point == points_[0]) { return points_[1]; } else if (&point == points_[1]) { return points_[2]; } else if (&point == points_[2]) { return points_[0]; } assert(0); } // The neighbor clockwise to given point Triangle* Triangle::NeighborCW(Point& point) { if (&point == points_[0]) { return neighbors_[1]; } else if (&point == points_[1]) { return neighbors_[2]; } return neighbors_[0]; } // The neighbor counter-clockwise to given point Triangle* Triangle::NeighborCCW(Point& point) { if (&point == points_[0]) { return neighbors_[2]; } else if (&point == points_[1]) { return neighbors_[0]; } return neighbors_[1]; } bool Triangle::GetConstrainedEdgeCCW(Point& p) { if (&p == points_[0]) { return constrained_edge[2]; } else if (&p == points_[1]) { return constrained_edge[0]; } return constrained_edge[1]; } bool Triangle::GetConstrainedEdgeCW(Point& p) { if (&p == points_[0]) { return constrained_edge[1]; } else if (&p == points_[1]) { return constrained_edge[2]; } return constrained_edge[0]; } void Triangle::SetConstrainedEdgeCCW(Point& p, bool ce) { if (&p == points_[0]) { constrained_edge[2] = ce; } else if (&p == points_[1]) { constrained_edge[0] = ce; } else { constrained_edge[1] = ce; } } void Triangle::SetConstrainedEdgeCW(Point& p, bool ce) { if (&p == points_[0]) { constrained_edge[1] = ce; } else if (&p == points_[1]) { constrained_edge[2] = ce; } else { constrained_edge[0] = ce; } } bool Triangle::GetDelunayEdgeCCW(Point& p) { if (&p == points_[0]) { return delaunay_edge[2]; } else if (&p == points_[1]) { return delaunay_edge[0]; } return delaunay_edge[1]; } bool Triangle::GetDelunayEdgeCW(Point& p) { if (&p == points_[0]) { return delaunay_edge[1]; } else if (&p == points_[1]) { return delaunay_edge[2]; } return delaunay_edge[0]; } void Triangle::SetDelunayEdgeCCW(Point& p, bool e) { if (&p == points_[0]) { delaunay_edge[2] = e; } else if (&p == points_[1]) { delaunay_edge[0] = e; } else { delaunay_edge[1] = e; } } void Triangle::SetDelunayEdgeCW(Point& p, bool e) { if (&p == points_[0]) { delaunay_edge[1] = e; } else if (&p == points_[1]) { delaunay_edge[2] = e; } else { delaunay_edge[0] = e; } } // The neighbor across to given point Triangle& Triangle::NeighborAcross(Point& opoint) { if (&opoint == points_[0]) { return *neighbors_[0]; } else if (&opoint == points_[1]) { return *neighbors_[1]; } return *neighbors_[2]; } void Triangle::DebugPrint() { using namespace std; cout << points_[0]->x << "," << points_[0]->y << " "; cout << points_[1]->x << "," << points_[1]->y << " "; cout << points_[2]->x << "," << points_[2]->y << endl; } }
zzg0078426-betterperformance-v8
poly2tri/common/shapes.cc
C++
bsd
9,126
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #ifndef UTILS_H #define UTILS_H // Otherwise #defines like M_PI are undeclared under Visual Studio #define _USE_MATH_DEFINES #include <exception> #include <math.h> namespace p2t { const double PI_3div4 = 3 * M_PI / 4; const double EPSILON = 1e-12; enum Orientation { CW, CCW, COLLINEAR }; /** * Forumla to calculate signed area<br> * Positive if CCW<br> * Negative if CW<br> * 0 if collinear<br> * <pre> * A[P1,P2,P3] = (x1*y2 - y1*x2) + (x2*y3 - y2*x3) + (x3*y1 - y3*x1) * = (x1-x3)*(y2-y3) - (y1-y3)*(x2-x3) * </pre> */ Orientation Orient2d(Point& pa, Point& pb, Point& pc) { double detleft = (pa.x - pc.x) * (pb.y - pc.y); double detright = (pa.y - pc.y) * (pb.x - pc.x); double val = detleft - detright; if (val > -EPSILON && val < EPSILON) { return COLLINEAR; } else if (val > 0) { return CCW; } return CW; } bool InScanArea(Point& pa, Point& pb, Point& pc, Point& pd) { double pdx = pd.x; double pdy = pd.y; double adx = pa.x - pdx; double ady = pa.y - pdy; double bdx = pb.x - pdx; double bdy = pb.y - pdy; double adxbdy = adx * bdy; double bdxady = bdx * ady; double oabd = adxbdy - bdxady; if (oabd <= EPSILON) { return false; } double cdx = pc.x - pdx; double cdy = pc.y - pdy; double cdxady = cdx * ady; double adxcdy = adx * cdy; double ocad = cdxady - adxcdy; if (ocad <= EPSILON) { return false; } return true; } } #endif
zzg0078426-betterperformance-v8
poly2tri/common/utils.h
C++
bsd
3,174
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ #include <cstdlib> #include <GL/glfw.h> #include <time.h> #include <fstream> #include <string> #include <sstream> #include <algorithm> #include <iterator> #include <iostream> using namespace std; #include "../poly2tri/poly2tri.h" using namespace p2t; void Init(); void ShutDown(int return_code); void MainLoop(const double zoom); void Draw(const double zoom); void DrawMap(const double zoom); void ConstrainedColor(bool constrain); double StringToDouble(const std::string& s); double Random(double (*fun)(double), double xmin, double xmax); double Fun(double x); /// Dude hole examples vector<Point*> CreateHeadHole(); vector<Point*> CreateChestHole(); float rotate_y = 0, rotate_z = 0; const float rotations_per_tick = .2; /// Screen center x double cx = 0.0; /// Screen center y double cy = 0.0; /// Constrained triangles vector<Triangle*> triangles; /// Triangle map list<Triangle*> map; /// Polylines vector< vector<Point*> > polylines; /// Draw the entire triangle map? bool draw_map = false; /// Create a random distribution of points? bool random_distribution = false; int main(int argc, char* argv[]) { int num_points = 0; double max, min; double zoom; if (argc != 5) { cout << "-== USAGE ==-" << endl; cout << "Load Data File: p2t filename center_x center_y zoom" << endl; cout << " Random Points: p2t random num_points width zoom" << endl; return 1; } if(string(argv[1]) == "random") { num_points = atoi(argv[2]); random_distribution = true; char* pEnd; max = strtod(argv[3], &pEnd); min = -max; cx = cy = 0; zoom = atof(argv[4]); } else { zoom = atof(argv[4]); cx = atof(argv[2]); cy = atof(argv[3]); } vector<p2t::Point*> polyline; if(random_distribution) { // Create a simple bounding box polyline.push_back(new Point(min,min)); polyline.push_back(new Point(min,max)); polyline.push_back(new Point(max,max)); polyline.push_back(new Point(max,min)); } else { // Load pointset from file // Parse and tokenize data file string line; ifstream myfile(argv[1]); if (myfile.is_open()) { while (!myfile.eof()) { getline(myfile, line); if (line.size() == 0) { break; } istringstream iss(line); vector<string> tokens; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(tokens)); double x = StringToDouble(tokens[0]); double y = StringToDouble(tokens[1]); polyline.push_back(new Point(x, y)); num_points++; } myfile.close(); } else { cout << "File not opened" << endl; } } cout << "Number of constrained edges = " << polyline.size() << endl; polylines.push_back(polyline); Init(); /* * Perform triangulation! */ double init_time = glfwGetTime(); /* * STEP 1: Create CDT and add primary polyline * NOTE: polyline must be a simple polygon. The polyline's points * constitute constrained edges. No repeat points!!! */ CDT* cdt = new CDT(polyline); /* * STEP 2: Add holes or Steiner points if necessary */ string s(argv[1]); if(s.find("dude.dat", 0) != string::npos) { // Add head hole vector<Point*> head_hole = CreateHeadHole(); num_points += head_hole.size(); cdt->AddHole(head_hole); // Add chest hole vector<Point*> chest_hole = CreateChestHole(); num_points += chest_hole.size(); cdt->AddHole(chest_hole); polylines.push_back(head_hole); polylines.push_back(chest_hole); } else if (random_distribution) { max-=(1e-4); min+=(1e-4); for(int i = 0; i < num_points; i++) { double x = Random(Fun, min, max); double y = Random(Fun, min, max); cdt->AddPoint(new Point(x, y)); } } /* * STEP 3: Triangulate! */ cdt->Triangulate(); double dt = glfwGetTime() - init_time; triangles = cdt->GetTriangles(); map = cdt->GetMap(); cout << "Number of points = " << num_points << endl; cout << "Number of triangles = " << triangles.size() << endl; cout << "Elapsed time (ms) = " << dt*1000.0 << endl; MainLoop(zoom); delete cdt; ShutDown(0); return 0; } void Init() { const int window_width = 800, window_height = 600; if (glfwInit() != GL_TRUE) ShutDown(1); // 800 x 600, 16 bit color, no depth, alpha or stencil buffers, windowed if (glfwOpenWindow(window_width, window_height, 5, 6, 5, 0, 0, 0, GLFW_WINDOW) != GL_TRUE) ShutDown(1); glfwSetWindowTitle("Poly2Tri - C++"); glfwSwapInterval(1); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.0, 0.0, 0.0, 0.0); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); } void ShutDown(int return_code) { glfwTerminate(); exit(return_code); } void MainLoop(const double zoom) { // the time of the previous frame double old_time = glfwGetTime(); // this just loops as long as the program runs bool running = true; while (running) { // calculate time elapsed, and the amount by which stuff rotates double current_time = glfwGetTime(), delta_rotate = (current_time - old_time) * rotations_per_tick * 360; old_time = current_time; // escape to quit, arrow keys to rotate view // Check if ESC key was pressed or window was closed running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED); if (glfwGetKey(GLFW_KEY_LEFT) == GLFW_PRESS) rotate_y += delta_rotate; if (glfwGetKey(GLFW_KEY_RIGHT) == GLFW_PRESS) rotate_y -= delta_rotate; // z axis always rotates rotate_z += delta_rotate; // Draw the scene if (draw_map) { DrawMap(zoom); } else { Draw(zoom); } // swap back and front buffers glfwSwapBuffers(); } } void ResetZoom(double zoom, double cx, double cy, double width, double height) { double left = -width / zoom; double right = width / zoom; double bottom = -height / zoom; double top = height / zoom; // Reset viewport glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Reset ortho view glOrtho(left, right, bottom, top, 1, -1); glTranslatef(-cx, -cy, 0); glMatrixMode(GL_MODELVIEW); glDisable(GL_DEPTH_TEST); glLoadIdentity(); // Clear the screen glClear(GL_COLOR_BUFFER_BIT); } void Draw(const double zoom) { // reset zoom Point center = Point(cx, cy); ResetZoom(zoom, center.x, center.y, 800, 600); for (int i = 0; i < triangles.size(); i++) { Triangle& t = *triangles[i]; Point& a = *t.GetPoint(0); Point& b = *t.GetPoint(1); Point& c = *t.GetPoint(2); // Red glColor3f(1, 0, 0); glBegin(GL_LINE_LOOP); glVertex2f(a.x, a.y); glVertex2f(b.x, b.y); glVertex2f(c.x, c.y); glEnd(); } // green glColor3f(0, 1, 0); for(int i = 0; i < polylines.size(); i++) { vector<Point*> poly = polylines[i]; glBegin(GL_LINE_LOOP); for(int j = 0; j < poly.size(); j++) { glVertex2f(poly[j]->x, poly[j]->y); } glEnd(); } } void DrawMap(const double zoom) { // reset zoom Point center = Point(cx, cy); ResetZoom(zoom, center.x, center.y, 800, 600); list<Triangle*>::iterator it; for (it = map.begin(); it != map.end(); it++) { Triangle& t = **it; Point& a = *t.GetPoint(0); Point& b = *t.GetPoint(1); Point& c = *t.GetPoint(2); ConstrainedColor(t.constrained_edge[2]); glBegin(GL_LINES); glVertex2f(a.x, a.y); glVertex2f(b.x, b.y); glEnd( ); ConstrainedColor(t.constrained_edge[0]); glBegin(GL_LINES); glVertex2f(b.x, b.y); glVertex2f(c.x, c.y); glEnd( ); ConstrainedColor(t.constrained_edge[1]); glBegin(GL_LINES); glVertex2f(c.x, c.y); glVertex2f(a.x, a.y); glEnd( ); } } void ConstrainedColor(bool constrain) { if (constrain) { // Green glColor3f(0, 1, 0); } else { // Red glColor3f(1, 0, 0); } } vector<Point*> CreateHeadHole() { vector<Point*> head_hole; head_hole.push_back(new Point(325, 437)); head_hole.push_back(new Point(320, 423)); head_hole.push_back(new Point(329, 413)); head_hole.push_back(new Point(332, 423)); return head_hole; } vector<Point*> CreateChestHole() { vector<Point*> chest_hole; chest_hole.push_back(new Point(320.72342,480)); chest_hole.push_back(new Point(338.90617,465.96863)); chest_hole.push_back(new Point(347.99754,480.61584)); chest_hole.push_back(new Point(329.8148,510.41534)); chest_hole.push_back(new Point(339.91632,480.11077)); chest_hole.push_back(new Point(334.86556,478.09046)); return chest_hole; } double StringToDouble(const std::string& s) { std::istringstream i(s); double x; if (!(i >> x)) return 0; return x; } double Fun(double x) { return 2.5 + sin(10 * x) / x; } double Random(double (*fun)(double), double xmin = 0, double xmax = 1) { static double (*Fun)(double) = NULL, YMin, YMax; static bool First = true; // Initialises random generator for first call if (First) { First = false; srand((unsigned) time(NULL)); } // Evaluates maximum of function if (fun != Fun) { Fun = fun; YMin = 0, YMax = Fun(xmin); for (int iX = 1; iX < RAND_MAX; iX++) { double X = xmin + (xmax - xmin) * iX / RAND_MAX; double Y = Fun(X); YMax = Y > YMax ? Y : YMax; } } // Gets random values for X & Y double X = xmin + (xmax - xmin) * rand() / RAND_MAX; double Y = YMin + (YMax - YMin) * rand() / RAND_MAX; // Returns if valid and try again if not valid return Y < fun(X) ? X : Random(Fun, xmin, xmax); }
zzg0078426-betterperformance-v8
testbed/main.cc
C++
bsd
11,710
#! /usr/bin/env python # encoding: utf-8 # waf 1.6.2 VERSION='0.3.3' import sys APPNAME='p2t' top = '.' out = 'build' CPP_SOURCES = ['poly2tri/common/shapes.cc', 'poly2tri/sweep/cdt.cc', 'poly2tri/sweep/advancing_front.cc', 'poly2tri/sweep/sweep_context.cc', 'poly2tri/sweep/sweep.cc', 'testbed/main.cc'] from waflib.Tools.compiler_cxx import cxx_compiler cxx_compiler['win32'] = ['g++'] #Platform specific libs if sys.platform == 'win32': # MS Windows sys_libs = ['glfw', 'opengl32'] elif sys.platform == 'darwin': # Apple OSX sys_libs = ['glfw', 'OpenGL'] else: # GNU/Linux, BSD, etc sys_libs = ['glfw', 'GL'] def options(opt): print(' set_options') opt.load('compiler_cxx') def configure(conf): print(' calling the configuration') conf.load('compiler_cxx') conf.env.CXXFLAGS = ['-O3', '-ffast-math'] conf.env.DEFINES_P2T = ['P2T'] conf.env.LIB_P2T = sys_libs def build(bld): print(' building') bld.program(features = 'cxx cxxprogram', source=CPP_SOURCES, target = 'p2t', uselib = 'P2T')
zzg0078426-betterperformance-v8
wscript
Python
bsd
1,162
package com.zyeeda.framework.tomcat; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.valves.ValveBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UrlSessionTrackingValve extends ValveBase { private final static Logger logger = LoggerFactory.getLogger(UrlSessionTrackingValve.class); private final static String JSESSIONID_PATTERN = "^(.*?)(?:\\;jsessionid=([^\\?#]*))?(\\?[^#]*)?(#.*)?$"; @Override public void invoke(Request request, Response response) throws IOException, ServletException { Pattern pattern = Pattern.compile(JSESSIONID_PATTERN, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(request.getRequestURI()); if (matcher.matches()) { String jsessionid = matcher.group(2); if (jsessionid != null && !"".equals(jsessionid)) { logger.debug("Find jsessionid {} from url {}, set request session id.", jsessionid, request.getRequestURI()); request.setRequestedSessionId(jsessionid); request.setRequestedSessionURL(true); } } this.getNext().invoke(request, response); } }
zyeeda-framework
tomcat/src/main/java/com/zyeeda/framework/tomcat/UrlSessionTrackingValve.java
Java
asf20
1,316
package com.zyeeda.framework.unittest.services; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; public class ServletContextMock implements ServletContext { private Map<String, Object> attributes = new HashMap<String, Object>(); @Override public Object getAttribute(String name) { return this.attributes.get(name); } @Override public Enumeration<?> getAttributeNames() { return null; } @Override public ServletContext getContext(String arg0) { return null; } @Override public String getContextPath() { return null; } @Override public String getInitParameter(String arg0) { return null; } @Override public Enumeration<?> getInitParameterNames() { return new Enumeration<Object>() { @Override public boolean hasMoreElements() { return false; } @Override public Object nextElement() { return null; } }; } @Override public int getMajorVersion() { return 0; } @Override public String getMimeType(String arg0) { return null; } @Override public int getMinorVersion() { return 0; } @Override public RequestDispatcher getNamedDispatcher(String arg0) { return null; } @Override public String getRealPath(String path) { return System.getProperty("framework.application.root"); } @Override public RequestDispatcher getRequestDispatcher(String arg0) { return null; } @Override public URL getResource(String arg0) throws MalformedURLException { return null; } @Override public InputStream getResourceAsStream(String arg0) { return null; } @Override public Set<?> getResourcePaths(String arg0) { return null; } @Override public String getServerInfo() { return null; } @Override public Servlet getServlet(String arg0) throws ServletException { return null; } @Override public String getServletContextName() { return null; } @Override public Enumeration<?> getServletNames() { return null; } @Override public Enumeration<?> getServlets() { return null; } @Override public void log(String arg0) { } @Override public void log(Exception arg0, String arg1) { } @Override public void log(String arg0, Throwable arg1) { } @Override public void removeAttribute(String name) { this.attributes.remove(name); } @Override public void setAttribute(String name, Object value) { this.attributes.put(name, value); } }
zyeeda-framework
core/src/test/java/com/zyeeda/framework/unittest/services/ServletContextMock.java
Java
asf20
2,810
package com.zyeeda.framework.nosql; import com.mongodb.DB; import com.mongodb.Mongo; import com.zyeeda.framework.service.Service; public interface MongoDbService extends Service { public Mongo getMongo(); public DB getDefaultDatabase(); public DB getDatabase(String name); }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/nosql/MongoDbService.java
Java
asf20
302
package com.zyeeda.framework.nosql.internal; import org.apache.commons.configuration.Configuration; import org.apache.tapestry5.ioc.annotations.Marker; import org.apache.tapestry5.ioc.annotations.Primary; import org.apache.tapestry5.ioc.annotations.ServiceId; import org.apache.tapestry5.ioc.services.RegistryShutdownHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.DB; import com.mongodb.DBAddress; import com.mongodb.Mongo; import com.zyeeda.framework.config.ConfigurationService; import com.zyeeda.framework.nosql.MongoDbService; import com.zyeeda.framework.service.AbstractService; @Marker(Primary.class) @ServiceId("default-mongodb-service") public class DefaultMongoDbServiceProvider extends AbstractService implements MongoDbService { private final static Logger logger = LoggerFactory.getLogger(DefaultMongoDbServiceProvider.class); private final static String HOST_KEY = "host"; private final static String PORT_KEY = "port"; private final static String SYSTEM_USERNAME_KEY = "systemUsername"; private final static String SYSTEM_PASSWORD_KEY = "systemPassword"; private final static String DEFAULT_DATABASE_NAME_KEY = "defaultDatabaseName"; private final static String DEFAULT_DEFAULT_DATABASE_NAME = "zyeeda-framework"; private ConfigurationService configSvc; private String host; private int port; private String systemUsername; private String defaultDatabaseName; private Configuration config; private Mongo mongo; public DefaultMongoDbServiceProvider(RegistryShutdownHub shutdownHub, @Primary ConfigurationService configSvc) { super(shutdownHub); this.configSvc = configSvc; Configuration config = this.getConfiguration(this.configSvc); this.init(config); } private void init(Configuration config) { this.config = config; this.host = config.getString(HOST_KEY, DBAddress.defaultHost()); this.port = config.getInt(PORT_KEY, DBAddress.defaultPort()); this.systemUsername = config.getString(SYSTEM_USERNAME_KEY); this.defaultDatabaseName = config.getString(DEFAULT_DATABASE_NAME_KEY, DEFAULT_DEFAULT_DATABASE_NAME); if (logger.isDebugEnabled()) { logger.debug("{} = {}", HOST_KEY, this.host); logger.debug("{} = {}", PORT_KEY, this.port); logger.debug("{} = {}", SYSTEM_USERNAME_KEY, this.systemUsername); logger.debug("{} = {}", SYSTEM_PASSWORD_KEY, "******"); logger.debug("{} = {}", DEFAULT_DATABASE_NAME_KEY, this.defaultDatabaseName); } } @Override public void start() throws Exception { this.mongo = new Mongo(this.host, this.port); DB adminDb = this.mongo.getDB("admin"); String systemPassword = this.config.getString(SYSTEM_PASSWORD_KEY); if (this.systemUsername != null && systemPassword != null) { adminDb.authenticate(this.systemUsername, systemPassword.toCharArray()); } } @Override public void stop() { this.mongo.close(); } @Override public Mongo getMongo() { return this.mongo; } @Override public DB getDefaultDatabase() { return this.getDatabase(this.defaultDatabaseName); } @Override public DB getDatabase(String name) { return this.mongo.getDB(name); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/nosql/internal/DefaultMongoDbServiceProvider.java
Java
asf20
3,249
package com.zyeeda.framework.ioc; import org.apache.tapestry5.ioc.ServiceBinder; import org.apache.tapestry5.ioc.annotations.Primary; import org.apache.tapestry5.ioc.annotations.Startup; import com.zyeeda.framework.account.AccountService; import com.zyeeda.framework.account.internal.SystemAccountServiceProvider; import com.zyeeda.framework.config.ConfigurationService; import com.zyeeda.framework.config.internal.DefaultConfigurationServiceProvider; import com.zyeeda.framework.knowledge.KnowledgeService; import com.zyeeda.framework.knowledge.internal.DroolsKnowledgeServiceProvider; import com.zyeeda.framework.ldap.LdapService; import com.zyeeda.framework.ldap.internal.SunLdapServiceProvider; import com.zyeeda.framework.openid.consumer.OpenIdConsumerService; import com.zyeeda.framework.openid.consumer.internal.DefaultOpenIdConsumerServiceProvider; import com.zyeeda.framework.persistence.PersistenceService; import com.zyeeda.framework.persistence.annotations.DroolsTask; import com.zyeeda.framework.persistence.internal.DefaultPersistenceServiceProvider; import com.zyeeda.framework.persistence.internal.DroolsTaskPersistenceServiceProvider; import com.zyeeda.framework.security.SecurityService; import com.zyeeda.framework.security.internal.OpenIdProviderSecurityServiceProvider; import com.zyeeda.framework.sync.UserSyncService; import com.zyeeda.framework.sync.internal.HttpClientUserSyncServiceProvider; import com.zyeeda.framework.template.TemplateService; import com.zyeeda.framework.template.internal.FreemarkerTemplateServiceProvider; import com.zyeeda.framework.transaction.TransactionService; import com.zyeeda.framework.transaction.internal.DefaultTransactionServiceProvider; import com.zyeeda.framework.validation.ValidationService; import com.zyeeda.framework.validation.internal.HibernateValidationServiceProvider; public class FrameworkModule { //private final static Logger logger = LoggerFactory.getLogger(FrameworkModule.class); public static void bind(ServiceBinder binder) { binder.bind(ConfigurationService.class, DefaultConfigurationServiceProvider.class); binder.bind(TemplateService.class, FreemarkerTemplateServiceProvider.class); binder.bind(PersistenceService.class, DefaultPersistenceServiceProvider.class); binder.bind(PersistenceService.class, DroolsTaskPersistenceServiceProvider.class); binder.bind(ValidationService.class, HibernateValidationServiceProvider.class); binder.bind(LdapService.class, SunLdapServiceProvider.class); binder.bind(SecurityService.class, OpenIdProviderSecurityServiceProvider.class); binder.bind(KnowledgeService.class, DroolsKnowledgeServiceProvider.class); binder.bind(TransactionService.class, DefaultTransactionServiceProvider.class); binder.bind(OpenIdConsumerService.class, DefaultOpenIdConsumerServiceProvider.class); binder.bind(AccountService.class, SystemAccountServiceProvider.class); //binder.bind(UserSyncService.class, HttpClientUserSyncServiceProvider.class); } @Startup public static void startServices( @Primary final ConfigurationService configSvc, @Primary final TemplateService tplSvc, @Primary final TransactionService txSvc, @Primary final ValidationService validationSvc, @Primary final PersistenceService defaultPersistenceSvc, @DroolsTask final PersistenceService droolsTaskPersistenceSvc, @Primary final LdapService ldapSvc, @Primary final SecurityService<?> securitySvc, @Primary final KnowledgeService knowledgeSvc, @Primary final OpenIdConsumerService consumerSvc, @Primary final AccountService accountSvc) throws Exception { //@Primary final UserSyncService userSyncService) throws Exception { configSvc.start(); tplSvc.start(); txSvc.start(); validationSvc.start(); defaultPersistenceSvc.start(); droolsTaskPersistenceSvc.start(); ldapSvc.start(); securitySvc.start(); knowledgeSvc.start(); consumerSvc.start(); accountSvc.start(); //userSyncService.start(); } /*public void contributeRegistryStartup( OrderedConfiguration<Runnable> configuration, @Primary final ConfigurationService configSvc, @Primary final TemplateService tplSvc, @Primary final TransactionService txSvc, @Primary final ValidationService validationSvc, @Primary final PersistenceService defaultPersistenceSvc, @DroolsTaskPersistence final PersistenceService droolsTaskPersistenceSvc, @AttachmentPersistence final PersistenceService attachPersistenceSvc, @Primary final LdapService ldapSvc, @Primary final SecurityService<?> securitySvc, @Primary final KnowledgeService knowledgeSvc) { configuration.add("ServiceStartup", new Runnable() { @Override public void run() { try { configSvc.start(); tplSvc.start(); txSvc.start(); validationSvc.start(); defaultPersistenceSvc.start(); droolsTaskPersistenceSvc.start(); attachPersistenceSvc.start(); ldapSvc.start(); securitySvc.start(); knowledgeSvc.start(); } catch (Throwable t) { logger.error("Service repository start up failed.", t); throw new RuntimeException(t); } } }); }*/ }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ioc/FrameworkModule.java
Java
asf20
5,306
package com.zyeeda.framework.ioc; import java.util.HashSet; import java.util.Set; import org.apache.shiro.util.CollectionUtils; import org.apache.tapestry5.ioc.def.ContributionDef; import org.apache.tapestry5.ioc.def.DecoratorDef; import org.apache.tapestry5.ioc.def.ModuleDef; import org.apache.tapestry5.ioc.def.ServiceDef; public class CustomModuleDef implements ModuleDef { private Set<ContributionDef> defs; public CustomModuleDef(ContributionDef... defs) { this.defs = CollectionUtils.asSet(defs); } @SuppressWarnings("rawtypes") @Override public Class getBuilderClass() { return null; } @Override public Set<ContributionDef> getContributionDefs() { return this.defs; } @Override public Set<DecoratorDef> getDecoratorDefs() { return new HashSet<DecoratorDef>(); } @Override public String getLoggerName() { return "CustomModule"; } @Override public ServiceDef getServiceDef(String serviceId) { return null; } @Override public Set<String> getServiceIds() { return new HashSet<String>(); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ioc/CustomModuleDef.java
Java
asf20
1,044
// Copyright 2011, Zyeeda, Inc. All Rights Reserved. // Confidential and Proprietary Information of Zyeeda, Inc. package com.zyeeda.framework.account; import java.util.Map; import com.zyeeda.framework.service.Service; /** * account support service * * @author Qi Zhao * @date 2011-06-15 * * @LastChanged * @LastChangedBy $LastChangedBy: $ * @LastChangedDate $LastChangedDate: $ * @LastChangedRevision $LastChangedRevision: $ */ public interface AccountService extends Service { public Map<String, String> getMockSignInConfig(String prefix); }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/account/AccountService.java
Java
asf20
566
// Copyright 2011, Zyeeda, Inc. All Rights Reserved. // Confidential and Proprietary Information of Zyeeda, Inc. package com.zyeeda.framework.account.internal; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import org.apache.commons.configuration.Configuration; import org.apache.tapestry5.ioc.annotations.Marker; import org.apache.tapestry5.ioc.annotations.Primary; import org.apache.tapestry5.ioc.annotations.ServiceId; import org.apache.tapestry5.ioc.services.RegistryShutdownHub; import com.zyeeda.framework.account.AccountService; import com.zyeeda.framework.config.ConfigurationService; import com.zyeeda.framework.service.AbstractService; /** * account support service implement * * @author Qi Zhao * @date 2011-06-15 * * @LastChanged * @LastChangedBy $LastChangedBy: $ * @LastChangedDate $LastChangedDate: $ * @LastChangedRevision $LastChangedRevision: $ */ @ServiceId("system-account-service-provider") @Marker(Primary.class) public class SystemAccountServiceProvider extends AbstractService implements AccountService { private Configuration config; public SystemAccountServiceProvider(ConfigurationService configSvc, RegistryShutdownHub shutdownHub) { super(shutdownHub); this.config = this.getConfiguration(configSvc); } @Override @SuppressWarnings("unchecked") public Map<String, String> getMockSignInConfig(String prefix) { Map<String, String> result = new HashMap<String, String>(); Iterator<String> keys = config.getKeys(prefix); while (keys.hasNext()) { String key = keys.next(); result.put(key, config.getString(key)); } return result; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/account/internal/SystemAccountServiceProvider.java
Java
asf20
1,725
package com.zyeeda.framework.persistence; import java.util.Date; import org.hibernate.event.PreInsertEvent; import org.hibernate.event.PreInsertEventListener; import org.hibernate.event.PreUpdateEvent; import org.hibernate.event.PreUpdateEventListener; import com.zyeeda.framework.entities.base.RevisionDomainEntity; import com.zyeeda.framework.security.SecurityService; public class AutoRevisionEventListener implements PreInsertEventListener, PreUpdateEventListener { private static final long serialVersionUID = 3017978089669707604L; private SecurityService<?> securitySvc; public AutoRevisionEventListener(SecurityService<?> securitySvc) { this.securitySvc = securitySvc; } @Override public boolean onPreInsert(PreInsertEvent event) { Object e = event.getEntity(); if (e instanceof RevisionDomainEntity) { RevisionDomainEntity rev = (RevisionDomainEntity) e; Date now = new Date(); rev.setCreator(this.securitySvc.getCurrentUser()); rev.setCreatedTime(now); rev.setLastModifier(this.securitySvc.getCurrentUser()); rev.setLastModifiedTime(now); } return false; } @Override public boolean onPreUpdate(PreUpdateEvent event) { Object e = event.getEntity(); if (e instanceof RevisionDomainEntity) { RevisionDomainEntity rev = (RevisionDomainEntity) e; rev.setLastModifier(this.securitySvc.getCurrentUser()); rev.setLastModifiedTime(new Date()); } return false; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/persistence/AutoRevisionEventListener.java
Java
asf20
1,480
package com.zyeeda.framework.persistence.annotations; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.RetentionPolicy; @Target({ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DroolsTask { }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/persistence/annotations/DroolsTask.java
Java
asf20
391
/* * Copyright 2010 Zyeeda Co. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zyeeda.framework.persistence.internal; import java.util.Properties; import org.apache.tapestry5.ioc.annotations.Marker; import org.apache.tapestry5.ioc.annotations.Primary; import org.apache.tapestry5.ioc.annotations.ServiceId; import org.apache.tapestry5.ioc.services.RegistryShutdownHub; import org.hibernate.cfg.beanvalidation.BeanValidationEventListener; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.event.PreDeleteEventListener; import org.hibernate.event.PreInsertEventListener; import org.hibernate.event.PreUpdateEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import com.zyeeda.framework.persistence.AutoRevisionEventListener; import com.zyeeda.framework.persistence.AutoRevisionEventListener; import com.zyeeda.framework.persistence.PersistenceService; import com.zyeeda.framework.security.SecurityService; import com.zyeeda.framework.validation.ValidationService; /** * Persistence service using Hibernate. * * @author Rui Tang * @version %I%, %G% * @since 1.0 */ @ServiceId("default-persistence-service") @Marker(Primary.class) public class DefaultPersistenceServiceProvider extends AbstractPersistenceServiceProvider implements PersistenceService { private final static Logger logger = LoggerFactory.getLogger(DefaultPersistenceServiceProvider.class); private final static String PERSISTENCE_UNIT_NAME = "default"; //private final static String ZYEEDA_FRAMEWORK_ENTITY_CLASSES_MANIFEST_ENTRY_NAME = "Zyeeda-Framework-Entity-Classes"; // Injected private final ValidationService validationSvc; private final SecurityService<?> securitySvc; public DefaultPersistenceServiceProvider( @Primary ValidationService validationSvc, @Primary SecurityService<?> securitySvc, RegistryShutdownHub shutdownHub) { super(shutdownHub); this.validationSvc = validationSvc; this.securitySvc = securitySvc; } @Override public void start() throws Exception { Ejb3Configuration config = new Ejb3Configuration().configure(PERSISTENCE_UNIT_NAME, null); config.getEventListeners().setPreInsertEventListeners( new PreInsertEventListener[] { new BeanValidationEventListener(this.validationSvc.getPreInsertValidatorFactory(), new Properties()), new AutoRevisionEventListener(this.securitySvc) }); config.getEventListeners().setPreUpdateEventListeners( new PreUpdateEventListener[] { new BeanValidationEventListener(this.validationSvc.getPreUpdateValidatorFactory(), new Properties()), new AutoRevisionEventListener(this.securitySvc) }); config.getEventListeners().setPreDeleteEventListeners( new PreDeleteEventListener[] { new BeanValidationEventListener(this.validationSvc.getPreDeleteValidatorFactory(), new Properties()) }); //this.addMappingClasses(config, ZYEEDA_FRAMEWORK_ENTITY_CLASSES_MANIFEST_ENTRY_NAME); this.setSessionFactory(config.buildEntityManagerFactory()); } @Override protected Logger getLogger() { return logger; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/persistence/internal/DefaultPersistenceServiceProvider.java
Java
asf20
3,801
package com.zyeeda.framework.persistence.internal; import org.apache.tapestry5.ioc.annotations.Marker; import org.apache.tapestry5.ioc.annotations.ServiceId; import org.apache.tapestry5.ioc.services.RegistryShutdownHub; import org.hibernate.ejb.Ejb3Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.persistence.PersistenceService; import com.zyeeda.framework.persistence.annotations.DroolsTask; @ServiceId("drools-task-persistence-service") @Marker(DroolsTask.class) public class DroolsTaskPersistenceServiceProvider extends AbstractPersistenceServiceProvider implements PersistenceService { private final static Logger logger = LoggerFactory.getLogger(DroolsTaskPersistenceServiceProvider.class); private final static String PERSISTENCE_UNIT_NAME = "drools-task"; //private final static String DROOLS_TASK_ENTITY_CLASSES_MANIFEST_ENTRY_NAME = "Drools-Task-Entity-Classes"; public DroolsTaskPersistenceServiceProvider(RegistryShutdownHub shutdownHub) { super(shutdownHub); } @Override public void start() throws Exception { Ejb3Configuration config = new Ejb3Configuration().configure(PERSISTENCE_UNIT_NAME, null); //this.addMappingClasses(config, DROOLS_TASK_ENTITY_CLASSES_MANIFEST_ENTRY_NAME); this.setSessionFactory(config.buildEntityManagerFactory()); } @Override protected Logger getLogger() { return logger; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/persistence/internal/DroolsTaskPersistenceServiceProvider.java
Java
asf20
1,405
package com.zyeeda.framework.persistence.internal; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.apache.tapestry5.ioc.services.RegistryShutdownHub; import org.slf4j.Logger; import com.zyeeda.framework.persistence.PersistenceService; import com.zyeeda.framework.service.AbstractService; public abstract class AbstractPersistenceServiceProvider extends AbstractService implements PersistenceService { private EntityManagerFactory sessionFactory; private final ThreadLocal<EntityManager> sessionThreadLocal = new ThreadLocal<EntityManager>(); //private final ThreadLocal<Integer> countThreadLocal = new ThreadLocal<Integer>(); public AbstractPersistenceServiceProvider(RegistryShutdownHub shutdownHub) { super(shutdownHub); } /*protected void addMappingClasses(Ejb3Configuration config, String key) throws IOException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { logger.debug("context class loader is null, use current class loader instead"); cl = this.getClass().getClassLoader(); } Enumeration<URL> urls = cl.getResources("META-INF/MANIFEST.MF"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); InputStream is = null; try { is = url.openStream(); Manifest mf = new Manifest(is); String classes = mf.getMainAttributes().getValue(key); if (classes == null) { continue; } String[] classArray = StringUtils.split(classes, ','); for (String className : classArray) { try { Class<?> clazz = cl.loadClass(className); config.addAnnotatedClass(clazz); } catch (ClassNotFoundException e) { logger.warn(e.getMessage(), e); } } } finally { if (is != null) { is.close(); } } } }*/ protected abstract Logger getLogger(); @Override public void stop() throws Exception { this.sessionFactory.close(); this.sessionFactory = null; } @Override public EntityManager openSession() { EntityManager session = this.sessionThreadLocal.get(); if (session == null) { session = this.getSessionFactory().createEntityManager(); this.getLogger().info("Open session on thread [{}].", Thread.currentThread().getName()); this.sessionThreadLocal.set(session); } return session; } @Override public void closeSession() { EntityManager session = this.sessionThreadLocal.get(); if (session == null) { this.getLogger().warn("No session opened on thread [{}].", Thread.currentThread().getName()); return; } session.close(); this.sessionThreadLocal.remove(); this.getLogger().info("Close session on thread [{}].", Thread.currentThread().getName()); } @Override public EntityManager getCurrentSession() { return this.sessionThreadLocal.get(); } protected void setSessionFactory(EntityManagerFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public EntityManagerFactory getSessionFactory() { return this.sessionFactory; } /*@Override public Session openSession() { Integer count = countThreadLocal.get(); if (count == null) { count = 0; } countThreadLocal.set(++count); Session session = sessionThreadLocal.get(); if (session == null) { session = this.sessionFactory.openSession(); sessionThreadLocal.set(session); } return session; }*/ /*@Override public void closeSession() { Integer count = countThreadLocal.get(); if (count == null || count == 0) { LoggerHelper.trace(logger, "会话未开启"); return; } countThreadLocal.set(--count); if (count > 0) { LoggerHelper.trace(logger, "会话未关闭"); return; } this.realCloseSession(); }*/ /*private void realCloseSession() { Session session = sessionThreadLocal.get(); sessionThreadLocal.remove(); countThreadLocal.remove(); if (session != null) { session.close(); } LoggerHelper.debug(logger, "会话已关闭"); }*/ }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/persistence/internal/AbstractPersistenceServiceProvider.java
Java
asf20
4,244
package com.zyeeda.framework.persistence; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import com.zyeeda.framework.service.Service; public interface PersistenceService extends Service { public EntityManagerFactory getSessionFactory(); public EntityManager openSession(); public void closeSession(); public EntityManager getCurrentSession(); }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/persistence/PersistenceService.java
Java
asf20
401
package com.zyeeda.framework.ws; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapContext; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import org.apache.commons.lang.StringUtils; import org.apache.tapestry5.ioc.internal.services.RegistryShutdownHubImpl; import org.apache.tapestry5.ioc.services.RegistryShutdownHub; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.account.AccountService; import com.zyeeda.framework.account.internal.SystemAccountServiceProvider; import com.zyeeda.framework.config.ConfigurationService; import com.zyeeda.framework.config.internal.DefaultConfigurationServiceProvider; import com.zyeeda.framework.entities.Account; import com.zyeeda.framework.entities.User; import com.zyeeda.framework.entities.Department; import com.zyeeda.framework.helpers.AccountHelper; import com.zyeeda.framework.ldap.LdapService; import com.zyeeda.framework.ldap.SearchControlsFactory; import com.zyeeda.framework.managers.AccountManager; import com.zyeeda.framework.managers.DepartmentManager; import com.zyeeda.framework.managers.UserManager; import com.zyeeda.framework.managers.UserPersistException; import com.zyeeda.framework.managers.internal.LdapDepartmentManager; import com.zyeeda.framework.managers.internal.LdapUserManager; import com.zyeeda.framework.managers.internal.SystemAccountManager; import com.zyeeda.framework.sync.UserSyncService; import com.zyeeda.framework.utils.LdapEncryptUtils; import com.zyeeda.framework.viewmodels.AccountVo; import com.zyeeda.framework.viewmodels.UserVo; import com.zyeeda.framework.ws.base.ResourceService; @Path("/users") public class UserService extends ResourceService { private Logger logger = LoggerFactory.getLogger(UserService.class); public UserService(@Context ServletContext ctx) { super(ctx); } private static String createUserDn(String parent, String id) { return "uid=" + id + "," + parent; } @POST @Path("/{parent:.*}") @Produces("application/json") public User persist(@FormParam("") User user, @PathParam("parent") String parent) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); UserSyncService userSyncService = this.getUserSynchService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); SearchControls sc = SearchControlsFactory.getSearchControls( SearchControls.SUBTREE_SCOPE); List<User> userList = userMgr.findByName(user.getId(), sc); if (userList != null && userList.size() > 0) { throw new RuntimeException("账号不能重复"); } else { user.setDepartmentName(parent); user.setDeptFullPath(createUserDn(parent, user.getId())); userMgr.persist(user); user = userMgr.findById(user.getDeptFullPath()); userSyncService.persist(user); return user; } } @DELETE @Path("/{id}") public String remove(@PathParam("id") String id, @PathParam("cascade") Boolean cascade) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); if (cascade != null) { userMgr.remove(id); return "{success: 'true'}"; } else { Integer count = userMgr.getChildrenCountById(id, "(objectclass=*)"); if (count > 0) { return "{\"success\": \"false\"}"; } else { userMgr.remove(id); return "{\"success\": \"true\"}"; } } } @PUT @Path("/{id}") @Produces("application/json") public User update(@FormParam("") User user, @PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); UserSyncService userSyncService = this.getUserSynchService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); String uid = id.substring(id.indexOf("=") + 1, id.indexOf(",")); if (!uid.equals(user.getId())) { throw new RuntimeException("不能修改账号"); } else { user.setDeptFullPath(id); userMgr.update(user); User u = userMgr.findById(id); if (u != null) { userSyncService.update(user); } else { userSyncService.persist(user); } return user; } } @GET @Path("/{id}") @Produces("application/json") public User findById(@PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); return userMgr.findById(id); } @GET @Path("/search/{name}") @Produces("application/json") public List<UserVo> getUserListByName(@PathParam("name") String name) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); return UserService.fillUserListPropertiesToVo(userMgr.findByName(name)); } @GET @Path("/search") @Produces("application/json") public String search(@FormParam("name") String name) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); List<User> userList = userMgr.search(name); StringBuffer buffer = new StringBuffer("{"); buffer.append("\"totalRecords\":").append(userList.size()) .append(",").append("\"startIndex\":").append(0) .append(",").append("\"pageSize\":").append(13) .append(",").append("\"records\":["); for (User user : userList) { buffer.append("{\"id\":").append("\"").append(user.getId()).append("\"").append(",") .append("\"username\":").append("\"").append(user.getUsername()).append("\"").append(",") .append("\"mobile\":").append("\"").append(user.getMobile() == null ? "" : user.getMobile()).append("\"").append(",") .append("\"email\":").append("\"").append(user.getEmail() == null ? "" : user.getEmail()).append("\"").append(",") .append("\"status\":").append("\"").append(user.getStatus() == null ? "" : user.getStatus()).append("\"").append(",") .append("\"parent\":").append("\"").append(user.getDepartmentName() == null ? "" : user.getDepartmentName()).append("\"").append(",") .append("\"fullpath\":").append("\"").append(user.getDeptFullPath() == null ? "" : user.getDeptFullPath()).append("\"").append("},"); } if (buffer.lastIndexOf(",") != -1 && userList.size() > 0) { buffer.deleteCharAt(buffer.lastIndexOf(",")); } buffer.append("]}"); return buffer.toString(); } @GET @Path("/userList/{deptId}") @Produces("application/json") public List<UserVo> getUserListByDepartmentId(@PathParam("deptId") String deptId) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); return UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(deptId)); } @PUT @Path("/{id}/update_password") @Produces("application/json") public User updatePassword(@PathParam("id") String id, @FormParam("oldPassword") String oldPassword, @FormParam("newPassword") String newPassword) throws UserPersistException, UnsupportedEncodingException, NoSuchAlgorithmException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); User u = userMgr.findById(id); String ldapPw = u.getPassword(); String inputPw = oldPassword; if (LdapEncryptUtils.verifySHA(ldapPw, inputPw)) { if (!LdapEncryptUtils.verifySHA(ldapPw, newPassword)) { userMgr.updatePassword(id, newPassword); } } else { throw new RuntimeException("旧密码输入错误"); } return userMgr.findById(id); } @PUT @Path("/{id}/enable") @Produces("application/json") public User enable(@PathParam("id") String id, @FormParam("status") Boolean visible) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); UserSyncService userSyncService = this.getUserSynchService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); userMgr.enable(id); userSyncService.enable(id); return userMgr.findById(id); } @PUT @Path("/{id}/unenable") @Produces("application/json") public User disable(@PathParam("id") String id, @FormParam("status") Boolean visible) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); UserSyncService userSyncService = this.getUserSynchService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); userMgr.disable(id); userSyncService.disable(id); return userMgr.findById(id); } @POST @Path("/{id}") @Produces("application/json") public void uploadPhoto(@Context HttpServletRequest request, @PathParam("id") String id) throws Throwable { InputStream in = request.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b, 0, 1024)) != -1) { baos.write(b, 0, len); } baos.flush(); // byte[] bytes = baos.toByteArray(); LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); User user = new User(); user.setId("china"); // user.setPhoto(bytes); userMgr.update(user); } @GET @Path("/current_user_in_dept_all_user") @Produces("application/json") public List<UserVo> getCurrentUserInDepartmentAllUser() throws UserPersistException { String currentUser = this.getSecurityService().getCurrentUser(); LdapService ldapSvc = this.getLdapService(); UserManager userManager = new LdapUserManager(ldapSvc); SearchControls sc = SearchControlsFactory.getSearchControls( SearchControls.SUBTREE_SCOPE); List<User> users = userManager.findByName(currentUser, sc); User user = null; if (users != null && users.size() > 0) { user = users.get(0); if (user != null && StringUtils.isNotBlank(user.getDeptFullPath())) { String secondDept = user.getDeptFullPath(); secondDept = secondDept.substring(secondDept.indexOf(",") + 1, secondDept.length()); String[] spilt = StringUtils.split(secondDept); if (spilt.length >= 2) { secondDept = spilt[spilt.length - 2] + "," + spilt[spilt.length - 1]; } users = userManager.findByDepartmentId(secondDept, sc); } } List<UserVo> listUser = fillUserListPropertiesToVo(users, "task"); return listUser; } public static UserVo fillUserPropertiesToVo(User user) { UserVo userVo = new UserVo(); userVo.setId(user.getId()); userVo.setType("task"); userVo.setLabel(user.getUsername()); userVo.setCheckName(user.getUsername()); userVo.setLeaf(true); userVo.setUid(user.getId()); userVo.setDeptFullPath(user.getDeptFullPath()); userVo.setKind("user"); return userVo; } public static UserVo fillUserPropertiesToVo(User user, String type) { UserVo userVo = new UserVo(); userVo.setId(user.getId()); userVo.setType(type); userVo.setLabel( user.getUsername()); userVo.setCheckName(user.getUsername()); userVo.setLeaf(true); userVo.setUid(user.getId()); userVo.setDeptFullPath(user.getDeptFullPath()); userVo.setKind("user"); return userVo; } public static List<UserVo> fillUserListPropertiesToVo(List<User> userList) { List<UserVo> userVoList = new ArrayList<UserVo>(userList.size()); UserVo userVo = null; for (User user : userList) { userVo = UserService.fillUserPropertiesToVo(user); userVoList.add(userVo); } return userVoList; } public static List<UserVo> fillUserListPropertiesToVo(List<User> userList, String type) { List<UserVo> userVoList = new ArrayList<UserVo>(userList.size()); UserVo userVo = null; for (User user : userList) { userVo = UserService.fillUserPropertiesToVo(user, type); userVoList.add(userVo); } return userVoList; } // @POST // @Path("/{id}") // @Produces("application/json") // public Account updateAccount(@FormParam("") Account objAccount, @PathParam("id") String fullPath){ // if(objAccount == null){ // throw new RuntimeException("用户名或密码不能为空"); // }else{ // objAccount.setUserFullPath(fullPath); // } // return objAccount; // } /** * 配置系统信息 * 将旧的数据删除,保存新的数据。 * Json list * return userList */ @POST @Path("/accounts/{id}") @Produces("application/json") public List<Account> updateAccounts(@FormParam("userList") String userListJson, @PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); AccountManager objAccountManager = new SystemAccountManager(ldapSvc); ObjectMapper mapper = new ObjectMapper(); List<Account> userList = null; try { userList = mapper.readValue(userListJson, new TypeReference<List<Account>>() { }); List<Account> tempAccountList = new ArrayList<Account>(); LdapContext ctx = ldapSvc.getLdapContext(); NamingEnumeration<SearchResult> ns = ctx.search(id, "objectclass=*", SearchControlsFactory.getDefaultSearchControls()); while (ns.hasMore()) { Account ac = AccountHelper.convertAttributesToAccount(ns.next().getAttributes()); tempAccountList.add(ac); } for (Account account : tempAccountList) { account.setUserFullPath(id); objAccountManager.remove("username=" + account.getUserName() + "," + id); } for (Account account : userList) { account.setUserFullPath(id); // objAccountManager.remove("username=" + account.getUserName() + "," + id); objAccountManager.update(account); } // logger.debug("UserList size is {}", userList.size()); } catch (JsonParseException e) { logger.error(e.getMessage(), e); } catch (JsonMappingException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } catch (NamingException e) { logger.error(e.getMessage(), e); } return userList; } // objAccountManager.remove(account.getSystemName()); // Account newAccount = objAccountManager.findByUserIdAndSystemName(id, account.getSystemName()); // newAccount.setUserName(account.getUserName()); // newAccount.setPassword(account.getPassword()); // newAccount.setVisible(account.getVisible()); // objAccountManager.update(newAccount); // account.setUserFullPath(id); // objAccountManager.remove(account.getSystemName());//.findByUserIdAndSystemName(id, account.getSystemName()); //// newAccount.setUserName(account.getUserName()); //// newAccount.setPassword(account.getPassword()); //// newAccount.setVisible(account.getVisible()); //// newAccount.setUserFullPath(id); /** * get account list */ @GET @Path("/accounts/{id}") @Produces("application/json") public AccountVo getAccounts(@PathParam("id") String id) throws UserPersistException{ LdapService ldapSvc = this.getLdapService(); AccountManager objAccountManager = new SystemAccountManager(ldapSvc); List<Account> list = objAccountManager.findByUserId(id); AccountVo avo = new AccountVo(); avo.setAccounts(list); return avo; } // public void removeSysConfigure(String systemName) throws UserPersistException{ // LdapService ldapSvc = this.getLdapService(); // AccountManager objAccountManager = new SystemAccountManager(ldapSvc); // objAccountManager.remove(systemName); // } /* @POST @Path("/accounts/{id}") @Produces("application/json") public Account updateAccounts(@FormParam("") Account objAccount, @PathParam("id") String id) throws UserPersistException{ LdapService ldapSvc = this.getLdapService(); AccountManager objAccountManager = new SystemAccountManager(ldapSvc); if(objAccount == null){ throw new RuntimeException("用户名或密码为空"); } else { objAccount.setUserFullPath("username=" + objAccount.getUserName() + "," + id); objAccountManager.update(objAccount); return objAccount; } } */ // @GET @Path("/systemUsers/{uid}/{systemName}") @Produces("application/json") public Map<String, Object> mockSignIn(@PathParam("uid") String uid,@PathParam("systemName") String systemName) throws UserPersistException{ logger.debug(")))))))))))))uid = {} and systemName = {}", uid, systemName); LdapService ldapSvc = this.getLdapService(); AccountManager objAccountManager = new SystemAccountManager(ldapSvc); RegistryShutdownHub regShutdownHub = new RegistryShutdownHubImpl(logger); Collection<ServletContext> contexts = new ArrayList<ServletContext>(); contexts.add(this.getServletContext()); ConfigurationService configService = new DefaultConfigurationServiceProvider(contexts, regShutdownHub); AccountService accountSve = new SystemAccountServiceProvider(configService, regShutdownHub); // List<Account> list = objAccountManager.findByUserId(uid); //Map map = accountSve.getMockSignInConfig("oa.sign.in.url.test"); //logger.debug(")))))))))))))))))map url is {}", map.get("oa.sign.in.url.test")); Map<String,Object> result = new HashMap<String, Object>(); result.put("account", objAccountManager.findByUserIdAndSystemName(uid, systemName)); result.put("url", accountSve.getMockSignInConfig(systemName)); return result; } @GET @Path("/tests/{uid}/{systemName}") public String testMethod(@PathParam("uid") String uid,@PathParam("systemName") String systemName) { return "uid = "+uid + " systemName = "+systemName; } @GET @Path("/userlist_for_defect_by_current_site_user_send_sms/{deptName}") @Produces("application/json") public List<User> getUserListByDepartmentName(@PathParam("deptName") String deptName) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); DepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); SearchControls sc = SearchControlsFactory.getSearchControls(SearchControls.SUBTREE_SCOPE); List<Department> deptList = deptMgr.findByName(deptName); Department dept = null; if (deptList != null && deptList.size() > 0) { dept = deptList.get(0); } List<User> userList = userMgr.findByDepartmentId(dept.getDeptFullPath(), sc); return userList; } @GET @Path("/current_all_user_defect") @Produces("application/json") public List<UserVo> getCurrentUserInDepartmentAllUserDefect() throws UserPersistException { String currentUser = this.getSecurityService().getCurrentUser(); LdapService ldapSvc = this.getLdapService(); UserManager userManager = new LdapUserManager(ldapSvc); SearchControls sc = SearchControlsFactory.getSearchControls( SearchControls.SUBTREE_SCOPE); List<User> users = userManager.findByName(currentUser, sc); User user = null; if (users != null && users.size() > 0) { user = users.get(0); if (user != null && StringUtils.isNotBlank(user.getDeptFullPath())) { String secondDept = user.getDeptFullPath(); secondDept = secondDept.substring(secondDept.indexOf(",") + 1, secondDept.length()); String[] spilt = StringUtils.split(secondDept); if (spilt.length >= 2) { secondDept = spilt[spilt.length - 2] + "," + spilt[spilt.length - 1]; } users = userManager.findByDepartmentId(secondDept, sc); } } List<UserVo> listUser = fillUserListPropertiesToVoDefect(users); return listUser; } public static List<UserVo> fillUserListPropertiesToVoDefect(List<User> userList) { List<UserVo> userVoList = new ArrayList<UserVo>(userList.size()); UserVo userVo = null; for (User user : userList) { userVo = UserService.fillUserPropertiesToVo(user); userVoList.add(userVo); } return userVoList; } public static UserVo fillUserPropertiesToVoDefect(User user) { UserVo userVo = new UserVo(); userVo.setId(user.getId()); userVo.setType("task"); userVo.setLabel(user.getId() ); userVo.setCheckName(user.getId()); userVo.setLeaf(true); userVo.setUid(user.getId()); userVo.setDeptFullPath(user.getDeptFullPath()); userVo.setKind("user"); return userVo; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/UserService.java
Java
asf20
21,311
package com.zyeeda.framework.ws; import javax.servlet.ServletContext; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import com.zyeeda.framework.ws.base.ResourceService; @Path("/permission") public class PermissionService extends ResourceService{ public PermissionService(@Context ServletContext ctx){ super(ctx); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/PermissionService.java
Java
asf20
352
package com.zyeeda.framework.ws; import java.util.Collections; import java.util.List; import javax.servlet.ServletContext; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import com.googlecode.genericdao.search.Filter; import com.googlecode.genericdao.search.Search; import com.zyeeda.framework.entities.Dictionary; import com.zyeeda.framework.managers.DictionaryManager; import com.zyeeda.framework.managers.internal.DefaultDictionaryManager; import com.zyeeda.framework.utils.MenuListComparator; import com.zyeeda.framework.ws.base.ResourceService; @Path("/dicts") public class DictionaryService extends ResourceService { public DictionaryService(@Context ServletContext ctx) { super(ctx); } @GET @Path("/{type}") @Produces("application/json") public List<Dictionary> getDictionary(@PathParam("type") String type) { DictionaryManager dictMgr = new DefaultDictionaryManager(this.getPersistenceService()); Search search = new Search(); search.addFilterEqual("type", type); List<Dictionary> dicts = dictMgr.search(search); return dicts; } @POST @Path("/") @Produces("application/json") public Dictionary createDictionary(@FormParam("") Dictionary dict) { DictionaryManager dictMgr = new DefaultDictionaryManager(this.getPersistenceService()); dictMgr.persist(dict); this.getPersistenceService().getCurrentSession().flush(); return dictMgr.find(dict.getId()); } @GET @Path("/get_list_except") @Produces("application/json") public List<Dictionary> getListExceptId(@QueryParam("name") String name) { DictionaryManager dictMgr = new DefaultDictionaryManager(this.getPersistenceService()); Search search = new Search(); //search.addField(Filter.equal("type", "defectLevel"), Filter.notEqual("name", name)); search.addFilterEqual("type", "defectLevel"); search.addFilterNotEqual("name", name); return dictMgr.search(search); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/DictionaryService.java
Java
asf20
2,130
package com.zyeeda.framework.ws; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.entities.Department; import com.zyeeda.framework.entities.Role; import com.zyeeda.framework.entities.User; import com.zyeeda.framework.ldap.LdapService; import com.zyeeda.framework.managers.RoleManager; import com.zyeeda.framework.managers.UserManager; import com.zyeeda.framework.managers.UserPersistException; import com.zyeeda.framework.managers.internal.DefaultRoleManager; import com.zyeeda.framework.managers.internal.LdapDepartmentManager; import com.zyeeda.framework.managers.internal.LdapUserManager; import com.zyeeda.framework.viewmodels.DepartmentVo; import com.zyeeda.framework.viewmodels.OrganizationNodeVo; import com.zyeeda.framework.viewmodels.UserVo; import com.zyeeda.framework.ws.base.ResourceService; @Path("/depts") public class DepartmentService extends ResourceService { private static final Logger logger = LoggerFactory.getLogger(DepartmentService.class); public DepartmentService(@Context ServletContext ctx) { super(ctx); } @POST @Path("/{parent}") @Produces("application/json") public Department persist(@FormParam("") Department dept, @PathParam("parent") String parent) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); if (deptMgr.findByName(dept.getName()) != null && deptMgr.findByName(dept.getName()).size() > 0) { throw new RuntimeException("部门名称不能重复"); } else { dept.setParent(parent); dept.setId("ou=" + dept.getName() + "," + dept.getParent()); dept.setDeptFullPath("ou=" + dept.getName() + "," + dept.getParent()); deptMgr.persist(dept); return deptMgr.findById(dept.getId()); } } @DELETE @Path("/{id}") @Produces("application/json") public String remove(@PathParam("id") String id, @FormParam("cascade") String cascade) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); LdapUserManager userManager = new LdapUserManager(ldapSvc); if (cascade != null) { deptMgr.remove(id); return "{\"success\": \"true\"}"; } else { Integer deptCount = deptMgr.getChildrenCountById(id, "(objectclass=*)"); Integer userCount = userManager.getChildrenCountById(id, "(objectclass=*)"); if (userCount > 0 || deptCount > 0) { return "{\"success\": \"false\"}"; } else { deptMgr.remove(id); return "{\"success\": \"true\"}"; } } } @PUT @Path("/{id}") @Produces("application/json") public Department update(@FormParam("") Department dept, @PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); dept.setId(id); deptMgr.update(dept); return deptMgr.findById(id); } @GET @Path("/{id}") @Produces("application/json") public Department findById(@PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); return deptMgr.findById(id); } @GET @Path("/search/{name}") @Produces("application/json") public List<DepartmentVo> findByName(@PathParam("name") String name) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); return DepartmentService.fillPropertiesToVo(deptMgr.findByName(name)); } @GET @Path("/search") @Produces("application/json") public String search(@FormParam("name") String name) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); List<Department> deptList = deptMgr.search(name); StringBuffer buffer = new StringBuffer("{"); buffer.append("\"totalRecords\":").append(deptList.size()) .append(",").append("\"startIndex\":").append(0) .append(",").append("\"pageSize\":").append(13) .append(",").append("\"records\":["); for (Department department : deptList) { buffer.append("{\"name\":").append("\"").append(department.getId()).append("\"").append(",") .append("\"parent\":").append("\"").append(department.getParent() == null ? "" : department.getParent()).append("\"").append(",") .append("\"fullpath\":").append("\"").append(department.getDeptFullPath() == null ? "" : department.getDeptFullPath()).append("\"").append(",") .append("\"description\":").append("\"").append(department.getDescription() == null ? "" : department.getDescription()).append("\"").append("},"); } if (buffer.lastIndexOf(",") != -1 && deptList.size() > 0) { buffer.deleteCharAt(buffer.lastIndexOf(",")); } buffer.append("]}"); return buffer.toString(); } @GET @Path("/search/{parent}/{name}") @Produces("application/json") public List<DepartmentVo> findByName(@PathParam("parent") String parent, @PathParam("name") String name) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); return DepartmentService.fillPropertiesToVo(deptMgr.findByName(parent, name)); } @GET @Path("/{id}/children") @Produces("application/json") public List<OrganizationNodeVo> getChildrenById(@Context HttpServletRequest request, @PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); LdapUserManager userMgr = new LdapUserManager(ldapSvc); List<DepartmentVo> deptVoList = null; List<UserVo> userVoList = null; String type = request.getParameter("type"); if (StringUtils.isNotBlank(type) && "task".equals(type)) { deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id), type); userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id), type); } else { deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id)); userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id)); } List<OrganizationNodeVo> orgList = this.mergeDepartmentVoAndUserVo(deptVoList, userVoList); return orgList; } private List<OrganizationNodeVo> mergeDepartmentVoAndUserVo(List<DepartmentVo> deptVoList, List<UserVo> userVoList) { List<OrganizationNodeVo> orgNodeVoList = new ArrayList<OrganizationNodeVo>(); for (DepartmentVo deptVo: deptVoList) { OrganizationNodeVo orgNodeVo = new OrganizationNodeVo(); orgNodeVo.setId(deptVo.getId()); orgNodeVo.setCheckName(deptVo.getCheckName()); orgNodeVo.setIo(deptVo.getIo()); orgNodeVo.setLabel(deptVo.getLabel()); orgNodeVo.setType(deptVo.getType()); orgNodeVo.setFullPath(deptVo.getDeptFullPath()); orgNodeVo.setKind(deptVo.getKind()); orgNodeVoList.add(orgNodeVo); } for (UserVo userVo: userVoList) { logger.debug("username = {}", userVo.getCheckName()); OrganizationNodeVo orgNodeVo = new OrganizationNodeVo(); orgNodeVo.setId(userVo.getDeptFullPath()); orgNodeVo.setCheckName(userVo.getCheckName()); orgNodeVo.setIo(userVo.getId()); orgNodeVo.setLabel(userVo.getLabel()); orgNodeVo.setType(userVo.getType()); orgNodeVo.setLeaf(userVo.isLeaf()); orgNodeVo.setFullPath(userVo.getDeptFullPath()); orgNodeVo.setKind(userVo.getKind()); orgNodeVoList.add(orgNodeVo); } return orgNodeVoList; } public static DepartmentVo fillPropertiesToVo(Department dept) { DepartmentVo deptVo = new DepartmentVo(); deptVo.setId(dept.getId()); deptVo.setType("io"); deptVo.setLabel(dept.getName()); deptVo.setCheckName(dept.getId()); deptVo.setLeaf(false); if (StringUtils.isBlank(dept.getParent())) { deptVo.setDeptFullPath("o=" + dept.getId()); } else { deptVo.setDeptFullPath("ou=" + dept.getId() + "," + dept.getParent()); } if (StringUtils.isBlank(deptVo.getDeptFullPath())) { deptVo.setIo("/rest/depts/root/children"); } else { deptVo.setIo("/rest/depts/" + deptVo.getDeptFullPath() + "/children"); } deptVo.setKind("dept"); return deptVo; } public static List<DepartmentVo> fillPropertiesToVo(List<Department> deptList, String type) { List<DepartmentVo> deptVoList = new ArrayList<DepartmentVo>(deptList.size()); DepartmentVo deptVo = null; for (Department dept : deptList) { deptVo = DepartmentService.fillPropertiesToVo(dept); deptVo.setId(dept.getId()); deptVo.setIo(deptVo.getIo() + "?type=task"); deptVo.setType(type); deptVoList.add(deptVo); } return deptVoList; } @GET @Path("second_level_dept_role") @Produces("application/json") public List<DepartmentVo> getSecondLevelDepartmentAndRole() throws UserPersistException { List<Department> deptList = null; LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); deptList = deptMgr.getChildrenById("o=广州局"); List<DepartmentVo> deptVoList = DepartmentService.fillPropertiesToVoAndRoles(deptList); return deptVoList; } public static List<DepartmentVo> fillPropertiesToVoAndRoles(List<Department> deptList) { List<DepartmentVo> deptVoList = new ArrayList<DepartmentVo>(deptList.size()); DepartmentVo deptVo = null; for (Department dept : deptList) { deptVo = DepartmentService.fillPropertiesToVoAndRole(dept); deptVoList.add(deptVo); } return deptVoList; } public static DepartmentVo fillPropertiesToVoAndRole(Department dept) { DepartmentVo deptVo = new DepartmentVo(); deptVo.setType("io"); deptVo.setLabel(dept.getName()); deptVo.setId(dept.getDeptFullPath()); deptVo.setCheckName(dept.getId()); deptVo.setLeaf(false); if (StringUtils.isNotBlank(dept.getDeptFullPath())) { deptVo.setIo("/rest/roles/dept_and_role/" + dept.getDeptFullPath()); } deptVo.setKind("dept"); return deptVo; } public static List<DepartmentVo> fillPropertiesToVo(List<Department> deptList) { List<DepartmentVo> deptVoList = new ArrayList<DepartmentVo>(deptList.size()); DepartmentVo deptVo = null; for (Department dept : deptList) { deptVo = DepartmentService.fillPropertiesToVo(dept); deptVoList.add(deptVo); } return deptVoList; } @GET @Path("root_and_second_level_dept") @Produces("application/json") public List<Department> getRootAndSecondLevelDepartment() throws UserPersistException { List<Department> deptList = null; LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); deptList = deptMgr.getRootAndSecondLevelDepartment(); // List<DepartmentVo> deptVoList = DepartmentService.fillPropertiesToVo(deptList); return deptList; } @GET @Path("root_and_second_level_dept_vo") @Produces("application/json") public List<DepartmentVo> getRootAndSecondLevelDepartmentVo() throws UserPersistException { List<Department> deptList = null; LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); deptList = deptMgr.getRootAndSecondLevelDepartment(); List<DepartmentVo> deptVoList = DepartmentService.fillPropertiesToVo(deptList); for (DepartmentVo deptVo : deptVoList) { deptVo.setIo(""); } return deptVoList; } @GET @Path("second_level_dept") @Produces("application/json") public List<Department> getSecondLevelDepartment() throws UserPersistException { List<Department> deptList = null; LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); deptList = deptMgr.getChildrenById("o=广州局"); return deptList; } @GET @Path("/children/{id}") @Produces("application/json") public List<OrganizationNodeVo> getChindren(@PathParam("id") String id) throws UserPersistException { List<Department> deptList = null; LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); deptList = deptMgr.getChildrenById(id); return this.mergeDepartmentVoAndUserVo(fillPropertiesToVo(deptList, "task"), new ArrayList<UserVo>()); } // @GET // @Path("/search_by_condition") // @Produces("application/json") public List<Department> searchByCondition(String condition) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); List<Department> deptList = deptMgr.search(condition); return deptList; } /** * 适用站点 * @param condition * @return * @throws UserPersistException */ @GET @Path("/site_dept") @Produces("application/json") public List<OrganizationNodeVo> getSiteDepartment(@QueryParam("condition") String condition) throws UserPersistException { List<Department> deptList = this.searchByCondition(""); List<String> siteDeptList = new ArrayList<String>(); siteDeptList.add("广州站"); siteDeptList.add("宝安站"); siteDeptList.add("福山站"); siteDeptList.add("肇庆站"); siteDeptList.add("花都站"); siteDeptList.add("穗东站"); List<DepartmentVo> deptVoList = fillPropertiesToVo(deptList, "task"); List<DepartmentVo> removeDeptVoList = new ArrayList<DepartmentVo>(); for (DepartmentVo deptVo : deptVoList) { deptVo.setIo(""); logger.info("department name is {}", deptVo.getId()); if (!siteDeptList.contains(deptVo.getId())) { removeDeptVoList.add(deptVo); } } deptVoList.removeAll(removeDeptVoList); return this.mergeDepartmentVoAndUserVo(deptVoList, new ArrayList<UserVo>()); } /** * 适用班组 * @return * @throws UserPersistException */ @GET @Path("/site_team/{id}") @Produces("application/json") public List<OrganizationNodeVo> getSuitTeam(@Context HttpServletRequest request, @PathParam("id") String id) throws UserPersistException { List<Department> deptList = null; LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); deptList = deptMgr.getChildrenById(id); List<DepartmentVo> deptVoList = fillPropertiesToVo(deptList, "task"); List<DepartmentVo> removeDeptVoList = new ArrayList<DepartmentVo>(); for (DepartmentVo departmentVo : deptVoList) { departmentVo.setIo(""); logger.info("department name is {}", departmentVo.getId()); if ("物资管理人员".equals(departmentVo.getId())) { removeDeptVoList.add(departmentVo); } } deptVoList.removeAll(removeDeptVoList); return this.mergeDepartmentVoAndUserVo(deptVoList, new ArrayList<UserVo>()); } /** * 消缺班组 * @param userId * @return * @throws UserPersistException */ @GET @Path("eliminating_team") @Produces("application/json") public List<Department> getDepartmentListByUserId() throws UserPersistException { List<Department> deptList = null; LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); UserManager userManager = new LdapUserManager(this.getLdapService()); String currentUser = this.getSecurityService().getCurrentUser(); List<User> userList = userManager.findByName(currentUser); User user = null; if (userList != null && userList.size() > 0) { user = userList.get(0); if (user != null && StringUtils.isNotBlank(user.getDepartmentName())) { String departmentName = user.getDepartmentName(); if (departmentName.indexOf(",") != -1) { departmentName = StringUtils.substring(departmentName, departmentName.indexOf(",") + 1, departmentName.length()); } deptList = deptMgr.getDepartmentListByUserId(departmentName); } } return deptList; } @GET @Path("/get_children/{id}") @Produces("application/json") public List<Department> getChindrenById(@PathParam("id") String id) throws UserPersistException { List<Department> deptList = null; LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); deptList = deptMgr.getChildrenById(id); return deptList; } @GET @Path("/{id}/children/{roleId}") @Produces("application/json") public List<OrganizationNodeVo> getChildrenNodesByDepartmentIdAndRoleId(@Context HttpServletRequest request, @PathParam("id") String id, @PathParam("roleId") String roleId) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role role = roleMgr.find(id); Set<String> roleByUser = new HashSet<String>(); if(role != null) { roleByUser = role.getSubjects(); } LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); LdapUserManager userMgr = new LdapUserManager(ldapSvc); List<DepartmentVo> deptVoList = null; List<UserVo> userVoList = null; String type = request.getParameter("type"); if (StringUtils.isNotBlank(type) && "task".equals(type)) { deptVoList = DepartmentService.fillDepartmentListPropertiesToVoByRoleId(deptMgr.getChildrenById(id), type, roleId); } else { deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id)); } userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id)); List<OrganizationNodeVo> orgList = this.mergeDepartmentVoAndUserVoCheckUser(deptVoList, userVoList, roleByUser); return orgList; } private List<OrganizationNodeVo> mergeDepartmentVoAndUserVoCheckUser(List<DepartmentVo> deptVoList, List<UserVo> userVoList, Set<String> userId) { List<OrganizationNodeVo> orgNodeVoList = new ArrayList<OrganizationNodeVo>(); for (DepartmentVo deptVo: deptVoList) { OrganizationNodeVo orgNodeVo = new OrganizationNodeVo(); orgNodeVo.setId(deptVo.getId()); orgNodeVo.setCheckName(deptVo.getCheckName()); orgNodeVo.setIo(deptVo.getIo()); orgNodeVo.setLabel(deptVo.getLabel()); orgNodeVo.setType(deptVo.getType()); orgNodeVo.setFullPath(deptVo.getId()); orgNodeVo.setKind(deptVo.getKind()); orgNodeVoList.add(orgNodeVo); } for (UserVo userVo: userVoList) { OrganizationNodeVo orgNodeVo = new OrganizationNodeVo(); orgNodeVo.setId(userVo.getCheckName()); orgNodeVo.setCheckName(userVo.getCheckName()); orgNodeVo.setIo(userVo.getId()); for(String id:userId){ if(id.equals(userVo.getId())){ orgNodeVo.setChecked(true); } } orgNodeVo.setLabel(userVo.getLabel()); orgNodeVo.setType("task"); orgNodeVo.setLeaf(userVo.isLeaf()); orgNodeVo.setFullPath("uid=" + userVo.getId() + "," + userVo.getDeptFullPath()); orgNodeVo.setKind(userVo.getKind()); orgNodeVoList.add(orgNodeVo); } return orgNodeVoList; } public static DepartmentVo fillDepartmentPropertiesToVoByRole(Department dept, String roleId) { DepartmentVo deptVo = new DepartmentVo(); deptVo.setId(dept.getId()); deptVo.setType("io"); deptVo.setLabel(dept.getName()); deptVo.setCheckName(dept.getId()); deptVo.setLeaf(false); if (StringUtils.isBlank(dept.getParent())) { deptVo.setDeptFullPath("o=" + dept.getId()); } else { deptVo.setDeptFullPath("ou=" + dept.getId() + "," + dept.getParent()); } if (StringUtils.isBlank(deptVo.getDeptFullPath())) { deptVo.setIo("/rest/depts/root/children"); } else { deptVo.setIo("/rest/depts/" + deptVo.getDeptFullPath() + "/children/"+roleId); } deptVo.setKind("dept"); return deptVo; } public static List<DepartmentVo> fillDepartmentListPropertiesToVoByRoleId(List<Department> deptList, String type, String roleId) { List<DepartmentVo> deptVoList = new ArrayList<DepartmentVo>(deptList.size()); DepartmentVo deptVo = null; for (Department dept : deptList) { deptVo = DepartmentService.fillDepartmentPropertiesToVoByRole(dept, roleId); deptVo.setIo(deptVo.getIo() + "?type=task"); deptVo.setType(type); deptVoList.add(deptVo); } return deptVoList; } @GET @Path("/{id}/children/for_user_combobox_dept_not_combobox") @Produces("application/json") public List<OrganizationNodeVo> getChildrenByIdForUserComboboxDeptNotCombobox( @Context HttpServletRequest request, @PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); LdapUserManager userMgr = new LdapUserManager(ldapSvc); List<DepartmentVo> deptVoList = null; List<UserVo> userVoList = null; String type = request.getParameter("type"); deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id)); for (DepartmentVo deptVo : deptVoList) { deptVo.setIo("/rest/depts/" + deptVo.getDeptFullPath() + "/children/for_user_combobox_dept_not_combobox?type=task"); } userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id), type); List<OrganizationNodeVo> orgList = this.mergeDepartmentVoAndUserVo(deptVoList, userVoList); return orgList; } @GET @Path("/{id}/children/for_dept_combobox_user_not_combobox") @Produces("application/json") public List<OrganizationNodeVo> getChildrenByIdForDeptComboboxUserNotCombobox( @Context HttpServletRequest request, @PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); LdapUserManager userMgr = new LdapUserManager(ldapSvc); List<DepartmentVo> deptVoList = null; List<UserVo> userVoList = null; String type = request.getParameter("type"); deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id), type); for (DepartmentVo deptVo : deptVoList) { deptVo.setIo("/rest/depts/" + deptVo.getDeptFullPath() + "/children/for_dept_combobox_user_not_combobox?type=task"); } userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id)); List<OrganizationNodeVo> orgList = this.mergeDepartmentVoAndUserVo(deptVoList, userVoList); return orgList; } @GET @Path("/{id}/children/for_user_combobox_dept_not_combobox") @Produces("application/json") public List<OrganizationNodeVo> getChildrenByIdForUserComboboxDeptNotCombobox( @PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); LdapUserManager userMgr = new LdapUserManager(ldapSvc); List<DepartmentVo> deptVoList = null; List<UserVo> userVoList = null; deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id)); userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id), "task"); List<OrganizationNodeVo> orgList = this.mergeDepartmentVoAndUserVo(deptVoList, userVoList); return orgList; } @GET @Path("/{id}/children/for_dept_combobox_user_not_combobox") @Produces("application/json") public List<OrganizationNodeVo> getChildrenByIdForDeptComboboxUserNotCombobox( @PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc); LdapUserManager userMgr = new LdapUserManager(ldapSvc); List<DepartmentVo> deptVoList = null; List<UserVo> userVoList = null; deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id), "task"); userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id)); List<OrganizationNodeVo> orgList = this.mergeDepartmentVoAndUserVo(deptVoList, userVoList); return orgList; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/DepartmentService.java
Java
asf20
25,297
package com.zyeeda.framework.ws; import java.util.ArrayList; import java.util.List; import com.zyeeda.framework.entities.Document; import com.zyeeda.framework.utils.DatetimeUtils; import com.zyeeda.framework.viewmodels.DocumentVo; import com.zyeeda.framework.viewmodels.DocumentsVo; public class DocumentServiceHelper { public static DocumentVo document2Vo(Document doc) { DocumentVo vo = new DocumentVo(); vo.setId(doc.getId()); vo.setFileName(doc.getName()); vo.setCreator(doc.getCreator()); vo.setCreatedTime(DatetimeUtils.formatDatetime(doc.getCreatedTime())); vo.setFileType(doc.getFileType()); vo.setFileSize(doc.getFileSize()); vo.setDeleteUrl(String.format("/rest/docs/%s", doc.getId())); vo.setDownloadUrl(String.format("/rest/docs/%s/download/%s", doc.getId(), doc.getName())); vo.setViewUrl(String.format("/rest/docs/%s/view/%s", doc.getId(), doc.getName())); return vo; } public static DocumentsVo documentList2Vo(List<Document> docs) { DocumentsVo docsVo = new DocumentsVo(); docsVo.setTotalRecords(docs.size()); docsVo.setStartIndex(0); List<DocumentVo> docVos = new ArrayList<DocumentVo>(docs.size()); for (Document doc : docs) { docVos.add(document2Vo(doc)); } docsVo.setRecords(docVos); return docsVo; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/DocumentServiceHelper.java
Java
asf20
1,331
package com.zyeeda.framework.ws; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.xml.xpath.XPathExpressionException; import org.apache.commons.lang.StringUtils; import org.apache.shiro.util.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.googlecode.genericdao.search.Search; import com.zyeeda.framework.entities.Role; import com.zyeeda.framework.entities.User; import com.zyeeda.framework.managers.PermissionManager; import com.zyeeda.framework.managers.RoleManager; import com.zyeeda.framework.managers.UserManager; import com.zyeeda.framework.managers.UserPersistException; import com.zyeeda.framework.managers.internal.DefaultPermissionManager; import com.zyeeda.framework.managers.internal.DefaultRoleManager; import com.zyeeda.framework.managers.internal.LdapUserManager; import com.zyeeda.framework.viewmodels.PermissionVo; import com.zyeeda.framework.viewmodels.RoleVo; import com.zyeeda.framework.viewmodels.RoleWithUserVo; import com.zyeeda.framework.viewmodels.UserNameVo; import com.zyeeda.framework.viewmodels.UserVo; import com.zyeeda.framework.ws.base.ResourceService; @Path("/roles") public class RoleService extends ResourceService{ private static final Logger logger = LoggerFactory.getLogger(RoleService.class); private final static String ROAM_PERMISSION_FILE = "roamPermission.xml"; private final static String PERMISSION_FILE = "permission.xml"; public RoleService(@Context ServletContext ctx) { super(ctx); } @GET @Path("/get_role_with_out_dept") @Produces("application/json") public List<Role> getRoleWithOutDept(){ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Search search = new Search(); search.addFilterEmpty("deptepment"); List<Role> list = roleMgr.search(search); return list; } @GET @Path("/{id}/get_role") @Produces("application/json") public Role getOneRolesById(@PathParam("id") String id) { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); return roleMgr.find(id); } @GET @Path("/getAllRoles") @Produces("application/json") public List<Role> getRoles() { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); logger.debug("this get all roles is success!"); return roleMgr.findAll(); } @DELETE @Path("/") @Produces("application/json") public boolean getRoles(@QueryParam("ids") String ids ){ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); boolean bool = true; try { if(roleMgr != null){ String[] id=ids.split(";"); for(String sigleId:id){ roleMgr.removeById(sigleId); } } } catch (Exception e) { bool = false; } return bool; } @DELETE @Path("/defect_zizhi") @Produces("application/json") public List<Role> getRolesReturn(@QueryParam("ids") String ids ){ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); if(roleMgr != null){ String[] id=ids.split(";"); for(String sigleId:id){ roleMgr.removeById(sigleId); } } return roleMgr.findAll(); } @GET @Path("/{id}/role_and_auth") @Produces("application/json") public RoleWithUserVo getRolesById(@PathParam("id") String id) throws XPathExpressionException, IOException { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role role = roleMgr.find(id); logger.debug("this role's permission is " + role.getPermissions()); PermissionManager permissionMgr = new DefaultPermissionManager(); RoleWithUserVo roleWithUserVo = new RoleWithUserVo(); for(String userName:role.getSubjects()){ UserNameVo userVo = new UserNameVo(); userVo.setUserName(userName); roleWithUserVo.getUserName().add(userVo); } for(String auth:role.getPermissionList()){ PermissionVo permission = new PermissionVo(); permission = permissionMgr.getPermissionByPath(auth, PERMISSION_FILE); roleWithUserVo.getPermission().add(permission); } return roleWithUserVo; } @POST @Path("/{id}/edite") @Produces("application/json") public Role editeRole(@PathParam("id") String id, @FormParam("") Role role){ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role newRole=roleMgr.find(id); newRole.setName(role.getName()); newRole.setDescription(role.getDescription()); this.getPersistenceService().getCurrentSession().flush(); return roleMgr.find(id); } @POST @Path("/{id}/zizhi_edite") @Produces("application/json") public List<Role> editeRoleReturnAll(@PathParam("id") String id, @FormParam("") Role role){ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role newRole=roleMgr.find(id); newRole.setName(role.getName()); newRole.setDescription(role.getDescription()); this.getPersistenceService().getCurrentSession().flush(); return roleMgr.findAll(); } @POST @Path("/") @Produces("application/json") public Role creatRole(@FormParam("") Role role) { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); String name = role.getName(); Search search = new Search(); search.addFilterEqual("name", name); List<Role> list = roleMgr.search(search); if (list.size() > 0) { return null; }else{ roleMgr.persist(role); this.getPersistenceService().getCurrentSession().flush(); return roleMgr.find(role.getId()); } } @POST @Path("/return_all") @Produces("application/json") public List<Role> creatRoleReturnAll(@FormParam("") Role role) { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); String name = role.getName(); Search search = new Search(); search.addFilterEqual("name", name); List<Role> list = roleMgr.search(search); if (list.size() > 0) { return null; }else{ roleMgr.persist(role); this.getPersistenceService().getCurrentSession().flush(); return roleMgr.findAll(); } } @PUT @Path("/") @Produces("application/json") public Role editRole(@FormParam("") Role role) { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role setRole=roleMgr.find(role.getId()); Role newRole=roleMgr.save(setRole); this.getPersistenceService().getCurrentSession().flush(); return newRole; } @POST @Path("/{id}/assign_user") @Produces("application/json") public void assignRoleUser(@PathParam("id") String id,@QueryParam("ids") String ids) { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role role = roleMgr.find(id); role.getSubjects().clear(); if(StringUtils.isNotBlank(ids)){ String[] usersName = ids.split(","); for (int i = 0; i < usersName.length; i++) { role.getSubjects().add(usersName[i]); } } this.getPersistenceService().getCurrentSession().flush(); } @GET @Path("/{id}/sub_user") @Produces("application/json") public List<String> getUserByRoleId(@PathParam("id") String id){ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role role = roleMgr.find(id); Set<String> user = role.getSubjects(); List<String> list = new ArrayList<String>(); for(String userId:user) { list.add(userId); } return list; } @POST @Path("/{id}/assign_auth") @Produces("application/json") public Role assignRoleAuth(@PathParam("id") String id, @FormParam("") Role role) throws XPathExpressionException, IOException { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); PermissionManager permissionMgr = new DefaultPermissionManager(); Role newRole = roleMgr.find(id); String[] str = role.getPermissions().split(";"); List<String> authList = CollectionUtils.asList(str); String authArray = permissionMgr.getParentPermissionListAuthByList(authList, PERMISSION_FILE); String auth = newRole.getPermissions(); if(StringUtils.isBlank(auth)){ newRole.setPermissions(authArray); } else { int flog = auth.indexOf("_"); if(flog >= 0){ String menuAuth = auth.substring(flog + 1, auth.length()); String menuPermission = authArray + "_" + menuAuth; newRole.setPermissions(menuPermission); } else { newRole.setPermissions(authArray); } } this.getPersistenceService().getCurrentSession().flush(); return newRole; } @POST @Path("/{id}/assign_raom_auth") @Produces("application/json") public Role assignroamRoleAuth(@PathParam("id") String id, @FormParam("") Role role) throws XPathExpressionException, IOException { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); PermissionManager permissionMgr = new DefaultPermissionManager(); Role newRole = roleMgr.find(id); logger.debug("this ramoPermissions is : {}", role.getRamoPermissions()); String[] str = role.getRamoPermissions().split(";"); List<String> authList = CollectionUtils.asList(str); String authArray = permissionMgr.getParentPermissionListAuthByList(authList,ROAM_PERMISSION_FILE); String auth = newRole.getPermissions(); if(StringUtils.isBlank(auth)) { String menuPermission = "_" + authArray; newRole.setPermissions(menuPermission); } else { int flog = auth.indexOf("_"); if(flog >= 0){ String menuAuth = auth.substring(0, flog); String menuPermission = menuAuth+ "_" + authArray; newRole.setPermissions(menuPermission); } else { String menuPermission = auth + "_" + authArray; logger.debug("this ramoPermissions is : {}", menuPermission); newRole.setPermissions(menuPermission); } } this.getPersistenceService().getCurrentSession().flush(); return newRole; } @POST @Path("/{id}/remove_auth") @Produces("application/json") public Role removeAuth(@PathParam("id") String id, @QueryParam("permission") String permission) throws XPathExpressionException, IOException{ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role role = roleMgr.find(id); String[] permissions = permission.split(";"); List<String> permissionSet = role.getPermissionList(); for(String havaermissions : permissions){ if (permissionSet.contains(havaermissions)) { permissionSet.remove(havaermissions); } } String utils = StringUtils.join(permissionSet, ";"); role.setPermissions(utils); this.getPersistenceService().getCurrentSession().flush(); return role; } @POST @Path("/{id}/remove_user") @Produces("application/json") public boolean removeUser(@PathParam("id") String id, @QueryParam("subject") String subject) throws XPathExpressionException, IOException{ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role role = roleMgr.find(id); String[] subjects = subject.split(";"); boolean result = false; for(String subjectsSub:subjects) { for(String auth:role.getSubjects()) { if(auth.equals(subjectsSub)) { result = true; logger.debug("this role's subject remove is success" ); break; } } if(result) { role.getSubjects().remove(subjectsSub); } } this.getPersistenceService().getCurrentSession().flush(); // PermissionManager permissionMgr = new DefaultPermissionManager(); // RoleWithUserVo roleWithUserVo = new RoleWithUserVo(); // for(String userName:role.getSubjects()){ // UserNameVo userVo = new UserNameVo(); // userVo.setUserName(userName); // roleWithUserVo.getUserName().add(userVo); // } // for(String auth:role.getPermissionList()){ // PermissionVo permission = new PermissionVo(); // permission = permissionMgr.getPermissionByPath(auth); // roleWithUserVo.getPermission().add(permission); // } return result; } @GET @Path("/get_roles_subuser") @Produces("application/json") public Set<UserVo> getAllSubUser() throws UserPersistException{ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); String userName = this.getSecurityService().getCurrentUser(); List<Role> roleList = roleMgr.getRoleBySubject(userName); String creator = this.getSecurityService().getCurrentUser(); UserManager userManager = new LdapUserManager(this.getLdapService()); List<User> userList = userManager.findByName(creator); List<String> siteDeptList = new ArrayList<String>(); siteDeptList.add("广州站"); siteDeptList.add("宝安站"); siteDeptList.add("福山站"); siteDeptList.add("肇庆站"); siteDeptList.add("花都站"); siteDeptList.add("隧东站"); String subStationName = null; if (userList != null && userList.size() > 0) { if (StringUtils.isNotBlank(userList.get(0).getDeptFullPath())) { String fullPath = userList.get(0).getDeptFullPath(); String[] spilt = StringUtils.split(fullPath, ","); for (int i = 0; i < spilt.length; i++) { if (spilt[i].indexOf("=") != -1) { spilt[i] = StringUtils.substring(spilt[i], spilt[i] .indexOf("=") + 1, spilt[i].length()); if (siteDeptList.contains(spilt[i])) { subStationName = spilt[i]; break; } } } } } //List<String> subjectList = new ArrayList<String>(); Set<UserVo> userNameVoList = new HashSet<UserVo>(); for(Role role : roleList){ if("当班-值长".equals(role.getName()) && role.getDeptepment().equals(subStationName)){ for(String user : role.getSubjects()){ UserVo userVo = new UserVo(); userVo.setCheckName(user); userVo.setLabel(user); userVo.setType("task"); userVo.setLeaf(true); if(userNameVoList.size() == 0) { userNameVoList.add(userVo); continue; } for(UserVo userNameVo : userNameVoList){ if(!(userNameVo.getCheckName().equals(user))){ userNameVoList.add(userVo); break; } } } } } return userNameVoList; } @GET @Path("/depts/{id}") @Produces("application/json") public List<UserVo> getUserVo(@PathParam("id") String id) { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); Role role = roleMgr.find(id); List<UserVo> listUserVo = roleMgr.getUserVoByRole(role); return listUserVo; } @GET @Path("/get_all_roles_vo") @Produces("application/json") public List<RoleVo> getRolesVo() { RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); String hql = "select distinct F_DEPTEMENT_ID, F_DEPTEPMENT from sys_role"; List<Role> listRole = new ArrayList<Role>(); listRole = roleMgr.getRoleDistinct(hql); logger.debug("this get all roles is success!", listRole.size()); List<RoleVo> roleVo = roleMgr.deptToVo(listRole); return roleVo; } @GET @Path("/dept_and_role/{deptId}") @Produces("application/json") public List<RoleVo> getDeptById(@PathParam("deptId") String deptId){ RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService()); List<Role> list = new ArrayList<Role>(); Search search = new Search(); search.addFilterEqual("deptepmentId", deptId); list = roleMgr.search(search); List<RoleVo> roleVo = roleMgr.roleToVo(list); return roleVo; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/RoleService.java
Java
asf20
15,783
package com.zyeeda.framework.ws; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import com.zyeeda.framework.entities.TestEntity; import com.zyeeda.framework.ws.base.ResourceService; @Path("/tests") public class TestService extends ResourceService { public TestService(@Context ServletContext ctx) { super(ctx); } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) public List<TestEntity> getList() { List<TestEntity> list = new ArrayList<TestEntity>(); TestEntity e = new TestEntity(); e.setName("name1"); TestEntity e2 = new TestEntity(); e2.setName("name2"); TestEntity e3 = new TestEntity(); e3.setName("name3"); List<TestEntity> list2 = new ArrayList<TestEntity>(); list2.add(e2); list2.add(e3); e.setChildren(list2); TestEntity e4 = new TestEntity(); e4.setName("name4"); List<TestEntity> list3 = new ArrayList<TestEntity>(); list3.add(e4); e3.setChildren(list3); list.add(e); return list; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/TestService.java
Java
asf20
1,213
package com.zyeeda.framework.ws; import javax.servlet.ServletContext; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import com.zyeeda.framework.entities.User; import com.zyeeda.framework.managers.UserPersistException; import com.zyeeda.framework.managers.internal.DefaultUserManager; import com.zyeeda.framework.ws.base.ResourceService; @Path("/sync") public class DefaultUserService extends ResourceService { public DefaultUserService(@Context ServletContext ctx) { super(ctx); } @POST @Path("/persist") @Produces("application/json") public User createUser(@FormParam("") User user) throws UserPersistException { DefaultUserManager userMgr = new DefaultUserManager(this.getPersistenceService()); if (userMgr.findById(user.getId()) != null) { throw new RuntimeException("账号不能重复"); } else { userMgr.persist(user); return userMgr.findById(user.getId()); } } @PUT @Path("/update") @Produces("application/json") public User editUser(@FormParam("") User user) throws UserPersistException { DefaultUserManager userMg = new DefaultUserManager(this .getPersistenceService()); User u = userMg.find(user.getId()); u.setUsername(user.getUsername()); u.setEmail(user.getEmail()); u.setBirthday(user.getBirthday()); u.setDateOfWork(user.getDateOfWork()); u.setDegree(user.getDegree()); u.setDepartmentName(user.getDepartmentName()); u.setDeptFullPath(user.getDeptFullPath()); u.setGender(user.getGender()); u.setPassword(user.getPassword()); u.setMobile(user.getMobile()); u.setPosition(user.getPosition()); u.setPostStatus(user.getPostStatus()); u.setStatus(user.getStatus()); userMg.update(u); return u; } @PUT @Path("/editPassword") public User editPassword(@QueryParam("id") String id, @QueryParam("formerlyPassword") String formerlyPassword, @QueryParam("nowPasswrd") String nowPasswrd) throws UserPersistException { DefaultUserManager userMg = new DefaultUserManager(this .getPersistenceService()); User user = userMg.findById(id); if (user.getPassword().equals(formerlyPassword)) { if (!nowPasswrd.equals(user.getPassword())) { userMg.updatePassword(id, nowPasswrd); } } else { throw new RuntimeException("旧密码输入错误"); } return null; } @PUT @Path("/enable") @Produces("application/json") public User enable(@PathParam("id") String id) throws UserPersistException { DefaultUserManager userMg = new DefaultUserManager(this.getPersistenceService()); userMg.enable(id); return userMg.findById(id); } @PUT @Path("/{id}/disable") @Produces("application/json") public User disable(@PathParam("id") String id) throws UserPersistException { DefaultUserManager userMg = new DefaultUserManager(this.getPersistenceService()); userMg.enable(id); return userMg.findById(id); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/DefaultUserService.java
Java
asf20
3,113
package com.zyeeda.framework.ws.base; import javax.servlet.ServletContext; import org.apache.tapestry5.ioc.Registry; import com.zyeeda.framework.FrameworkConstants; import com.zyeeda.framework.ftp.FtpService; import com.zyeeda.framework.ftp.internal.CommonsFtpServiceProvider; import com.zyeeda.framework.knowledge.KnowledgeService; import com.zyeeda.framework.ldap.LdapService; import com.zyeeda.framework.ldap.internal.SunLdapServiceProvider; import com.zyeeda.framework.nosql.MongoDbService; import com.zyeeda.framework.nosql.internal.DefaultMongoDbServiceProvider; import com.zyeeda.framework.persistence.PersistenceService; import com.zyeeda.framework.persistence.internal.DefaultPersistenceServiceProvider; import com.zyeeda.framework.scheduler.SchedulerService; import com.zyeeda.framework.scheduler.internal.QuartzSchedulerServiceProvider; import com.zyeeda.framework.security.SecurityService; import com.zyeeda.framework.security.internal.OpenIdConsumerSecurityServiceProvider; import com.zyeeda.framework.sync.UserSyncService; import com.zyeeda.framework.sync.internal.HttpClientUserSyncServiceProvider; import com.zyeeda.framework.utils.IocUtils; public class ResourceService { private ServletContext ctx; private Registry reg; public ResourceService(ServletContext ctx) { this.ctx = ctx; this.reg = (Registry) this.ctx.getAttribute(FrameworkConstants.SERVICE_REGISTRY); } protected ServletContext getServletContext() { return this.ctx; } protected Registry getServiceRegistry() { return this.reg; } protected PersistenceService getPersistenceService() { return this.reg.getService(IocUtils.getServiceId(DefaultPersistenceServiceProvider.class), PersistenceService.class); } protected SecurityService<?> getSecurityService() { return this.reg.getService(IocUtils.getServiceId(OpenIdConsumerSecurityServiceProvider.class), SecurityService.class); } protected LdapService getLdapService() { return this.reg.getService(IocUtils.getServiceId(SunLdapServiceProvider.class), LdapService.class); } protected UserSyncService getUserSynchService() { return this.reg.getService(IocUtils.getServiceId(HttpClientUserSyncServiceProvider.class), UserSyncService.class); } protected SchedulerService<?> getSchedulerService() { return this.reg.getService(IocUtils.getServiceId(QuartzSchedulerServiceProvider.class), SchedulerService.class); } protected KnowledgeService getKnowledgeService(){ return this.reg.getService(KnowledgeService.class); } protected MongoDbService getMongoDbService() { return this.reg.getService(IocUtils.getServiceId(DefaultMongoDbServiceProvider.class), MongoDbService.class); } protected FtpService getFtpService() { return this.reg.getService(IocUtils.getServiceId(CommonsFtpServiceProvider.class), FtpService.class); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/base/ResourceService.java
Java
asf20
3,031
package com.zyeeda.framework.ws; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.xml.xpath.XPathExpressionException; import com.zyeeda.framework.entities.Role; import com.zyeeda.framework.managers.PermissionManager; import com.zyeeda.framework.managers.RoleManager; import com.zyeeda.framework.managers.internal.DefaultPermissionManager; import com.zyeeda.framework.managers.internal.DefaultRoleManager; import com.zyeeda.framework.viewmodels.AuthVO; import com.zyeeda.framework.viewmodels.PermissionVo; import com.zyeeda.framework.ws.base.ResourceService; @Path("/auth") public class AuthService extends ResourceService { private final static String ROAM_PERMISSION_FILE = "roamPermission.xml"; private final static String PERMISSION_FILE = "permission.xml"; public AuthService(@Context ServletContext ctx) { super(ctx); } @GET @Path("/{id}/{role_id}") @Produces("application/json") public List<AuthVO> getPermissionById(@PathParam("id") String id, @PathParam("role_id") String roleId) throws XPathExpressionException, IOException { RoleManager roleMgr = new DefaultRoleManager(this .getPersistenceService()); PermissionManager permissionMgr = new DefaultPermissionManager(); List<PermissionVo> list = permissionMgr.findSubPermissionById(id, PERMISSION_FILE); Role role = roleMgr.find(roleId); List<AuthVO> authVO = getAuthList(list, roleId, role .getPermissionList()); return authVO; } public List<AuthVO> getAuthList(List<PermissionVo> list, String roleId, List<String> auth) { List<AuthVO> authList = new ArrayList<AuthVO>(); for (PermissionVo permission : list) { //PermissionVo permission = (PermissionVo) list.get(i); AuthVO authVO = new AuthVO(); authVO.setId(permission.getId()); authVO.setLabel("<a>" + permission.getName() + "</a>"); authVO.setType("task"); authVO.setTag(permission.getValue()); for (String roleAuth : auth) { if (roleAuth.trim().equals(permission.getValue().trim())) { authVO.setChecked(true); break; } else { authVO.setChecked(false); } } if ("false".equals(permission.getIsHaveIO().toString())) { authVO.setIo("/rest/auth/" + permission.getId() + "/" + roleId); authVO.setLeaf(false); } else { authVO.setLeaf(true); } authList.add(authVO); // if(permission.getPermissionList().size() > 0) { // this.getAuthList(list, roleId, auth); // } } return authList; } @GET @Path("/{id}/raom_permission/{role_id}") @Produces("application/json") public List<AuthVO> getRPermissionById(@PathParam("id") String id, @PathParam("role_id") String roleId) throws XPathExpressionException, IOException { RoleManager roleMgr = new DefaultRoleManager(this .getPersistenceService()); PermissionManager permissionMgr = new DefaultPermissionManager(); List<PermissionVo> list = permissionMgr.findSubPermissionById(id, ROAM_PERMISSION_FILE); Role role = roleMgr.find(roleId); List<AuthVO> authVO = getRaomAuthList(list, roleId, role .getPermissionList()); return authVO; } public List<AuthVO> getRaomAuthList(List<PermissionVo> list, String roleId, List<String> auth) { List<AuthVO> authList = new ArrayList<AuthVO>(); for (PermissionVo permission : list) { //PermissionVo permission = (PermissionVo) list.get(i); AuthVO authVO = new AuthVO(); authVO.setId(permission.getId()); authVO.setLabel("<a>" + permission.getName() + "</a>"); authVO.setType("task"); authVO.setTag(permission.getValue()); for (String roleAuth : auth) { if (roleAuth.trim().equals(permission.getValue().trim())) { authVO.setChecked(true); break; } else { authVO.setChecked(false); } } if ("false".equals(permission.getIsHaveIO().toString())) { authVO.setIo("/rest/auth/" + permission.getId() + "/raom_permission/" + roleId); authVO.setLeaf(false); } else { authVO.setLeaf(true); } authList.add(authVO); // if(permission.getPermissionList().size() > 0) { // this.getAuthList(list, roleId, auth); // } } return authList; } // // @GET // @Path("/{id}/{role_id}") // @Produces("application/json") // public List<AuthVO> getRoamPermissionById(@PathParam("id") String id, // @PathParam("role_id") String roleId) // throws XPathExpressionException, IOException { // RoleManager roleMgr = new DefaultRoleManager(this // .getPersistenceService()); // PermissionManager permissionMgr = new DefaultPermissionManager(); // List<PermissionVo> list = permissionMgr.findSubPermissionById(id); // Role role = roleMgr.find(roleId); // List<AuthVO> authVO = getAuthList(list, roleId, role // .getPermissionList()); // return authVO; // } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/AuthService.java
Java
asf20
5,150
package com.zyeeda.framework.ws; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.xml.xpath.XPathExpressionException; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.entities.Role; import com.zyeeda.framework.managers.MenuManager; import com.zyeeda.framework.managers.PermissionManager; import com.zyeeda.framework.managers.internal.DefaultMenuManager; import com.zyeeda.framework.managers.internal.DefaultPermissionManager; import com.zyeeda.framework.managers.internal.DefaultRoleManager; import com.zyeeda.framework.viewmodels.MenuAndPermission; import com.zyeeda.framework.viewmodels.MenuVo; import com.zyeeda.framework.viewmodels.PermissionVo; import com.zyeeda.framework.ws.base.ResourceService; @Path("/menu") public class MenuService extends ResourceService { private static final Logger logger = LoggerFactory.getLogger(MenuService.class); private final static String ROAM_PERMISSION_FILE = "roamPermission.xml"; public MenuService(@Context ServletContext ctx) { super(ctx); } @GET @Path("/") @Produces("application/json") public MenuAndPermission getMenu()throws XPathExpressionException, IOException { String user = this.getSecurityService().getCurrentUser(); MenuManager menuMgr = new DefaultMenuManager(); DefaultRoleManager roleMgr = new DefaultRoleManager(this .getPersistenceService()); PermissionManager permissionMgr = new DefaultPermissionManager(); List<String> rolesAuth = new ArrayList<String>(); MenuAndPermission roleWithUserVo = new MenuAndPermission(); List<MenuVo> listMenu = new ArrayList<MenuVo>(); List<Role> roles = new ArrayList<Role>(); roles = roleMgr.getRoleBySubject(user); Set<String> authList = roleMgr.getListAuth(roles); Session session = SecurityUtils.getSubject().getSession(); //List<PermissionVo> permissionVoList = new ArrayList<PermissionVo>(); for(String auth : authList) { PermissionVo permission = permissionMgr.getPermissionByPath(auth, ROAM_PERMISSION_FILE); if(permission != null) { roleWithUserVo.getListPermission().add(permission); } } session.setAttribute("auth", authList); if(roles.size() == 1) { logger.debug("the value of the dept subject is = {} ", roles.get(0).getPermissionList()); listMenu = menuMgr.getMenuListByPermissionAuth(roles.get(0).getPermissionList()); roleWithUserVo.getListMenu().addAll(listMenu); return roleWithUserVo; } for(Role role:roles) { logger.debug("the value of the dept subject is = {} ", role.getPermissions()); for(String permission:role.getPermissionList()){ if(rolesAuth.size() == 0){ rolesAuth.add(permission); continue; } if(!(rolesAuth.contains(permission))){ rolesAuth.add(permission); } } } listMenu = menuMgr.getMenuListByPermissionAuth(rolesAuth); roleWithUserVo.getListMenu().addAll(listMenu); return roleWithUserVo; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/MenuService.java
Java
asf20
3,280
package com.zyeeda.framework.ws; import static com.zyeeda.framework.ws.DocumentServiceHelper.document2Vo; import static com.zyeeda.framework.ws.DocumentServiceHelper.documentList2Vo; import java.io.IOException; import java.io.InputStream; import java.net.URLConnection; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.ServletContext; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.MultipartBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.entities.Document; import com.zyeeda.framework.managers.DocumentException; import com.zyeeda.framework.managers.DocumentManager; import com.zyeeda.framework.managers.internal.MongoDbDocumentManager; import com.zyeeda.framework.viewmodels.DocumentVo; import com.zyeeda.framework.viewmodels.DocumentsVo; import com.zyeeda.framework.ws.base.ResourceService; @Path("/docs") public class DocumentService extends ResourceService { private static final Logger logger = LoggerFactory.getLogger(DocumentService.class); private final static String DEFAULT_CHARSET = "GBK"; //private static final int OBJECT_ID_LENGTH = 24; //private static final int DISPLAY_PAGE_NUMBER = 200; public DocumentService(@Context ServletContext ctx) { super(ctx); } @POST @Path("/") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("text/json") public DocumentVo upload(MultipartBody body, @QueryParam("foreignId") String foreignId, @Context UriInfo ui) throws DocumentException { logger.debug("foreign id = {}", foreignId); DocumentManager docMgr = new MongoDbDocumentManager(this.getMongoDbService()); Document doc = new Document(); doc.setTemp(true); String currentUser = this.getSecurityService().getCurrentUser(); doc.setOwner(currentUser); // 拥有人 doc.setCreator(currentUser); // 创建人 doc.setLastModifier(currentUser);// 最后修改人 doc.setForeignId(foreignId); Date now = new Date(); doc.setCreatedTime(now);// 创建时间 doc.setLastModifiedTime(now);// 最后修改时间 InputStream is = null; List<Attachment> attaches = body.getAllAttachments(); try { for (Attachment attach : attaches) { String key = attach.getContentDisposition().getParameter("name"); if ("Filedata".equals(key)) { MediaType contentType = attach.getContentType(); logger.debug("content type = {} ", contentType.toString()); doc.setContentType(contentType.toString()); doc.setSubType(contentType.getSubtype()); doc.setPrimaryType(contentType.getType()); is = attach.getDataHandler().getInputStream(); logger.debug("filesize = {}", is.available()); doc.setContent(is); } else if ("Filename".equals(key)) { String value = IOUtils.toString(attach.getDataHandler().getInputStream(), "UTF-8"); doc.setName(value); String fileType = StringUtils.substringAfterLast(value, "."); doc.setFileType(fileType); if (logger.isDebugEnabled()) { logger.debug("multipart: fileName = {}", value); logger.debug("file type = {}", value); } } } if (MediaType.APPLICATION_OCTET_STREAM.equals(doc.getContentType())) { String contentType = URLConnection.guessContentTypeFromName(doc.getName()); logger.debug("guess content type from name = {}", contentType); doc.setContentType(contentType); } docMgr.persist(doc); return document2Vo(docMgr.findById(doc.getId(), false)); } catch (IOException e) { throw new DocumentException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { logger.error("Saving document failed.", e); } } } } @GET @Path("/{id}/download/{fileName}") @Produces("multipart/mixed") public MultipartBody download(@PathParam("id") String id, @PathParam("fileName") String fileName) throws DocumentException { if (logger.isDebugEnabled()) { logger.debug("id = {}", id); logger.debug("file name = {}", fileName); } DocumentManager docMgr = new MongoDbDocumentManager(this.getMongoDbService()); InputStream is = null; try { Document doc = docMgr.findByIdAndFileName(id, fileName); if (doc == null) { throw new DocumentException("找不到指定文件"); } logger.debug("document content type = {}", doc.getContentType()); is = doc.getContent(); Attachment attach = new Attachment(id, MediaType.APPLICATION_OCTET_STREAM, is); List<Attachment> attaches = new ArrayList<Attachment>(); attaches.add(attach); return new MultipartBody(attaches, true); } finally { if (is != null) { try { is.close(); } catch (IOException e) { logger.error("Error occured when closing file stream.", e); } } } } @GET @Path("/{id}/view/{fileName}") @Produces("multipart/mixed") public Attachment view(@PathParam("id") String id, @PathParam("fileName") String fileName) throws DocumentException { if (logger.isDebugEnabled()) { logger.debug("id = {}", id); logger.debug("file name = {}", fileName); } DocumentManager docMgr = new MongoDbDocumentManager(this.getMongoDbService()); InputStream is = null; try { Document doc = docMgr.findByIdAndFileName(id, fileName); if (doc == null) { throw new DocumentException("找不到指定文件"); } String contentType = doc.getContentType(); logger.debug("document content type = {}", contentType); if (StringUtils.startsWith(contentType, "text")) { contentType = String.format("%s;charset=%s", doc.getContentType(), DEFAULT_CHARSET); } Attachment attach = new Attachment(id, contentType, doc.getContent()); return attach; } finally { if (is != null) { try { is.close(); } catch (IOException e) { logger.error("Error occured when closing file stream.", e); } } } } @DELETE @Path("/{id}") @Produces("application/json") public void deleteById(@PathParam("id") String id) { logger.debug("id = {}", id); DocumentManager documentManager = new MongoDbDocumentManager(this.getMongoDbService()); documentManager.removeById(id); } @GET @Path("/count") @Produces(MediaType.TEXT_PLAIN) public long countByForeignId(@QueryParam("foreignId") String foreignId) { logger.debug("foreign id = {}", foreignId); DocumentManager docMgr = new MongoDbDocumentManager(this.getMongoDbService()); return docMgr.countByForeignId(foreignId); } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) public DocumentsVo listByForeignId(@QueryParam("foreignId") String foreignId, @Context UriInfo ui) { logger.debug("foreign id = {}", foreignId); DocumentManager docMgr = new MongoDbDocumentManager(this.getMongoDbService()); List<Document> docs = docMgr.findByForeignId(foreignId); return documentList2Vo(docs); } /*@GET @Path("/list/{page}") @Produces(MediaType.APPLICATION_JSON) public DocumentsVo listByForeignId(@QueryParam("foreginId") String foreginId, @QueryParam("keyword") String keyword, @PathParam("page") int page) throws DocumentException { int skip = (page - 1) * DISPLAY_PAGE_NUMBER; int limit = page * DISPLAY_PAGE_NUMBER; DocumentManager docMgr = new MongoDbDocumentManager(this.getMongoDbService()); List<Document> docs = docMgr.findByForeignIdAndKeyword(String foreignId, String keyword, int skip, int limit); List<DocumentVo> docVos = new ArrayList<DocumentVo>(docs.size()); for (int i = 0; i < docs.size(); i++) { Document doc = docs.get(i); DocumentVo docVo = document2Vo(doc); docVos.add(docVo); } DocumentsVo docsVo = new DocumentsVo(); docsVo.setCurrentPage(page); docsVo.setTotalCount(docMgr.countByForeignIdAndKeyword(String foreignId, String keyword)); docsVo.setTotalPage(Math.round( docsVo.getTotalCount() / DISPLAY_PAGE_NUMBER)); docsVo.setKeyword(keyword); docsVo.setDocs(docVos); return docsVo; }*/ /*@GET @Path("/{owner}/{page}") @Produces("application/json") public List<DocumentsVo> findByOwnerAndForeignId( @QueryParam("keyword") String keyword, @QueryParam("foreignId") String foreignId, @PathParam("owner") String owner, @PathParam("page") int page) throws DocumentException { int skip = (page - 1) * DISPLAY_PAGE_NUMBER; int limit = page * DISPLAY_PAGE_NUMBER; DocumentManager docMgr = new MongoDbDocumentManager(this.getMongoDbService()); List<Document> list = null; int documentNumber = 0; String[] key = keyword.split(","); logger.debug("findByOwnerAndForeignId skip={},keyword={}", skip, keyword); logger.debug("foreignId = {} ,owner = {}", foreignId, owner); // 有关键字的查询 if (StringUtils.isNotBlank(keyword)) { logger .debug("findByOwnerAndForeignId run findByKeyword have keyword"); list = docMgr.findByKeyword(owner, key, foreignId, skip, DISPLAY_PAGE_NUMBER); documentNumber = docMgr.findNumber(owner, foreignId, key); } else { logger .debug("findByOwnerAndForeignId run findByKeyword not keyword"); list = docMgr.findByKeyword(owner, foreignId, skip, DISPLAY_PAGE_NUMBER); documentNumber = docMgr.findOwnerNumber(owner, foreignId); } List<DocumentsVo> documentList = new ArrayList<DocumentsVo>(); documentList = this.getDocumentListVo(list, documentNumber, page); logger .debug("++++++++++++ documentList size = {}", documentList .size()); return documentList; }*/ /*@GET @Path("/{id}") @Produces("application/json") public Document findById(@PathParam("id") String id) throws DocumentException { DocumentManager documentManager = new MongoDbDocumentManager(this.getMongoDbService()); Document document = documentManager.findById(id); return document; } @PUT @Path("/") @Produces("application/json") public void editDocument(@FormParam("") Document document) throws UnknownHostException, DocumentException { String currentUser = this.getSecurityService().getCurrentUser(); document.setLastModifier(currentUser); document.setLastModifiedTime(new Date()); DocumentManager documentManager = new MongoDbDocumentManager(this.getMongoDbService()); documentManager.updateDocument(document); } // 如果没有ID给出提示 @DELETE @Path("/allRemove") @Produces("application/json") public void allRemove(@Parameter(name = "allId") String allId) throws DocumentException, UnknownHostException { DocumentManager documentManager = new MongoDbDocumentManager(); String[] id = allId.split(","); logger.debug(" allRemove id= {},idsize={}", id, id.length); documentManager.allremoveById(id); } private List<DocumentsVo> getDocumentListVo(List<Document> list, int documentNumber, int page) { List<DocumentsVo> documentListVo = new ArrayList<DocumentsVo>( list.size()); for (int i = 0; i < list.size(); i++) { DocumentsVo docListVo = new DocumentsVo(); Document document = list.get(i); docListVo.setId(document.getId()); docListVo.setName(document.getName()); docListVo.setDescription(document.getDescription()); docListVo.setCreator(document.getCreator()); docListVo.setCreatedTime(document.getCreatedTime()); docListVo.setLastModifier(document.getLastModifier()); docListVo.setLastModifiedTime(document.getLastModifiedTime()); docListVo.setForeignId(document.getForeignId()); docListVo.setOwner(document.getOwner()); docListVo.setFileSize(document.getFileSize()); docListVo.setFileType(document.getFileType()); docListVo.setKeyword(document.getKeyword()); docListVo.setContentType(document.getContentType()); docListVo.setSubType(document.getSubType()); docListVo.setType(document.getType()); docListVo.setCurrentlyPage(page); docListVo.setDocumentNumber(documentNumber); docListVo.setWeight(document.getWeight()); String deleteUrl = "/rest/docs/" + document.getId(); docListVo.setDeleteUrl(deleteUrl); String downloadUrl = "/rest/docs/" + document.getId() + "/download/" + document.getName(); docListVo.setDownloadUrl(downloadUrl); String viewUrl = "/rest/docs/" + document.getId() + "/view/" + document.getName() + ""; docListVo.setViewUrl(viewUrl); String viewByIdUrl = "/rest/docs/" + document.getId() + ""; docListVo.setViewByIdUrl(viewByIdUrl); float length = document.getFileSize(); if (length / KB >= 1 && length / KB < 1024) { docListVo.setSize(String.format("%.2f", length / KB) + "KB"); } else if (length / MB >= 1 && length / MB < 1024) { docListVo.setSize(String.format("%.2f", length / MB) + "MB"); } else if (length / GB >= 1) { docListVo.setSize(String.format("%.2f", length / GB) + "GB"); } else { docListVo.setSize(length + "byte"); } documentListVo.add(docListVo); } return documentListVo; }*/ }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/ws/DocumentService.java
Java
asf20
13,560
package com.zyeeda.framework.aop; import javax.servlet.ServletContext; import javax.transaction.Status; import javax.transaction.UserTransaction; import org.apache.tapestry5.ioc.Registry; import org.aspectj.lang.annotation.SuppressAjWarnings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.FrameworkConstants; import com.zyeeda.framework.aop.Transactional; import com.zyeeda.framework.transaction.TransactionService; import com.zyeeda.framework.transaction.internal.BitronixTransactionServiceProvider; import com.zyeeda.framework.utils.IocUtils; public aspect TransactionManagementAspect { private final static Logger logger = LoggerFactory.getLogger(TransactionManagementAspect.class); pointcut txEnabledMethod(ServletContext ctx) : execution(@Transactional public * *.*(ServletContext, ..)) && args(ctx); @SuppressAjWarnings("adviceDidNotMatch") Object around(ServletContext ctx) : txEnabledMethod(ctx) { Registry reg = (Registry) ctx.getAttribute(FrameworkConstants.SERVICE_REGISTRY); TransactionService txSvc = reg.getService(IocUtils.getServiceId(BitronixTransactionServiceProvider.class), TransactionService.class); UserTransaction utx = null; try { utx = txSvc.getTransaction(); if (utx.getStatus() == Status.STATUS_ACTIVE) { logger.debug("transaction is active"); return proceed(ctx); } logger.debug("trying to begin transaction"); utx.begin(); logger.debug("transaction begin"); Object retValue = proceed(ctx); utx.commit(); logger.debug("transaction commit"); return retValue; } catch (Throwable t) { if (utx != null) { try { utx.rollback(); } catch (Throwable t2) { logger.error("Transaction roll back failed.", t2); } logger.debug("transaction rollback"); } throw new RuntimeException(t); } } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/aop/TransactionManagementAspect.aj
AspectJ
asf20
1,855
package com.zyeeda.framework.aop; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Transactional { }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/aop/Transactional.java
Java
asf20
310
/* * Copyright 2010 Zyeeda Co. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zyeeda.framework.service; /** * Service interface. * * @author Rui Tang * @version %I%, %G% * @since 1.0 */ public interface Service { void start() throws Exception; void stop() throws Exception; ServiceState getState(); void changeState(ServiceState state); }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/service/Service.java
Java
asf20
953
/* * Copyright 2010 Zyeeda Co. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zyeeda.framework.service; /** * Service state. * * @author Rui Tang * @version %I%, %G% * @since 1.0 */ public enum ServiceState { NEW(1000), READY(200), STARTING(300), RUNNING(4000), STOPPING(5000), STOPPED(6000); private int statusCode; private ServiceState(int statusCode) { this.statusCode = statusCode; } public int getStatusCode() { return this.statusCode; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/service/ServiceState.java
Java
asf20
1,091
/* * Copyright 2010 Zyeeda Co. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zyeeda.framework.service; import org.apache.commons.configuration.Configuration; import org.apache.tapestry5.ioc.Resource; import org.apache.tapestry5.ioc.annotations.ServiceId; import org.apache.tapestry5.ioc.internal.util.ClasspathResource; import org.apache.tapestry5.ioc.services.RegistryShutdownHub; import org.apache.tapestry5.ioc.services.RegistryShutdownListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.config.ConfigurationService; /** * Abstract service. * * @author Rui Tang * @version %I%, %G% * @since 1.0 */ public abstract class AbstractService implements Service, RegistryShutdownListener { private final static Logger logger = LoggerFactory.getLogger(AbstractService.class); private ServiceState state = ServiceState.NEW; public AbstractService(RegistryShutdownHub shutdownHub) { shutdownHub.addRegistryShutdownListener(this); } @Override public ServiceState getState() { return this.state; } @Override public void changeState(ServiceState state) { this.state = state; } @Override public void start() throws Exception { } @Override public void stop() throws Exception { } @Override public void registryDidShutdown() { try { logger.info("{} stopping", this.getClass().getSimpleName()); this.stop(); logger.info("{} stopped", this.getClass().getSimpleName()); } catch (Exception e) { throw new RuntimeException(e); } } protected String getServiceId() { return this.getClass().getAnnotation(ServiceId.class).value(); } protected Configuration getConfiguration(ConfigurationService configSvc) { Resource configFile = new ClasspathResource(String.format("%s.properties", this.getServiceId())); Configuration config = configSvc.getConfiguration(configFile); return config; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/service/AbstractService.java
Java
asf20
2,576
package com.zyeeda.framework.managers; import com.googlecode.genericdao.dao.jpa.GenericDAO; import com.zyeeda.framework.entities.Dictionary; public interface DictionaryManager extends GenericDAO<Dictionary, String> { public Dictionary getDictionaryByTypeAndName(String name); }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/DictionaryManager.java
Java
asf20
295
package com.zyeeda.framework.managers; public class DocumentException extends Exception { private static final long serialVersionUID = -7159687624749433311L; public DocumentException(String message) { super(message); } public DocumentException(Throwable t) { super(t); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/DocumentException.java
Java
asf20
304
package com.zyeeda.framework.managers; import java.util.List; import com.zyeeda.framework.entities.Department; public interface DepartmentManager { public void persist(Department dept) throws UserPersistException; public Department findById(String id) throws UserPersistException; public void remove(String id) throws UserPersistException; public void update(Department dept) throws UserPersistException; public List<Department> getChildrenById(String id) throws UserPersistException; public List<Department> getRootAndSecondLevelDepartment() throws UserPersistException; public List<Department> getDepartmentListByUserId(String userId) throws UserPersistException; public List<Department> search(String condition) throws UserPersistException; public List<Department> findByName(String name) throws UserPersistException; }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/DepartmentManager.java
Java
asf20
878
package com.zyeeda.framework.managers; public class UserPersistException extends Exception { private static final long serialVersionUID = 8402227533625324307L; public UserPersistException() {} public UserPersistException(String message) { super(message); } public UserPersistException(Throwable t) { super(t); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/UserPersistException.java
Java
asf20
351
package com.zyeeda.framework.managers; import java.util.List; import com.googlecode.genericdao.dao.jpa.GenericDAO; import com.zyeeda.framework.entities.ActionHistory; public interface ActionHistoryManager extends GenericDAO<ActionHistory, String> { public ActionHistory findAlive(Long processInsId); public ActionHistory findAlive(Long processInsId, String nodeInsId); public List<ActionHistory> findListByProcessId(Long parseLong); public List<ActionHistory> findListByProcessCreator(String name); }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/ActionHistoryManager.java
Java
asf20
537
package com.zyeeda.framework.managers; import com.googlecode.genericdao.dao.jpa.GenericDAO; import com.zyeeda.framework.entities.ProcessHistory; public interface ProcessHistoryManager extends GenericDAO<ProcessHistory, String> { public ProcessHistory findByProcessInstanceId(Long processInstanceId); }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/ProcessHistoryManager.java
Java
asf20
318
package com.zyeeda.framework.managers; import java.io.IOException; import java.util.List; import javax.xml.xpath.XPathExpressionException; import com.zyeeda.framework.viewmodels.PermissionVo; public interface PermissionManager { public List<PermissionVo> findSubPermissionById(String id, String authXml) throws XPathExpressionException, IOException; public PermissionVo getPermissionByPath(String auth, String authXml) throws XPathExpressionException, IOException; public PermissionVo getParentPermissionByPath(String auth) throws XPathExpressionException, IOException; public String getParentPermissionListAuthByList(List<String> authList, String authXml) throws XPathExpressionException, IOException; public List<PermissionVo> getPermissionToTree(String id) throws XPathExpressionException, IOException ; // public PermissionVo getRaomPermissionByPath(String auth) // throws XPathExpressionException, IOException; // public List<PermissionVo> findSubRoamPermissionById(String id) // throws XPathExpressionException, IOException; }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/PermissionManager.java
Java
asf20
1,089
package com.zyeeda.framework.managers.internal; import com.googlecode.genericdao.search.Search; import com.zyeeda.framework.entities.ProcessHistory; import com.zyeeda.framework.managers.ProcessHistoryManager; import com.zyeeda.framework.managers.base.DomainEntityManager; import com.zyeeda.framework.persistence.PersistenceService; public class DefaultProcessHistoryManager extends DomainEntityManager<ProcessHistory, String> implements ProcessHistoryManager { public DefaultProcessHistoryManager(PersistenceService persistenceSvc) { super(persistenceSvc); } public ProcessHistory findByProcessInstanceId(Long processInstanceId) { Search search = new Search(); search.addFilterEqual("processInstanceId", processInstanceId); return this.searchUnique(search); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/DefaultProcessHistoryManager.java
Java
asf20
804
// Copyright 2011, Zyeeda, Inc. All Rights Reserved. // Confidential and Proprietary Information of Zyeeda, Inc. package com.zyeeda.framework.managers.internal; import java.util.ArrayList; import java.util.List; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapContext; import org.apache.shiro.realm.ldap.LdapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.entities.Account; import com.zyeeda.framework.helpers.AccountHelper; import com.zyeeda.framework.ldap.LdapService; import com.zyeeda.framework.ldap.LdapTemplate; import com.zyeeda.framework.ldap.SearchControlsFactory; import com.zyeeda.framework.managers.AccountManager; import com.zyeeda.framework.managers.UserPersistException; /** * system account manager implement * * @author Qi Zhao * @date 2011-06-15 * * @LastChanged * @LastChangedBy $LastChangedBy: $ * @LastChangedDate $LastChangedDate: $ * @LastChangedRevision $LastChangedRevision: $ */ public class SystemAccountManager implements AccountManager { private static final Logger logger = LoggerFactory.getLogger(SystemAccountManager.class); public static final String DEFAULT_DN_PREFIX = ",dc=ehv,dc=csg,dc=cn"; private LdapService ldapSvc; public SystemAccountManager(LdapService ldapSvc) { this.ldapSvc = ldapSvc; } public List<Account> findByUserId(String userId) throws UserPersistException { String fullDN = userId; //+ DEFAULT_DN_PREFIX; String filter = "(systemName=*)"; logger.debug("full dn = {}", fullDN); logger.debug("filter = {}", filter); return this.getAccountsByDNAndFilter(fullDN, filter); } public Account findByUserIdAndSystemName(String userId, String systemName) throws UserPersistException { String fullDN = userId;// + DEFAULT_DN_PREFIX; String filter = "(systemName=" + systemName + ")"; logger.debug("find by user id and sys name's full dn = {}", fullDN); logger.debug("filter = {}", filter); List<Account> accounts = this.getAccountsByDNAndFilter(fullDN, filter); if (accounts != null && accounts.size() > 0) { return accounts.get(0); } return null; } // public void update(Account account) throws UserPersistException { // LdapContext context = null; // try { // context = this.getLdapContext(); // Attributes attributes = AccountHelper.convertAccountToAttributes(account); // String dn = "username=" + account.getUserName() + "," + account.getUserFullPath(); // NamingEnumeration<SearchResult> ne = context.search(account.getUserFullPath(), "username=" + account.getUserName(), // SearchControlsFactory.getSearchControls(SearchControls.SUBTREE_SCOPE)); // if (ne.hasMore()) { // context.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attributes); // } else { // context.bind(dn, null, attributes); // } // } catch (NamingException e) { // throw new UserPersistException(e); // } // } public void update(Account account) throws UserPersistException { Attributes attributes = AccountHelper.convertAccountToAttributes(account); try { LdapTemplate ldapTemplate = this.getLdapTemplate(); ldapTemplate.bind("uid=" + account.getUserName() + "," + account.getUserFullPath(), attributes); } catch (NamingException e) { throw new UserPersistException(e); } } private LdapContext getLdapContext() throws NamingException { return this.ldapSvc.getLdapContext(); } private List<Account> getAccountsByDNAndFilter(String dn, String filter) throws UserPersistException { LdapContext context = null; List<Account> accounts = new ArrayList<Account>(); try { context = this.getLdapContext(); // dn += ",dc=ehv,dc=csg,dc=cn"; NamingEnumeration<SearchResult> nes = context.search(dn, filter, SearchControlsFactory .getSearchControls(SearchControls.SUBTREE_SCOPE)); if (nes == null) { return accounts; } accounts = AccountHelper .convertNameingEnumeractionToAccountList(nes); return accounts; } catch (NamingException e) { throw new UserPersistException(e); } finally { LdapUtils.closeContext(context); } } /* * Delete a context by systemName */ public void remove(String systemName) throws UserPersistException { try { LdapTemplate ldapTemplate = this.getLdapTemplate(); ldapTemplate.unbind(systemName, false); } catch (NamingException e) { throw new UserPersistException(e); } } private LdapTemplate getLdapTemplate() throws NamingException { return new LdapTemplate(this.ldapSvc.getLdapContext()); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/SystemAccountManager.java
Java
asf20
4,700
package com.zyeeda.framework.managers.internal; import com.googlecode.genericdao.search.Search; import com.zyeeda.framework.managers.DictionaryManager; import com.zyeeda.framework.entities.Dictionary; import com.zyeeda.framework.managers.base.DomainEntityManager; import com.zyeeda.framework.persistence.PersistenceService; public class DefaultDictionaryManager extends DomainEntityManager<Dictionary, String> implements DictionaryManager { public DefaultDictionaryManager(PersistenceService persistenceSvc) { super(persistenceSvc); } public Dictionary getDictionaryByTypeAndName(String name){ DictionaryManager dictMgr = new DefaultDictionaryManager(this.getPersistenceService()); Search search = new Search(); search.addFilterEqual("type", "defectLevel"); search.addFilterEqual("name", name); return dictMgr.searchUnique(search); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/DefaultDictionaryManager.java
Java
asf20
886
package com.zyeeda.framework.managers.internal; import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; import org.apache.commons.lang.StringUtils; import com.zyeeda.framework.entities.User; import com.zyeeda.framework.ldap.LdapService; import com.zyeeda.framework.ldap.LdapTemplate; import com.zyeeda.framework.ldap.SearchControlsFactory; import com.zyeeda.framework.managers.UserManager; import com.zyeeda.framework.managers.UserPersistException; import com.zyeeda.framework.utils.DatetimeUtils; public class LdapUserManager implements UserManager { private static final String LDAP_DEFAULT_PASSWORD = "123456"; private LdapService ldapSvc; public LdapUserManager(LdapService ldapSvc) { this.ldapSvc = ldapSvc; } @Override public void persist(User user) throws UserPersistException { try { LdapTemplate ldapTemplate = this.getLdapTemplate(); Attributes attrs = LdapUserManager.unmarshal(user); ldapTemplate.bind(user.getDeptFullPath(), attrs); } catch (NamingException e) { throw new UserPersistException(e); } catch (UnsupportedEncodingException e) { throw new UserPersistException(e); } } @Override public void remove(String id) throws UserPersistException { try { LdapTemplate ldapTemplate = this.getLdapTemplate(); ldapTemplate.unbind(id, true); } catch (NamingException e) { throw new UserPersistException(e); } } @Override public void update(User user) throws UserPersistException { try { String dn = user.getDeptFullPath(); LdapTemplate ldapTemplate = this.getLdapTemplate(); Attributes attrs = LdapUserManager.unmarshal(user); ldapTemplate.modifyAttributes(dn, attrs); } catch (NamingException e) { throw new UserPersistException(e); } catch (UnsupportedEncodingException e) { throw new UserPersistException(e); } } @Override public User findById(String id) throws UserPersistException { try { LdapTemplate ldapTemplate = this.getLdapTemplate(); Attributes attrs = ldapTemplate.findByDn(id); User user = LdapUserManager.marshal(attrs); return user; } catch (NamingException e) { throw new UserPersistException(e); } catch (ParseException e) { throw new UserPersistException(e); } } public Integer getChildrenCountById(String id, String filter) throws UserPersistException { try { LdapTemplate ldapTemplate = this.getLdapTemplate(); SearchControls sc = SearchControlsFactory.getSearchControls( SearchControls.ONELEVEL_SCOPE); List<Attributes> attrsList = ldapTemplate.getResultList(id, filter, sc); return attrsList.size(); } catch (NamingException e) { throw new UserPersistException(e); } } @Override public List<User> findByDepartmentId(String id) throws UserPersistException { SearchControls sc = SearchControlsFactory.getDefaultSearchControls(); List<User> userList = this.findByDepartmentId(id, sc); return userList; } @Override public List<User> findByDepartmentId(String id, SearchControls sc) throws UserPersistException { List<User> userList = null; try { LdapTemplate ldapTemplate = this.getLdapTemplate(); if ("root".equals(id)) { id = ""; } List<Attributes> attrsList = ldapTemplate.getResultList(id, "(uid=*)", sc); userList = new ArrayList<User>(attrsList.size()); for (Attributes attrs : attrsList) { User user = LdapUserManager.marshal(attrs); if (StringUtils.isNotBlank(id)) { user.setDeptFullPath("uid=" + user.getId() + "," + id); } else { user.setDeptFullPath("uid=" + user.getId()); } userList.add(user); } return userList; } catch (NamingException e) { throw new UserPersistException(e); } catch (ParseException e) { throw new UserPersistException(e); } } @Override public List<User> findByName(String name) throws UserPersistException { SearchControls sc = SearchControlsFactory.getSearchControls( SearchControls.ONELEVEL_SCOPE); List<User> userList = this.findByName(name, sc); return userList; } @Override public List<User> findByName(String name, SearchControls sc) throws UserPersistException { List<User> userList = null; try { LdapTemplate ldapTemplate = this.getLdapTemplate(); List<Attributes> attrsList = ldapTemplate.getResultList("", "(uid=" + name + ")", sc); userList = new ArrayList<User>(); for (Attributes attrs : attrsList) { User user = LdapUserManager.marshal(attrs); userList.add(user); } return userList; } catch (NamingException e) { throw new UserPersistException(e); } catch (ParseException e) { throw new UserPersistException(e); } } public void updatePassword(String id, String password) throws UserPersistException { try { LdapTemplate ldapTemplate = this.getLdapTemplate(); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", password)); ldapTemplate.modifyAttributes(id, mods); } catch (NamingException e) { throw new UserPersistException(e); } } @Override public void enable(String... ids) throws UserPersistException { try { this.setVisible(true, ids); } catch (NamingException e) { throw new UserPersistException(e); } catch (ParseException e) { throw new UserPersistException(e); } } @Override public void disable(String... ids) throws UserPersistException { try { this.setVisible(false, ids); } catch (NamingException e) { throw new UserPersistException(e); } catch (ParseException e) { throw new UserPersistException(e); } } private void setVisible(Boolean visible, String... ids) throws NamingException, ParseException { ModificationItem[] mods = new ModificationItem[1]; LdapTemplate ldapTemplate = this.getLdapTemplate(); for (String dn : ids) { mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("status", visible.toString())); ldapTemplate.modifyAttributes(dn, mods); } } // @Override // public List<User> getUserListByDepartmentId(String id, String type) // throws NamingException { // LdapContext ctx = null; // NamingEnumeration<SearchResult> ne = null; // List<User> userList = null; // logger.debug("the value of the id is = {} ", id); // // try { // ctx = this.ldapSvc.getLdapContext(); // ne = ctx.search(id, "(uid=*)", this.getOneLevelScopeSearchControls()); // // SearchResult entry = null; // userList = new ArrayList<User>(); // for (; ne.hasMore();) { // entry = ne.next(); // User user = new User(); // Attributes attr = entry.getAttributes(); // // user.setUsername((String) attr.get("cn").get()); // user.setId((String) attr.get("uid").get()); // user.setPassword(new String((byte[]) attr.get("userPassword").get())); // user.setDeptFullPath(id); // //// UserVo userVo = this.fillUserPropertiesToVo(user); //// userVo.setType(type); // userList.add(user); // } // return userList; // } finally { // LdapUtils.closeEnumeration(ne); // LdapUtils.closeContext(ctx); // } // } //add for upload photo // private static byte[] getBytesFromFile(File file) throws IOException { // InputStream is = new FileInputStream(file); // long length = file.length(); // if (length > Integer.MAX_VALUE) { // throw new IOException("File is to large "+file.getName()); // } // byte[] bytes = new byte[(int)length]; // int offset = 0; // int numRead = 0; // // while (offset < bytes.length // && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { // offset += numRead; // } // if (offset < bytes.length) { // throw new IOException("Could not completely read file "+file.getName()); // } // is.close(); // return bytes; // } public static Attributes unmarshal(User user) throws UnsupportedEncodingException { Attributes attrs = new BasicAttributes(); attrs.put("objectClass", "top"); attrs.put("objectClass", "person"); attrs.put("objectClass", "organizationalPerson"); attrs.put("objectClass", "inetOrgPerson"); attrs.put("objectClass", "employee"); attrs.put("cn", user.getUsername()); attrs.put("sn", user.getUsername()); attrs.put("uid", user.getId()); if (StringUtils.isNotBlank(user.getPassword())) { attrs.put("userPassword", user.getPassword()); } else { attrs.put("userPassword", LDAP_DEFAULT_PASSWORD); } if (StringUtils.isNotBlank(user.getGender())) { attrs.put("gender", user.getGender()); } if (StringUtils.isNotBlank(user.getPosition())) { attrs.put("position", user.getPosition()); } if (StringUtils.isNotBlank(user.getDegree())) { attrs.put("degree", user.getDegree()); } if (StringUtils.isNotBlank(user.getEmail())) { attrs.put("mail", user.getEmail()); } if (StringUtils.isNotBlank(user.getMobile())) { attrs.put("mobile", user.getMobile()); } if (user.getBirthday() != null) { attrs.put("birthday", DatetimeUtils.formatDate(user.getBirthday())); } if (user.getDateOfWork() != null) { attrs.put("dateOfWork", DatetimeUtils.formatDate(user.getDateOfWork())); } if (user.getStatus() != null) { attrs.put("status", user.getStatus().toString()); } if (user.getPostStatus() != null) { attrs.put("postStatus", user.getPostStatus().toString()); } if (user.getDepartmentName() != null) { attrs.put("deptName", user.getDepartmentName()); } if (user.getDeptFullPath() != null) { attrs.put("deptFullPath", user.getDeptFullPath()); } return attrs; } public static User marshal(Attributes attrs) throws NamingException, ParseException { User user = new User(); user.setUsername((String) attrs.get("sn").get()); user.setId((String) attrs.get("uid").get()); if (attrs.get("userPassword") != null) { user.setPassword(new String((byte[]) attrs.get("userPassword").get())); } if (attrs.get("gender") != null) { user.setGender((String) attrs.get("gender").get()); } if (attrs.get("degree") != null) { user.setDegree((String) attrs.get("degree").get()); } if (attrs.get("position") != null) { user.setPosition((String) attrs.get("position").get()); } if (attrs.get("mail") != null) { user.setEmail((String) attrs.get("mail").get()); } if (attrs.get("mobile") != null) { user.setMobile((String) attrs.get("mobile").get()); } if (attrs.get("birthday") != null) { user.setBirthday(DatetimeUtils.parseDate(attrs.get("birthday").get().toString())); } if (attrs.get("dateOfWork") != null) { user.setDateOfWork(DatetimeUtils.parseDate(attrs.get("dateOfWork").get().toString())); } if (attrs.get("status") != null) { user.setStatus(new Boolean(attrs.get("status").get().toString())); } if (attrs.get("postStatus") != null) { user.setPostStatus(new Boolean(attrs.get("postStatus").get().toString())); } if (attrs.get("deptName") != null) { user.setDepartmentName(attrs.get("deptName").get().toString()); } if (attrs.get("deptFullPath") != null) { user.setDeptFullPath(attrs.get("deptFullPath").get().toString()); } return user; } /* private LdapTemplate getLdapTemplate(LinkedHashMap<String, Boolean> orderBy) throws NamingException, IOException { LdapContext ctx = this.ldapSvc.getLdapContext(); if (orderBy != null) { for (String key : orderBy.keySet()) { ctx.setRequestControls(new Control[] { new SortControl(key, orderBy.get(key)) }); } } return new LdapTemplate(ctx); } */ private LdapTemplate getLdapTemplate() throws NamingException { return new LdapTemplate(this.ldapSvc.getLdapContext()); } @Override public List<User> search(String condition) throws UserPersistException { List<User> userList = null; try { LdapTemplate ldapTemplate = this.getLdapTemplate(); String filter = "(|(uid=*" + condition + "*)(cn=*" + condition + "*))"; if ("*".equals(condition)) { filter = "(|(uid=*)(cn=*))"; } List<Attributes> attrsList = ldapTemplate.getResultList("o=广州局", filter, SearchControlsFactory.getSearchControls(SearchControls.SUBTREE_SCOPE)); userList = new ArrayList<User>(); for (Attributes attrs : attrsList) { User user = LdapUserManager.marshal(attrs); userList.add(user); } return userList; } catch (NamingException e) { throw new UserPersistException(e); } catch (ParseException e) { throw new UserPersistException(e); } } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/LdapUserManager.java
Java
asf20
13,601
package com.zyeeda.framework.managers.internal; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttributes; import javax.naming.directory.SearchControls; import org.apache.commons.lang.StringUtils; import com.zyeeda.framework.entities.Department; import com.zyeeda.framework.entities.User; import com.zyeeda.framework.ldap.LdapService; import com.zyeeda.framework.ldap.LdapTemplate; import com.zyeeda.framework.ldap.SearchControlsFactory; import com.zyeeda.framework.managers.DepartmentManager; import com.zyeeda.framework.managers.UserPersistException; public class LdapDepartmentManager implements DepartmentManager { private LdapService ldapSvc; public LdapDepartmentManager(LdapService ldapSvc) { this.ldapSvc = ldapSvc; } public void persist(Department dept) throws UserPersistException { try { LdapTemplate ldapTemplate = this.getLdapTemplate(); Attributes attrs = unmarshal(dept); String dn = dept.getId(); ldapTemplate.bind(dn, attrs); } catch (NamingException e) { throw new UserPersistException(e); } } @Override public void remove(String dn) throws UserPersistException{ try { LdapTemplate ldapTemplate = this.getLdapTemplate(); ldapTemplate.unbind(dn, true); } catch (NamingException e) { throw new UserPersistException(e); } } @Override public void update(Department dept) throws UserPersistException { String dn = dept.getId(); Attributes attrs = unmarshal(dept); try { LdapTemplate ldapTemplate = this.getLdapTemplate(); ldapTemplate.modifyAttributes(dn, attrs); } catch (NamingException e) { throw new UserPersistException(e); } } public Department findById(String id) throws UserPersistException { try { LdapTemplate ldapTemplate = this.getLdapTemplate(); Attributes attrs = ldapTemplate.findByDn(id); Department dept = LdapDepartmentManager.marshal(attrs); dept.setId(id); dept.setDeptFullPath(id); dept.setParent(id); return dept; } catch (NamingException e) { throw new UserPersistException(e); } } @Override public List<Department> getChildrenById(String dn) throws UserPersistException { List<Attributes> attrList = null; List<Department> deptList = null; try { LdapTemplate ldapTemplate = this.getLdapTemplate(); String filter = ""; if ("root".equals(dn)) { dn = ""; filter = "o=*"; } else { filter = "ou=*"; } attrList = ldapTemplate.getResultList(dn, filter, SearchControlsFactory.getSearchControls(SearchControls.ONELEVEL_SCOPE)); deptList = new ArrayList<Department>(attrList.size()); for (Attributes attr : attrList) { Department department = marshal(attr); department.setParent(dn); department.setDeptFullPath("ou=" + department.getId() + "," + dn); deptList.add(department); } return deptList; } catch (NamingException e) { throw new UserPersistException(e); } } @Override public List<Department> findByName(String name) throws UserPersistException { return this.findByName("", name); } public Integer getChildrenCountById(String dn, String filter) throws UserPersistException { List<Attributes> attrList = null; try { LdapTemplate ldapTemplate = this.getLdapTemplate(); attrList = ldapTemplate.getResultList(dn, filter, SearchControlsFactory.getSearchControls(SearchControls.ONELEVEL_SCOPE)); return attrList.size(); } catch (NamingException e) { throw new UserPersistException(e); } } public List<Department> findByName(String parent, String name) throws UserPersistException { List<Department> deptList = null; try { LdapTemplate ldapTemplate = this.getLdapTemplate(); List<Attributes> attrsList = ldapTemplate.getResultList(parent, "(ou=" + name + ")", SearchControlsFactory.getSearchControls(SearchControls.SUBTREE_SCOPE)); deptList = new ArrayList<Department>(attrsList.size()); for (Attributes attrs : attrsList) { Department dept = LdapDepartmentManager.marshal(attrs); deptList.add(dept); } return deptList; } catch (NamingException e) { throw new UserPersistException(e); } } private static Attributes unmarshal(Department dept) { Attributes attrs = new BasicAttributes(); attrs.put("objectClass", "top"); attrs.put("objectClass", "organizationalUnit"); if (StringUtils.isNotBlank(dept.getName())) { attrs.put("ou", dept.getName()); } if (StringUtils.isNotBlank(dept.getDescription())) { attrs.put("description", dept.getDescription()); } return attrs; } private static Department marshal(Attributes attrs) throws NamingException { Department dept = new Department(); if (attrs.get("ou") != null) { dept.setId((String) attrs.get("ou").get()); dept.setName((String) attrs.get("ou").get()); } else if (attrs.get("o") != null) { dept.setId((String) attrs.get("o").get()); dept.setName((String) attrs.get("o").get()); } if (attrs.get("description") != null) { dept.setDescription((String) attrs.get("description").get()); } return dept; } private LdapTemplate getLdapTemplate() throws NamingException { return new LdapTemplate(this.ldapSvc.getLdapContext()); } @Override public List<Department> getRootAndSecondLevelDepartment() throws UserPersistException { List<Department> deptList = null; try { LdapTemplate ldapTemplate = this.getLdapTemplate(); List<Attributes> attrsList = ldapTemplate.getResultList("", "(o=广州局)", SearchControlsFactory.getDefaultSearchControls()); attrsList.addAll(ldapTemplate.getResultList("o=广州局", "(ou=*)", SearchControlsFactory.getDefaultSearchControls())); deptList = new ArrayList<Department>(attrsList.size()); for (Attributes attrs : attrsList) { Department dept = LdapDepartmentManager.marshal(attrs); deptList.add(dept); } return deptList; } catch (NamingException e) { throw new UserPersistException(e); } } @Override public List<Department> getDepartmentListByUserId(String userId) throws UserPersistException { List<Department> deptList = null; try { LdapTemplate ldapTemplate = this.getLdapTemplate(); List<Attributes> attrsList = ldapTemplate.getResultList(userId, "(|(o=*)(ou=*))", SearchControlsFactory.getDefaultSearchControls()); deptList = new ArrayList<Department>(attrsList.size()); for (Attributes attrs : attrsList) { Department dept = LdapDepartmentManager.marshal(attrs); deptList.add(dept); } return deptList; } catch (NamingException e) { throw new UserPersistException(e); } } @Override public List<Department> search(String condition) throws UserPersistException { List<Department> deptList = null; try { LdapTemplate ldapTemplate = this.getLdapTemplate(); List<Attributes> attrList = ldapTemplate.getResultList("", "uid=" + condition, SearchControlsFactory.getSearchControls(SearchControls.SUBTREE_SCOPE)); List<User> userList = new ArrayList<User>(attrList.size()); for (Attributes attrs : attrList) { User user = LdapUserManager.marshal(attrs); userList.add(user); } if (userList != null && userList.size() > 0) { } String filter = "(|(o=*" + condition + "*)(ou=*" + condition + "*" + "))"; if ("*".equals(condition) || StringUtils.isBlank(condition)) { filter = "(|(o=*)(ou=*))"; } List<Attributes> attrsList = ldapTemplate.getResultList("", filter, SearchControlsFactory.getSearchControls(SearchControls.SUBTREE_SCOPE)); deptList = new ArrayList<Department>(attrsList.size()); for (Attributes attrs : attrsList) { Department dept = LdapDepartmentManager.marshal(attrs); deptList.add(dept); } return deptList; } catch (NamingException e) { throw new UserPersistException(e); } catch (ParseException e) { throw new UserPersistException(e); } } /* private LdapTemplate getLdapTemplate(LinkedHashMap<String, Boolean> orderBy) throws NamingException, IOException { LdapContext ctx = this.ldapSvc.getLdapContext(); if (orderBy != null) { for (String key : orderBy.keySet()) { ctx.setRequestControls(new Control[] { new SortControl(key, orderBy.get(key)) }); } } return new LdapTemplate(ctx); } */ }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/LdapDepartmentManager.java
Java
asf20
8,965
package com.zyeeda.framework.managers.internal; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSFile; import com.zyeeda.framework.entities.Document; public class MongoDbDocumentManagerHelper { private final static Logger logger = LoggerFactory.getLogger(MongoDbDocumentManagerHelper.class); public static GridFSFile document2GridFSFile(GridFS fs, Document document) { GridFSFile file = fs.createFile(document.getContent()); file.put("isTemp", document.isTemp()); file.put("filename", document.getName()); // 数据库自带filename file.put("description", document.getDescription()); file.put("creator", document.getCreator()); file.put("uploadDate", document.getCreatedTime()); // 数据库自带uploadDate file.put("lastModifier", document.getLastModifier()); file.put("lastModifiedTime", document.getLastModifiedTime()); file.put("foreignId", document.getForeignId()); file.put("weight", document.getWeight()); file.put("owner", document.getOwner()); file.put("keyword", document.getKeyword()); file.put("fileType", document.getFileType()); // 数据库自带fileType file.put("contentType", document.getContentType()); // 数据库自带contentType file.put("subType", document.getSubType()); file.put("primaryType", document.getPrimaryType()); if (logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("filename = " + document.getName() + "\n"); sb.append("\tdescription = " + document.getDescription() + "\n"); sb.append("\tcreator = " + document.getCreator() + "\n"); sb.append("\tuploadDate = " + document.getCreatedTime() + "\n"); sb.append("\tlastModifier = " + document.getLastModifier() + "\n"); sb.append("\tlastModifiedTime = " + document.getLastModifiedTime() + "\n"); sb.append("\tforeignId = " + document.getForeignId() + "\n"); sb.append("\tweight = " + document.getWeight() + "\n"); sb.append("\towner = " + document.getOwner() + "\n"); sb.append("\tkeyword = " + document.getKeyword() + "\n"); sb.append("\tfileType = " + document.getFileType() + "\n"); sb.append("\tcontentType = " +document.getContentType() + "\n"); sb.append("\tprimaryType = " + document.getPrimaryType() + "\n"); sb.append("\tsubType = " + document.getSubType() + "\n"); logger.debug(sb.toString()); } return file; } public static Document gridFSDBFile2Document(GridFSDBFile file, boolean includeContent) { Document document = new Document(); document.setId(file.getId().toString()); document.setName(file.getFilename()); document.setDescription((String) file.get("description")); document.setCreator((String) file.get("creator")); document.setCreatedTime((Date) file.getUploadDate()); document.setLastModifier((String) file.get("lastModifier")); document.setLastModifiedTime((Date) file.get("lastModifiedTime")); document.setForeignId((String) file.get("foreignId")); document.setWeight((Integer) file.get("weight")); document.setOwner((String) file.get("owner")); document.setKeyword((String) file.get("keyword")); document.setFileType((String) file.get("fileType")); document.setContentType(file.getContentType()); document.setPrimaryType((String) file.get("primaryType")); document.setSubType((String) file.get("subType")); document.setFileSize(file.getLength()); if (includeContent) { document.setContent(file.getInputStream()); } return document; } public static Document gridFSDBFile2Document(GridFSDBFile file) { return gridFSDBFile2Document(file, true); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/MongoDbDocumentManagerHelper.java
Java
asf20
3,813
package com.zyeeda.framework.managers.internal; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import javax.persistence.Query; import javax.persistence.TypedQuery; import com.googlecode.genericdao.search.Search; import com.zyeeda.framework.entities.ActionHistory; import com.zyeeda.framework.managers.ActionHistoryManager; import com.zyeeda.framework.managers.base.DomainEntityManager; import com.zyeeda.framework.persistence.PersistenceService; public class DefaultActionHistoryManager extends DomainEntityManager<ActionHistory, String> implements ActionHistoryManager { public DefaultActionHistoryManager(PersistenceService persistenceSvc) { super(persistenceSvc); } public ActionHistory findAlive(Long processInsId) { Search search = new Search(); search.addFilterEqual("processInstanceId", processInsId); search.addFilterEqual("alive", true); return this.searchUnique(search); } public ActionHistory findAlive(Long processInsId, String nodeInsId) { Search search = new Search(); search.addFilterEqual("processInstanceId", processInsId); search.addFilterEqual("nodeInstanceId", nodeInsId); search.addFilterEqual("alive", true); return this.searchUnique(search); } public List<ActionHistory> findListByProcessId(Long processInsId){ Search search = new Search(); search.addFilterEqual("processInstanceId", processInsId); return this.search(search); } public List<ActionHistory> findListByProcessCreator(String name){ Search search = new Search(); search.addFilterEqual("creator", name); return this.search(search); } // public List<Long> findListByProcessCreator(String name){ // String sql = "select distinct f_process_ins_id FROM ZDA_SYS_ACTION_HISTORY where f_creator = ?"; // Query query = this.em().createNativeQuery(sql); // query.setParameter(1, name); // List<Long> longList = new ArrayList<Long>(); // List<Object[]> list = query.getResultList(); // for(int i = 0; i < list.size(); i ++) { // Object[] obj = list.get(i); // longList.add((Long)obj[0]); // } // return longList; // } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/DefaultActionHistoryManager.java
Java
asf20
2,168
package com.zyeeda.framework.managers.internal; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.xml.xpath.XPathExpressionException; import com.zyeeda.framework.managers.MenuManager; import com.zyeeda.framework.managers.PermissionManager; import com.zyeeda.framework.utils.MenuListComparator; import com.zyeeda.framework.viewmodels.MenuVo; import com.zyeeda.framework.viewmodels.PermissionVo; public class DefaultMenuManager implements MenuManager { private final static String PERMISSION_FILE = "permission.xml"; @SuppressWarnings("unchecked") public List<MenuVo> getMenuListByPermissionAuth(List<String> authList) throws XPathExpressionException, IOException { PermissionManager permissionMgr = new DefaultPermissionManager(); List<MenuVo> listMenu = new ArrayList<MenuVo>(); Map<String, MenuVo> menuMap = new LinkedHashMap<String, MenuVo>(); String root = null; for (String auth : authList) { PermissionVo childPermission = permissionMgr.getPermissionByPath(auth, PERMISSION_FILE); MenuVo childMenu = null; if (childPermission != null) { childMenu = this.convertPermission2Menu(childPermission); if (!(menuMap.containsKey(childMenu.getAuth()))) { menuMap.put(childMenu.getAuth(), childMenu); }else{ continue; } } PermissionVo parentPermission = permissionMgr.getParentPermissionByPath(auth); if (parentPermission == null) { listMenu.add(menuMap.get(childMenu.getAuth())); continue; } if (menuMap.containsKey(parentPermission.getValue())) { MenuVo menuKey = menuMap.get(parentPermission.getValue()); menuKey.getPermissionSet().add(childMenu); continue; } MenuVo parentMenu = this.convertPermission2Menu(parentPermission); parentMenu.getPermissionSet().add(childMenu); menuMap.put(parentPermission.getValue(), parentMenu); while (parentPermission != null) { parentMenu = new MenuVo(); String authKey = parentPermission.getValue(); parentPermission = permissionMgr.getParentPermissionByPath(parentPermission.getValue()); if(parentPermission != null){ parentMenu.setAuth(parentPermission.getValue()); parentMenu.setId(parentPermission.getId()); parentMenu.setName(parentPermission.getName()); parentMenu.setOrderBy(parentPermission.getOrderBy()); if (!(menuMap.containsKey(parentMenu.getAuth()))) { parentMenu.getPermissionSet().add(menuMap.get(authKey)); menuMap.put(parentMenu.getAuth(), parentMenu); } else { MenuVo menuKey = menuMap.get(parentMenu.getAuth()); menuKey.getPermissionSet().add(menuMap.get(authKey)); break; } } else { root = authKey; listMenu.add(menuMap.get(root)); } } } if(listMenu.size() > 0){ MenuListComparator comparator = new MenuListComparator(); Collections.sort(listMenu, comparator); } System.out.println("****************ssss" + listMenu.size()); return listMenu; } private MenuVo convertPermission2Menu(PermissionVo permission) { MenuVo menu = new MenuVo(); menu.setAuth(permission.getValue()); menu.setId(permission.getId()); menu.setName(permission.getName()); menu.setOrderBy(permission.getOrderBy()); return menu; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/DefaultMenuManager.java
Java
asf20
3,457
package com.zyeeda.framework.managers.internal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.TypedQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.entities.Role; import com.zyeeda.framework.managers.RoleManager; import com.zyeeda.framework.managers.base.DomainEntityManager; import com.zyeeda.framework.persistence.PersistenceService; import com.zyeeda.framework.viewmodels.RoleVo; import com.zyeeda.framework.viewmodels.UserVo; public class DefaultRoleManager extends DomainEntityManager<Role, String> implements RoleManager { private static final Logger logger = LoggerFactory.getLogger(DefaultRoleManager.class); public DefaultRoleManager(PersistenceService persistenceSvc) { super(persistenceSvc); } public Set<String> getListAuth(List<Role> roles) { Set<String> auths = new HashSet<String>(); for(Role role : roles) { auths.addAll(role.getPermissionList()); } return auths; } public List<Role> getRoleBySubject(String subject){ logger.debug("the value of the dept subject is = {} ", subject); //EntityManager session = (EntityManager)this.getPersistenceService().getCurrentSession(); TypedQuery<Role> query = this.em().createNamedQuery("getRolesBySubject", Role.class); query.setParameter("subject", subject); List<Role> roleList = query.getResultList(); return roleList; } @SuppressWarnings("unchecked") public List<Role> getRoleDistinct(String hql){ List<Role> list = new ArrayList<Role>(); TypedQuery<Role> createNativeQuery = (TypedQuery<Role>) this.em().createNativeQuery(hql); TypedQuery<Role> query = createNativeQuery; list = query.getResultList(); return list; } // public List<RoleVo> roleToVo(List<Role> listRole) { // List<RoleVo> listRoleVo = new ArrayList<RoleVo>(); // for(Role role : listRole) { // RoleVo roleVo = new RoleVo(); // if(role.getDeptepment() == null && role.getDeptepmentId() == null){ // roleVo.setCheckName(role.getName()); // roleVo.setLabel(role.getName()); // roleVo.setId(role.getId()); // roleVo.setLeaf(true); // roleVo.setType("tesk"); // roleVo.setKind("user"); // } else { // roleVo.setId(role.getDeptepmentId()); // roleVo.setCheckName(role.getDeptepment()); // roleVo.setLabel(role.getDeptepment()); // roleVo.setIo("/rest/line_location/"+role.getDeptepmentId()); // roleVo.setLeaf(false); // roleVo.setType("io"); // } // listRoleVo.add(roleVo); // } // return listRoleVo; // } // @SuppressWarnings("unchecked") // public List<Role> getRoleDistinct(String hql){ // List<Role> list = new ArrayList<Role>(); // TypedQuery<Role> createNativeQuery = (TypedQuery<Role>) this.em().createNativeQuery(hql); // TypedQuery<Role> query = createNativeQuery; // list = query.getResultList(); // return list; // } public List<RoleVo> deptToVo(List<Role> listRole) { List<RoleVo> listRoleVo = new ArrayList<RoleVo>(); for(Role role : listRole) { RoleVo roleVo = new RoleVo(); roleVo.setId(role.getDeptepmentId()); roleVo.setCheckName(role.getDeptepment()); roleVo.setLabel(role.getDeptepment()); roleVo.setIo("/rest/dept/"+role.getDeptepmentId()); roleVo.setLeaf(false); roleVo.setKind("role"); roleVo.setType("io"); listRoleVo.add(roleVo); } return listRoleVo; } public List<RoleVo> roleToVo(List<Role> listRole) { List<RoleVo> listRoleVo = new ArrayList<RoleVo>(); for(Role role : listRole) { RoleVo roleVo = new RoleVo(); roleVo.setCheckName(role.getName()); roleVo.setLabel(role.getName()); roleVo.setId(role.getId()); roleVo.setLeaf(false); roleVo.setType("io"); roleVo.setKind("role"); roleVo.setIo("/rest/roles/depts/" + role.getId()); listRoleVo.add(roleVo); } return listRoleVo; } public List<UserVo> getUserVoByRole(Role role) { Set<String> user = role.getSubjects(); List<UserVo> list = new ArrayList<UserVo>(); for(String userName:user) { UserVo userVo = new UserVo(); userVo.setCheckName(userName); userVo.setLabel(userName); userVo.setType("node"); userVo.setId(userName); userVo.setKind("user"); userVo.setLeaf(true); list.add(userVo); } return list; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/DefaultRoleManager.java
Java
asf20
4,421
package com.zyeeda.framework.managers.internal; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import com.zyeeda.framework.managers.PermissionManager; import com.zyeeda.framework.viewmodels.PermissionVo; public class DefaultPermissionManager implements PermissionManager { private final static String ROAM_PERMISSION_FILE = "roamPermission.xml"; private final static String PERMISSION_FILE = "permission.xml"; public void getAllPermssion(String authId) throws XPathExpressionException, IOException { List<PermissionVo> permissions = new ArrayList<PermissionVo>(); Map<String, PermissionVo> permissionMap = new LinkedHashMap<String, PermissionVo>(); List<PermissionVo> list = new ArrayList<PermissionVo>(); List<PermissionVo> authList = this.findSubRoamPermissionById(authId); for (PermissionVo permission : authList) { //String authId = permission.getId(); // PermissionVo permissionVo = this.getPermissionByPath(permission // .getValue(), ROAM_PERMISSION_FILE); permissionMap.put(permission.getId(), permission); if (authList.size() == 0) { continue; } permission.getPermissionList().addAll(authList); list.add(permission); //this.getAllPermssion(authList); } } public List<PermissionVo> getPermissionToTree(String id) throws XPathExpressionException, IOException { List<PermissionVo> listPermission = new ArrayList<PermissionVo>(); listPermission = this.findSubRoamPermissionById(id); for(PermissionVo permission : listPermission) { this.getAllPermssion(permission.getId()); } return listPermission; } public List<PermissionVo> findSubRoamPermissionById(String id) throws XPathExpressionException, IOException { List<PermissionVo> authList = new ArrayList<PermissionVo>(); InputStream is = null; InputSource src = null; XPathExpression exp = null; try { XPathFactory fac = XPathFactory.newInstance(); XPath xpath = fac.newXPath(); exp = xpath.compile("//p[@id='" + id + "']"); is = this.getClass().getClassLoader().getResourceAsStream( ROAM_PERMISSION_FILE); src = new InputSource(is); NodeList list = (NodeList) exp .evaluate(src, XPathConstants.NODESET); authList = new ArrayList<PermissionVo>(); for (int i = 0; i < list.getLength(); i++) { Element element = (Element) list.item(i); if (element == null) { return null; } NodeList children = element.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node e = children.item(j); if (e instanceof Element) { Element el = (Element) e; PermissionVo permission = new PermissionVo(); permission.setId(el.getAttribute("id")); permission.setName(el.getAttribute("name")); permission.setValue(el.getAttribute("value")); permission.setOrderBy(el.getAttribute("order")); if (el.getAttribute("value").endsWith("*")) { permission.setIsHaveIO(false); } else { permission.setIsHaveIO(true); } authList.add(permission); } } } } finally { is.close(); } return authList; } public List<PermissionVo> findSubPermissionById(String id, String authXml) throws XPathExpressionException, IOException { List<PermissionVo> authList = null; InputStream is = null; InputSource src = null; XPathExpression exp = null; try { XPathFactory fac = XPathFactory.newInstance(); XPath xpath = fac.newXPath(); exp = xpath.compile("//p[@id='" + id + "']"); is = this.getClass().getClassLoader().getResourceAsStream( authXml); src = new InputSource(is); NodeList list = (NodeList) exp .evaluate(src, XPathConstants.NODESET); authList = new ArrayList<PermissionVo>(); for (int i = 0; i < list.getLength(); i++) { Element element = (Element) list.item(i); NodeList children = element.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node e = children.item(j); if (e instanceof Element) { Element el = (Element) e; PermissionVo permission = new PermissionVo(); permission.setId(el.getAttribute("id")); permission.setName(el.getAttribute("name")); permission.setValue(el.getAttribute("value")); permission.setOrderBy(el.getAttribute("order")); if (el.getAttribute("value").endsWith("*")) { permission.setIsHaveIO(false); } else { permission.setIsHaveIO(true); } authList.add(permission); } } } } finally { is.close(); } return authList; } public PermissionVo getPermissionByPath(String auth, String authXml) throws XPathExpressionException, IOException { InputStream is = null; InputSource src = null; XPathExpression exp = null; PermissionVo permission = new PermissionVo(); if (auth != null) { try { XPathFactory fac = XPathFactory.newInstance(); XPath xpath = fac.newXPath(); exp = xpath.compile("//p[@value='" + auth + "']"); is = this.getClass().getClassLoader().getResourceAsStream( authXml); src = new InputSource(is); Node node = (Node) exp.evaluate(src, XPathConstants.NODE); Element elementNode = (Element) node; if (elementNode != null) { if (elementNode.getAttribute("value") == null) { return null; } permission.setId(elementNode.getAttribute("id")); permission.setName(elementNode.getAttribute("name")); permission.setValue(elementNode.getAttribute("value")); permission.setOrderBy(elementNode.getAttribute("order")); if (elementNode.getAttribute("value").endsWith("*")) { permission.setIsHaveIO(false); } else { permission.setIsHaveIO(true); } } else { return null; } } finally { if(is!=null){is.close();} } } return permission; } public PermissionVo getParentPermissionByPath(String auth) throws XPathExpressionException, IOException { InputStream is = null; System.out.println("*****************22*" + auth); InputSource src = null; XPathExpression exp = null; PermissionVo permission = new PermissionVo(); if (auth != null) { try { XPathFactory fac = XPathFactory.newInstance(); XPath xpath = fac.newXPath(); exp = xpath.compile("//p[@value='" + auth + "']"); is = this.getClass().getClassLoader().getResourceAsStream( PERMISSION_FILE); src = new InputSource(is); if (StringUtils.isNotBlank(auth) && auth != null) { Node node = (Node) exp.evaluate(src, XPathConstants.NODE); Element elementNode = (Element) node; Element elementParent = null; if (elementNode != null) { elementParent = (Element) elementNode.getParentNode(); permission.setId(elementParent.getAttribute("id")); permission.setName(elementParent.getAttribute("name")); permission .setValue(elementParent.getAttribute("value")); permission.setOrderBy(elementParent .getAttribute("order")); if (StringUtils.isBlank(elementParent .getAttribute("value"))) { permission = null; } } } else { permission = null; } } finally { is.close(); } } return permission; } private void getParentPermissionListAuthByPath(String auth, Set<String> allAuth, String authXml) throws XPathExpressionException, IOException { List<PermissionVo> permissionList = new ArrayList<PermissionVo>(); permissionList = findSubPermissionByValue(auth, authXml); for (PermissionVo permission : permissionList) { allAuth.add(permission.getValue()); this.getParentPermissionListAuthByPath(permission.getValue(), allAuth, authXml); } } public String getParentPermissionListAuthByList(List<String> authList, String authXml) throws XPathExpressionException, IOException { Set<String> allAuth = new HashSet<String>(); for (String auth : authList) { allAuth.add(auth); this.getParentPermissionListAuthByPath(auth, allAuth, authXml); } String utils = StringUtils.join(allAuth, ";"); return utils; } public List<PermissionVo> findSubPermissionByValue(String value, String authXml) throws XPathExpressionException, IOException { List<PermissionVo> authList = null; InputStream is = null; InputSource src = null; XPathExpression exp = null; try { XPathFactory fac = XPathFactory.newInstance(); XPath xpath = fac.newXPath(); exp = xpath.compile("//p[@value='" + value + "']"); is = this.getClass().getClassLoader().getResourceAsStream( authXml); src = new InputSource(is); NodeList list = (NodeList) exp .evaluate(src, XPathConstants.NODESET); authList = new ArrayList<PermissionVo>(); for (int i = 0; i < list.getLength(); i++) { Element element = (Element) list.item(i); if (element != null) { NodeList children = element.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node e = children.item(j); if (e instanceof Element) { Element el = (Element) e; PermissionVo permission = new PermissionVo(); permission.setId(el.getAttribute("id")); permission.setName(el.getAttribute("name")); permission.setValue(el.getAttribute("value")); permission.setOrderBy(el.getAttribute("order")); if (el.getAttribute("value").endsWith("*")) { permission.setIsHaveIO(false); } else { permission.setIsHaveIO(true); } authList.add(permission); } } } } } finally { is.close(); } return authList; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/DefaultPermissionManager.java
Java
asf20
10,291
package com.zyeeda.framework.managers.internal; import java.util.List; import javax.naming.directory.SearchControls; import com.zyeeda.framework.entities.User; import com.zyeeda.framework.managers.UserManager; import com.zyeeda.framework.managers.UserPersistException; import com.zyeeda.framework.managers.base.DomainEntityManager; import com.zyeeda.framework.persistence.PersistenceService; public class DefaultUserManager extends DomainEntityManager<User, String> implements UserManager { public DefaultUserManager(PersistenceService persistenceSvc) { super(persistenceSvc); } @Override public List<User> findByDepartmentId(String id) { return null; } @Override public User findById(String id) throws UserPersistException { return super.find(id); } @Override public List<User> findByName(String name) throws UserPersistException { return null; } @Override public void persist(User user) throws UserPersistException { super.persist(user); } @Override public void remove(String id) throws UserPersistException { super.removeById(id); } @Override public void disable(String... ids) throws UserPersistException { this.setVisible(false, ids); } @Override public void enable(String... ids) throws UserPersistException { this.setVisible(true, ids); } @Override public void update(User user) throws UserPersistException { super.merge(user); } @Override public void updatePassword(String id, String password) throws UserPersistException { User user = new User(); user.setId(id); user.setPassword(password); super.merge(user); } private void setVisible(Boolean visible, String... ids) { StringBuffer buffer = new StringBuffer(); for (String id : ids) { buffer.append(id).append(","); } if (buffer.length() > 0) { buffer.deleteCharAt(buffer.lastIndexOf(",")); } super.em().createQuery("update com.zyeeda.framework.entities.User o set o.status = ?1 where o.id in(?2)") .setParameter(1, visible).setParameter(2, buffer.toString()).executeUpdate(); } @Override public List<User> search(String condition) throws UserPersistException { return null; } @Override public List<User> findByDepartmentId(String id, SearchControls sc) throws UserPersistException { return null; } @Override public List<User> findByName(String name, SearchControls sc) throws UserPersistException { return null; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/DefaultUserManager.java
Java
asf20
2,521
package com.zyeeda.framework.managers.internal; import static com.zyeeda.framework.managers.internal.MongoDbDocumentManagerHelper.document2GridFSFile; import static com.zyeeda.framework.managers.internal.MongoDbDocumentManagerHelper.gridFSDBFile2Document; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.bson.types.ObjectId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSFile; import com.zyeeda.framework.entities.Document; import com.zyeeda.framework.managers.DocumentManager; import com.zyeeda.framework.nosql.MongoDbService; public class MongoDbDocumentManager implements DocumentManager { private static final Logger logger = LoggerFactory.getLogger(MongoDbDocumentManager.class); //private final static String COLLECTION_NAME = "docs"; private MongoDbService mongodbSvc; public MongoDbDocumentManager(MongoDbService mongodbSvc) { this.mongodbSvc = mongodbSvc; } /* @Deprecated private DBCollection getCollection() { DB db = this.mongodbSvc.getDefaultDatabase(); DBCollection collection = db.getCollection(COLLECTION_NAME); return collection; } */ private DBCollection getFilesCollection() { DB db = this.mongodbSvc.getDefaultDatabase(); DBCollection collection = db.getCollection("fs.files"); return collection; } @Override public void persist(Document document) { GridFS fs = new GridFS(this.mongodbSvc.getDefaultDatabase()); GridFSFile file = document2GridFSFile(fs, document); logger.info("saving uplaoded file {} ...", document.getName()); file.save(); logger.info("file {} saved", document.getName()); document.setId(file.getId().toString()); } @Override public Document findById(String id, boolean includeContent) { DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(id)); GridFS fs = new GridFS(this.mongodbSvc.getDefaultDatabase()); GridFSDBFile file = fs.findOne(query); return gridFSDBFile2Document(file, includeContent); } @Override public Document findByIdAndFileName(String id, String fileName) { logger.trace("find by id [{}] and file name [{}]", id, fileName); DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(id)); query.put("filename", fileName); GridFS fs = new GridFS(this.mongodbSvc.getDefaultDatabase()); GridFSDBFile file = fs.findOne(query); return gridFSDBFile2Document(file); } @Override public void removeById(String id) { logger.trace("remove by id = {}", id); GridFS fs = new GridFS(this.mongodbSvc.getDefaultDatabase()); fs.remove(new ObjectId(id)); } @Override public long countByForeignId(String foreignId) { DBObject query = new BasicDBObject(); query.put("foreignId", foreignId); DBCollection c = this.getFilesCollection(); return c.count(query); } @Override public void replaceForeignId(String oldForeignId, String newForeignId) { DBObject query = new BasicDBObject(); query.put("foreignId", oldForeignId); DBObject update = new BasicDBObject( "$set", new BasicDBObjectBuilder() .add("foreignId", newForeignId) .add("isTemp", false).get()); DBCollection collection = this.getFilesCollection(); collection.updateMulti(query, update); } @Override public List<Document> findByForeignId(String foreignId) { DBObject query = new BasicDBObject(); query.put("foreignId", foreignId); GridFS fs = new GridFS(this.mongodbSvc.getDefaultDatabase()); List<GridFSDBFile> files = fs.find(query); List<Document> docs = new ArrayList<Document>(files.size()); for (GridFSDBFile file : files) { docs.add(gridFSDBFile2Document(file, false)); } return docs; } @Override public void eraseTemp() { DBObject query = new BasicDBObject(); query.put("isTemp", true); GridFS fs = new GridFS(this.mongodbSvc.getDefaultDatabase()); fs.remove(query); } @Override public long countByIsTemp() { DBObject query = new BasicDBObject(); query.put("isTemp", true); DBCollection c = this.getFilesCollection(); return c.count(query); } @Override public long countBySuffixes(String foreignId, String tempForeignId, String... suffixes) { DBObject query = new BasicDBObjectBuilder().push("foreignId").add("$in", new String[] { foreignId, tempForeignId }).pop() .push("fileType").add("$in", suffixes).get(); logger.debug("bson query = {}", query); DBCollection c = this.getFilesCollection(); return c.count(query); } @Override public void copyFile(String oldForeignId, String newForeignId) { List<Document> docs = this.findByForeignId(oldForeignId); DBObject query = new BasicDBObject(); GridFS fs = new GridFS(this.mongodbSvc.getDefaultDatabase()); for (Document doc : docs) { query.put("_id", new ObjectId(doc.getId())); GridFSDBFile file = fs.findOne(query); doc.setForeignId(newForeignId); InputStream in = file.getInputStream(); doc.setContent(in); this.persist(doc); } } /* private List<Document> find(Map<String, Object> map, Map<String, Object> map1, String foreignId, int skip, int limit) throws DocumentException, MongoException { try { DBCollection collection = this.getCollection(); GridFS gridFS = new GridFS(collection.getDB()); BasicDBObject basicDBObject = new BasicDBObject(); if (StringUtils.isNotBlank(foreignId)) { basicDBObject.put("foreignId", foreignId); } if (map != null) { basicDBObject.put((String) map.get("condition"), map .get("value")); } if (map1 != null) { DBObject in = new BasicDBObject("$in", map1.get("value")); basicDBObject.put((String) map1.get("condition"), in); } BasicDBObject condition = new BasicDBObject(); condition.put("lastModifiedTime", -1);// 排序的元素 根据时间从大到小 DBCursor cursor = gridFS.getFileList(basicDBObject).sort(condition) .skip(skip).limit(limit); List<Document> documentList = new ArrayList<Document>(cursor .count()); while (cursor.hasNext()) { Document document = new Document(); GridFSDBFile gridFSDBFile = (GridFSDBFile) cursor.next(); document.setId(gridFSDBFile.getId().toString()); document.setName(gridFSDBFile.getFilename()); document.setDescription((String) gridFSDBFile .get("description")); document.setCreator((String) gridFSDBFile.get("creator")); document.setFileType((String) gridFSDBFile.get("fileType")); document.setFileSize(gridFSDBFile.getLength()); document.setCreatedTime(gridFSDBFile.getUploadDate()); document.setLastModifier((String) gridFSDBFile .get("lastModifier")); document.setLastModifiedTime((Date) gridFSDBFile .get("lastModifiedTime")); document.setForeignId((String) gridFSDBFile.get("foreignId")); Object obj = gridFSDBFile.get("weight"); if (obj != null) { document.setWeight(Integer.parseInt(obj.toString())); } document.setCreatedTime(gridFSDBFile.getUploadDate()); document.setOwner((String) gridFSDBFile.get("owner")); document.setFileType((String) gridFSDBFile.get("fileType")); document.setKeyword((String) gridFSDBFile.get("keyword")); document.setContentType(gridFSDBFile.getContentType()); document.setSubType((String) gridFSDBFile.get("subType")); document.setPrimaryType((String) gridFSDBFile.get("primaryType")); documentList.add(document); } return documentList; } catch (Exception e) { throw new DocumentException(e); } } @Override public List<Document> findByKeyword(String owner, String[] keyword, String foreignId, int skip, int limit) throws DocumentException { try { Map<String, Object> map = null; Map<String, Object> map1 = null; if (StringUtils.isNotBlank(owner)) { map = new HashMap<String, Object>(); map.put("condition", "owner"); map.put("value", owner); } map1 = new HashMap<String, Object>(); map1.put("condition", "keyword"); map1.put("value", keyword); return this.find(map, map1, foreignId, skip, limit); } catch (MongoException e) { throw new DocumentException(e); } } // 批量删除 @Override public void allremoveById(String[] id) throws DocumentException { logger.debug("remove by id = {}", id); try { DBCollection collection = this.getCollection(); GridFS gridFS = new GridFS(collection.getDB()); for (int i = 0; i < id.length; i++) { logger.debug("removeId = {}", id[i]); gridFS.remove(new ObjectId(id[i])); } } catch (MongoException e) { throw new DocumentException(e); } } @Override public int findNumber(String owner, String foreignId, String[] keyword) throws DocumentException { // TODO Auto-generated method stub return 0; } @Override public int findNumber(String foreignId, String[] keyword) throws DocumentException { // TODO Auto-generated method stub return 0; } @Override public int findOwnerNumber(String owner, String foreignId) throws DocumentException { // TODO Auto-generated method stub return 0; } @Override public List<Document> findByKeyword(String owner, String foreignId, int skip, int limit) throws DocumentException { // TODO Auto-generated method stub return null; } @Override public void updateDocument(Document document) throws UnknownHostException, DocumentException { // TODO Auto-generated method stub } */ /*@Override public void updateDocument(Document document) throws DocumentException { try { logger.debug("updateDocument keyword={}", document.getKeyword()); logger.debug("updateDocument name={}", document.getName()); logger.debug("updateDocument desc={}", document.getDescription()); Mongo mongo = new Mongo(addr, port); DBCollection collection = mongo.getDB(DB).getCollection("fs.files"); BasicDBObject updateObject = new BasicDBObject(); if (StringUtils.isNotBlank(document.getDescription())) { updateObject.put("description", document.getDescription()); } if (StringUtils.isNotBlank(document.getKeyword())) { updateObject.put("keyword", document.getKeyword()); } if (StringUtils.isNotBlank(document.getName())) { updateObject.put("filename", document.getName()); } if (StringUtils.isNotBlank(document.getLastModifier())) { updateObject.put("lastModifier", document.getLastModifier()); } if(document.getLastModifiedTime()!=null){ updateObject.put("lastModifiedTime", document.getLastModifiedTime()); } BasicDBObject basic = new BasicDBObject(); basic.put("$set", updateObject); collection.update(new BasicDBObject("_id", new ObjectId(document .getId())), basic, false, true); } catch (MongoException e) { throw new DocumentException(e); } catch (UnknownHostException e) { throw new DocumentException(e); } } // @Override // public List<Document> findByKeyword(String owner, int skip, int limit) // throws DocumentException { // Map<String, Object> map = null; // Map<String, Object> map1 = null; // if (StringUtils.isNotBlank(owner)) { // map = new HashMap<String, Object>(); // map.put("condition", "owner"); // map.put("value", owner); // } // return this.find(map, map1, null, skip, limit); // } @Override public List<Document> findByKeyword(String owner, String foreignId, int skip, int limit) throws DocumentException { Map<String, Object> map = null; Map<String, Object> map1 = null; if (StringUtils.isNotBlank(owner)) { map = new HashMap<String, Object>(); map.put("condition", "owner"); map.put("value", owner); } return this.find(map, map1, foreignId, skip, limit); } @Override public int findNumber(String owner, String foreignId, String[] keyword) throws DocumentException { try { DBCollection collection = this.getCollection(addr, port, DB); GridFS gridFS = new GridFS(collection.getDB()); BasicDBObject basicDBObject = new BasicDBObject(); if (StringUtils.isNotBlank(foreignId)) { basicDBObject.put("foreignId", foreignId); } if (StringUtils.isNotBlank(owner)) { basicDBObject.put("owner", owner); } DBObject in = new BasicDBObject("$in", keyword); basicDBObject.put("keyword", in); return gridFS.find(basicDBObject).size(); } catch (UnknownHostException e) { throw new DocumentException(e); } } @Override public int findNumber(String foreignId, String[] keyword) throws DocumentException { try { DBCollection collection = this.getCollection(addr, port, DB); GridFS gridFS = new GridFS(collection.getDB()); BasicDBObject basicDBObject = new BasicDBObject(); if (StringUtils.isNotBlank(foreignId)) { basicDBObject.put("foreignId", foreignId); } if (keyword.length > 1) { DBObject in = new BasicDBObject("$in", keyword); basicDBObject.put("keyword", in); } return gridFS.find(basicDBObject).size(); } catch (UnknownHostException e) { throw new DocumentException(e); } } @Override public int findOwnerNumber(String owner, String foreignId) throws DocumentException { try { DBCollection collection = this.getCollection(addr, port, DB); GridFS gridFS = new GridFS(collection.getDB()); BasicDBObject basicDBObject = new BasicDBObject(); if (StringUtils.isNotBlank(foreignId)) { basicDBObject.put("foreignId", foreignId); } if (StringUtils.isNotBlank(owner)) { basicDBObject.put("owner", owner); } return gridFS.find(basicDBObject).size(); } catch (UnknownHostException e) { throw new DocumentException(e); } } @Override public Document findById(String id) throws DocumentException { try { DBCollection collection = this.getCollection(addr, port, DB); GridFS gridFS = new GridFS(collection.getDB()); GridFSDBFile gridFSDbFile = gridFS.find(new ObjectId(id)); Document document = new Document(); document.setId(gridFSDbFile.getId().toString()); document.setName(gridFSDbFile.getFilename()); document.setDescription((String) gridFSDbFile.get("description")); document.setCreator((String) gridFSDbFile.get("creator")); document.setCreatedTime((Date) gridFSDbFile.get("createdTime")); document.setLastModifier((String) gridFSDbFile.get("lastModifier")); document.setLastModifiedTime((Date) gridFSDbFile .get("lastModifiedTime")); document.setForeignId((String) gridFSDbFile.get("foreignId")); Object weightObj = gridFSDbFile.get("weight"); if (weightObj != null) { document.setWeight(Integer.parseInt((weightObj.toString()))); } document.setOwner((String) gridFSDbFile.get("owner")); // document.setFileSize(gridFSDbFile.getLength()); // 系统默认的 document.setFileType((String) gridFSDbFile.get("fileType")); document.setKeyword((String) gridFSDbFile.get("keyword")); document.setContent(gridFSDbFile.getInputStream()); document.setContentType(gridFSDbFile.getContentType()); document.setSubType((String) gridFSDbFile.get("subType")); document.setType((String) gridFSDbFile.get("type")); return document; } catch (UnknownHostException e) { throw new DocumentException(e); } catch (MongoException e) { throw new DocumentException(e); } }*/ }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/internal/MongoDbDocumentManager.java
Java
asf20
15,844
package com.zyeeda.framework.managers; import java.util.List; import com.googlecode.genericdao.dao.jpa.GenericDAO; import com.zyeeda.framework.entities.Role; import com.zyeeda.framework.viewmodels.RoleVo; import com.zyeeda.framework.viewmodels.UserVo; public interface RoleManager extends GenericDAO<Role, String> { public List<Role> getRoleBySubject(String subject); public List<Role> getRoleDistinct(String hql); public List<RoleVo> roleToVo(List<Role> listRole); public List<UserVo> getUserVoByRole(Role role); public List<RoleVo> deptToVo(List<Role> listRole); }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/RoleManager.java
Java
asf20
619
package com.zyeeda.framework.managers.base; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.LinkedHashMap; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Query; import org.hibernate.ejb.HibernateEntityManagerFactory; import com.googlecode.genericdao.dao.jpa.GenericDAOImpl; import com.googlecode.genericdao.search.MetadataUtil; import com.googlecode.genericdao.search.jpa.JPASearchProcessor; import com.googlecode.genericdao.search.jpa.hibernate.HibernateMetadataUtil; import com.zyeeda.framework.persistence.PersistenceService; @SuppressWarnings("unchecked") public class DomainEntityManager<T, ID extends Serializable> extends GenericDAOImpl<T, ID> { private PersistenceService persistenceSvc; public DomainEntityManager(PersistenceService persistenceSvc) { this.persistenceSvc = persistenceSvc; this.setEntityManager(this.persistenceSvc.getCurrentSession()); HibernateEntityManagerFactory emf = (HibernateEntityManagerFactory) this.persistenceSvc.getSessionFactory(); MetadataUtil util = HibernateMetadataUtil.getInstanceForEntityManagerFactory(emf); JPASearchProcessor processor = new JPASearchProcessor(util); this.setSearchProcessor(processor); } protected PersistenceService getPersistenceService() { return this.persistenceSvc; } protected Class<T> entityClass = (Class<T>) ((ParameterizedType) this .getClass().getGenericSuperclass()).getActualTypeArguments()[0]; protected static void setQueryParams(Query query, Object[] queryParams) { if (queryParams != null && queryParams.length > 0) { for (int i = 0; i < queryParams.length; i++) { query.setParameter(i + 1, queryParams[i]); } } } /** * 获取实体的名称 * @param <E> * @param clazz 实体类 * @return */ protected static <E> String getEntityName(Class<E> clazz){ String entityname = clazz.getSimpleName(); Entity entity = clazz.getAnnotation(Entity.class); if(entity.name() != null && !"".equals(entity.name())){ entityname = entity.name(); } return entityname; } /** * 组装order by语句 * * @param orderby * @return */ protected static String buildOrderBy(LinkedHashMap<String, Object> orderby) { StringBuffer orderbyql = new StringBuffer(""); if (orderby != null && orderby.size() > 0) { orderbyql.append(" order by "); for (String key : orderby.keySet()) { orderbyql.append("o.").append(key).append(" ").append( orderby.get(key)).append(","); } orderbyql.deleteCharAt(orderbyql.length() - 1); } return orderbyql.toString(); } protected static <E> String getCountField(Class<E> clazz) { String out = "o"; try { PropertyDescriptor[] propertyDescriptors = Introspector .getBeanInfo(clazz).getPropertyDescriptors(); for (PropertyDescriptor propertydesc : propertyDescriptors) { Method method = propertydesc.getReadMethod(); if (method != null && method.isAnnotationPresent(EmbeddedId.class)) { PropertyDescriptor[] ps = Introspector.getBeanInfo( propertydesc.getPropertyType()) .getPropertyDescriptors(); out = "o." + propertydesc.getName() + "." + (!ps[1].getName().equals("class") ? ps[1] .getName() : ps[0].getName()); break; } } } catch (Exception e) { e.printStackTrace(); } return out; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/base/DomainEntityManager.java
Java
asf20
3,507
package com.zyeeda.framework.managers; import java.io.IOException; import java.util.List; import javax.xml.xpath.XPathExpressionException; import com.zyeeda.framework.viewmodels.MenuVo; public interface MenuManager { public List<MenuVo> getMenuListByPermissionAuth(List<String> authList) throws XPathExpressionException, IOException; }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/MenuManager.java
Java
asf20
361
package com.zyeeda.framework.managers; import java.util.List; import com.zyeeda.framework.entities.Document; public interface DocumentManager { public void persist(Document doc); public Document findById(String id, boolean includeContent); public Document findByIdAndFileName(String id, String fileName); public void removeById(String id); public long countByForeignId(String foreignId); public void replaceForeignId(String oldForeignId, String newForeignId); public List<Document> findByForeignId(String foreignId); public long countByIsTemp(); public void eraseTemp(); public long countBySuffixes(String foreignId, String tempForeignId, String... suffixes); public void copyFile(String oldForeignId, String newForeignId); /* public int findNumber(String owner,String foreignId,String[] keyword) throws DocumentException; public int findNumber(String foreignId, String[] keyword) throws DocumentException; public int findOwnerNumber(String owner,String foreignId) throws DocumentException; // 鏍规嵁ID鍚嶅瓧鍘绘煡璇 // 鏍规嵁鎷ユ湁浜哄叧閿瓧鏁版嵁绫诲埆鍘绘煡璇 public List<Document> findByKeyword(String owner, String[] keyword, String foreignId, int skip, int limit) throws DocumentException; //public List<Document> findByKeyword(String owner, int skip, int limit) throws DocumentException; public List<Document> findByKeyword(String owner,String foreignId, int skip, int limit) throws DocumentException; public void updateDocument(Document document) throws UnknownHostException, DocumentException; public void allremoveById(String[] id) throws DocumentException; */ }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/DocumentManager.java
Java
asf20
1,753
// Copyright 2011, Zyeeda, Inc. All Rights Reserved. // Confidential and Proprietary Information of Zyeeda, Inc. package com.zyeeda.framework.managers; import java.util.List; import com.zyeeda.framework.entities.Account; /** * account manager * * @author Qi Zhao * @date 2011-06-15 * * @LastChanged * @LastChangedBy $LastChangedBy: $ * @LastChangedDate $LastChangedDate: $ * @LastChangedRevision $LastChangedRevision: $ */ public interface AccountManager { public List<Account> findByUserId(String userId) throws UserPersistException; public Account findByUserIdAndSystemName(String userId, String systemName) throws UserPersistException; public void update(Account account) throws UserPersistException; public void remove(String systemName) throws UserPersistException; }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/AccountManager.java
Java
asf20
820
package com.zyeeda.framework.managers; import java.util.List; import javax.naming.directory.SearchControls; import com.zyeeda.framework.entities.User; public interface UserManager { public void persist(User user) throws UserPersistException; public void remove(String id) throws UserPersistException; public void update(User user) throws UserPersistException; public User findById(String id) throws UserPersistException; public List<User> findByDepartmentId(String id) throws UserPersistException; public List<User> findByName(String name) throws UserPersistException; public List<User> findByName(String name, SearchControls sc) throws UserPersistException; public List<User> search(String condition) throws UserPersistException; public void updatePassword(String id, String password) throws UserPersistException; public void enable(String... ids) throws UserPersistException; public void disable(String... ids) throws UserPersistException; public List<User> findByDepartmentId(String id, SearchControls sc) throws UserPersistException; }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/managers/UserManager.java
Java
asf20
1,112
/* * Copyright 2010 Zyeeda Co. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zyeeda.framework.helpers; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zyeeda.framework.template.TemplateService; import freemarker.template.TemplateException; /** * Template helper class. * * @author Rui Tang * @version %I%, %G% * @since 1.0 */ public class TemplateHelper { private static final Logger logger = LoggerFactory.getLogger(TemplateHelper.class); public static void paintException(TemplateService tplSvc, PrintWriter out, List<String> errorMessages) throws IOException, TemplateException { logger.debug("errorMessages = {}", errorMessages); Map<String, Object> args = new HashMap<String, Object>(); args.put("errorMessages", errorMessages); tplSvc.paint("/lib/zyeeda/default_error_view.ftl", out, args); } public static void paintException(TemplateService tplSvc, PrintWriter out, String errorMessage) throws IOException, TemplateException { logger.debug("errorMessage = {}", errorMessage); if (errorMessage == null) { paintException(tplSvc, out, (List<String>) null); return; } List<String> errorMessages = new ArrayList<String>(1); errorMessages.add(errorMessage); paintException(tplSvc, out, errorMessages); } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/helpers/TemplateHelper.java
Java
asf20
2,054
// Copyright 2011, Zyeeda, Inc. All Rights Reserved. // Confidential and Proprietary Information of Zyeeda, Inc. package com.zyeeda.framework.helpers; import java.util.ArrayList; import java.util.List; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttributes; import javax.naming.directory.SearchResult; import org.apache.commons.lang.StringUtils; import com.zyeeda.framework.entities.Account; /** * help the between the attributes and account convert. * * @author Qi Zhao * @date 2011-06-15 * * @LastChanged * @LastChangedBy $LastChangedBy: $ * @LastChangedDate $LastChangedDate: $ * @LastChangedRevision $LastChangedRevision: $ */ public class AccountHelper { public static Attributes convertAccountToAttributes(Account account) { Attributes attributes = new BasicAttributes(); attributes.put("objectClass", "inetOrgPerson"); attributes.put("objectClass", "organizationalPerson"); attributes.put("objectClass", "person"); attributes.put("objectClass", "top"); attributes.put("objectClass", "userReferenceSystem"); if (StringUtils.isNotBlank(account.getSystemName())) { attributes.put("cn", account.getSystemName()); attributes.put("sn", account.getSystemName()); attributes.put("systemName", account.getSystemName()); } else { attributes.put("cn", "fms"); attributes.put("sn", "fms"); attributes.put("systemName", "fms"); } if (StringUtils.isNotBlank(account.getUserName())) { attributes.put("username", account.getUserName()); } else { attributes.put("username", "temp"); } if (StringUtils.isNotBlank(account.getPassword())) { attributes.put("password", account.getPassword()); } else { attributes.put("password", "123456"); } attributes.put("status", account.getStatus().toString()); return attributes; } public static Account convertAttributesToAccount(Attributes attributes) throws NamingException { Account account = new Account(); account.setSystemName(attributes.get("systemName").get() != null ? (String) attributes .get("systemName").get() : ""); account.setUserName(attributes.get("username").get() != null ? (String) attributes .get("username").get() : ""); account.setPassword(attributes.get("password").get() != null ? (String) attributes .get("password").get() : ""); account.setStatus(Boolean.valueOf(attributes.get("status").get().toString())); return account; } public static List<Account> convertNameingEnumeractionToAccountList( NamingEnumeration<SearchResult> nes) throws NamingException { List<Account> accounts = new ArrayList<Account>(); while (nes.hasMore()) { Attributes attributes = nes.next().getAttributes(); Account account = convertAttributesToAccount(attributes); accounts.add(account); } return accounts; } }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/helpers/AccountHelper.java
Java
asf20
2,915
package com.zyeeda.framework.knowledge; import org.drools.runtime.StatefulKnowledgeSession; public interface StatefulSessionCommand<T> { public T execute(StatefulKnowledgeSession ksession); public int getSessionId(); }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/knowledge/StatefulSessionCommand.java
Java
asf20
231
package com.zyeeda.framework.knowledge; import org.drools.KnowledgeBase; import org.drools.task.service.TaskService; import com.zyeeda.framework.service.Service; public interface KnowledgeService extends Service { public KnowledgeBase getKnowledgeBase(); public TaskService getTaskService(); public <T> T execute(StatefulSessionCommand<T> command) throws Exception; }
zyeeda-framework
core/src/main/java/com/zyeeda/framework/knowledge/KnowledgeService.java
Java
asf20
397