branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>kwong4/UpgradedGames<file_sep>/project2/GetMeMyFruit.h // Author: <NAME> #ifndef _GETMEMYFRUIT_H #define _GETMEMYFRUIT_H #define MODE GFX_AUTODETECT_WINDOWED #define WIDTH 640 #define HEIGHT 480 #define JUMPIT 1600 #define BLACK makecol(0,0,0) #define WHITE makecol(255,255,255) #define YELLOW makecol(255,216,0) #define ORANGE makecol(255,127,39) #define GREEN makecol(80,226,83) #define RED makecol(255,47,63) #define BLUE makecol(70,101,200) #define ENEMY1_START_X 3 * 16 #define ENEMY1_START_Y 27 * 16 #define ENEMY1_END_X 31 * 16 #define ENEMY2_START_X 19 * 16 #define ENEMY2_START_Y 3 * 16 #define ENEMY2_END_X 43 * 16 #define ENEMY3_START_X 104 * 16 #define ENEMY3_START_Y 8 * 16 #define ENEMY3_END_X 116 * 16 #define ENEMY4_START_X 88 * 16 #define ENEMY4_START_Y 25 * 16 #define ENEMY4_END_X 118 * 16 #define START_POINT_X 59 * 16 #define START_POINT_Y 24 * 14 #define WALKFRAME_MIN 2 #define WALKFRAME_MAX 3 #define WAITFRAME_MIN 0 #define WAITFRAME_MAX 1 #define EASY_MODE 1 #define HARD_MODE 2 #define FRUIT_MAX 4 #define FRAME_DELAY 6 #define FRAME_DELAY_ENEMY 14 #define PLAYER_MAX_FRAME 4 #define JUMPFRAME 4 #define WAITCOUNT_MAX 5 #define TOP_BUFFER 10 #define FRUIT_CONSTANT 20 #define COOLDOWN 20 #define GAME_WORLD "GameWorld.FMP" //define the sprite structure typedef struct SPRITE { int dir, alive; int x,y; int min_x, max_x; int width,height; int xspeed,yspeed; int xdelay,ydelay; int xcount,ycount; int curframe,maxframe,animdir; int framecount,framedelay; int data; }SPRITE; // Functions // Tile Grabber BITMAP *grabframe(BITMAP *source, int width, int height, int startx, int starty, int columns, int frame); // Point collision with bounding box int inside_box(int x,int y,int left,int top,int right,int bottom); // Sprite collision with shrink and bounding box int collided(SPRITE *current, SPRITE *other, int shrink); // Mappy Collision detection int map_collided(int x, int y); // Check if sprite inside of screen int inside(SPRITE* sprite); // Print Insturction screen void instructions(); // Get Game menu input int getmenuinput(); // Print the welcome screen menu void welcome_screen(); // Draw initial start screen instructions void draw_startscreen(); // Setup initial files void setupscreen(); // Setup game void setupgame(); // Player walking position and animation update void walk(int dir); // Enemy walking position and animation update void walk_enemies(SPRITE *enemy); // Update Enemies void update_enemies(); // Player wait animation void wait(); // General update function void update(); // Get game input from user void getinput(); //declare the bitmaps and sprites BITMAP *player_image[5]; SPRITE *player; BITMAP *fruits_image[4]; SPRITE *fruits[4]; BITMAP *green_enemy_image[6]; SPRITE *green_enemy; BITMAP *blue_enemy_image[7]; SPRITE *blue_enemy; BITMAP *orange_enemy_image[6]; SPRITE *orange_enemy; BITMAP *red_enemy_image[6]; SPRITE *red_enemy; BITMAP *buffer; BITMAP *temp; BITMAP *title; SAMPLE *background_music; SAMPLE *click_sound; SAMPLE *jump_sound; SAMPLE *fruit_collect_sound; SAMPLE *enemy_die_sound; SAMPLE *game_over_sound; SAMPLE *splash_sound; SAMPLE *game_win_sound; int facing = 0; int jump = JUMPIT; int mapxoff, mapyoff; int oldpx, oldpy; int gameover = 0; int win = 0; int sound = 1; int waitcount = 0; int selection = 0; int max_selection = 2; int hardmode = 0; int fruit_collected = 0; int sound_cooldown = 0; int menu_cooldown = 0; DATAFILE *data; #endif <file_sep>/project1/defines.h /* Allegro datafile object indexes, produced by dat v4.4.2, MinGW32 */ /* Datafile: data.dat */ /* Date: Mon Oct 09 15:04:00 2017 */ /* Do not hand edit! */ #define ASTEROID1_BMP 0 /* BMP */ #define ASTEROID20_BMP 1 /* BMP */ #define ASTEROID21_BMP 2 /* BMP */ #define ASTEROID22_BMP 3 /* BMP */ #define BACKGROUND_BMP 4 /* BMP */ #define BACKGROUND_WAV 5 /* SAMP */ #define BULLET_BMP 6 /* BMP */ #define BULLET_WAV 7 /* SAMP */ #define CLICK_WAV 8 /* SAMP */ #define EXPLOSION_BMP 9 /* BMP */ #define GALATICDEFENSE_BMP 10 /* BMP */ #define PULSE_BMP 11 /* BMP */ #define PULSE_WAV 12 /* SAMP */ #define SPACESHIP_BMP 13 /* BMP */ <file_sep>/project1/spritehandler.cpp #include "spritehandler.h" spritehandler::spritehandler(void) { count = 0; } spritehandler::~spritehandler(void) { //delete the sprites for (int n = 0; n < count; n++) delete sprites[n]; } void spritehandler::add(sprite *spr) { if (spr != NULL) { sprites[count] = spr; count++; } } void spritehandler::create() { sprites[count] = new sprite(); count++; } sprite *spritehandler::get(int index) { return sprites[index]; } <file_sep>/project2/GetMeMyFruit.c // Author: <NAME> // Mappy Level Created by: <NAME> // Credits and sources in Design Document #include <stdio.h> #include <allegro.h> #include "mappyal.h" #include "GetMeMyFruit.h" #include "defines.h" // Tile Grabber BITMAP *grabframe(BITMAP *source, int width, int height, int startx, int starty, int columns, int frame) { BITMAP *temp = create_bitmap(width,height); int x = startx + (frame % columns) * width; int y = starty + (frame / columns) * height; blit(source, temp, x, y, 0, 0, width, height); return temp; } // Point collision with bounding box int inside_box(int x,int y,int left,int top,int right,int bottom) { if (x > left && x < right && y > top && y < bottom) return 1; else return 0; } // Sprite collision with shrink and bounding box int collided(SPRITE *current, SPRITE *other, int shrink) { int wa = current->x + current->width; int ha = current->y + current->height; int wb = other->x + other->width; int hb = other->y + other->height; if (inside_box(current->x, current->y, other->x+shrink, other->y+shrink, wb-shrink, hb-shrink) || inside_box(current->x, ha, other->x+shrink, other->y+shrink, wb-shrink, hb-shrink) || inside_box(wa, current->y, other->x+shrink, other->y+shrink, wb-shrink, hb-shrink) || inside_box(wa, ha, other->x+shrink, other->y+shrink, wb-shrink, hb-shrink)) { return 1; } else { return 0; } } // Mappy Collision detection int map_collided(int x, int y) { BLKSTR *blockdata; blockdata = MapGetBlock(x/mapblockwidth, y/mapblockheight); return blockdata->tl; } // Check if sprite inside of screen int inside(SPRITE* sprite) { //Is sprite visible on screen? if (sprite->y > mapyoff - FRUIT_CONSTANT && sprite->y < mapyoff + HEIGHT + FRUIT_CONSTANT) { if (sprite->x > mapxoff - FRUIT_CONSTANT && sprite->x < mapxoff + WIDTH + FRUIT_CONSTANT) { return 1; } } return 0; } // Print Insturction screen void instructions() { // Clear screen rectfill(screen, 0, 0, WIDTH, HEIGHT, BLACK); // Print game info textout_centre_ex(screen, font, "GAME INFO:", WIDTH/2, HEIGHT/4, WHITE, BLACK); textout_ex(screen, font, "- You are tasked with collecting 4 different types of fruit:", WIDTH/8, HEIGHT/4 + 20, WHITE, BLACK); textout_ex(screen, font, " - Orange", WIDTH/8, HEIGHT/4 + 30, ORANGE, BLACK); textout_ex(screen, font, " - Watermelon", WIDTH/8, HEIGHT/4 + 40, GREEN, BLACK); textout_ex(screen, font, " - Apple", WIDTH/8, HEIGHT/4 + 50, RED, BLACK); textout_ex(screen, font, " - Berries", WIDTH/8, HEIGHT/4 + 60, BLUE, BLACK); textout_ex(screen, font, "- Avoid enemies that may look like fruit, but move!", WIDTH/8, HEIGHT/4 + 70, WHITE, BLACK); textout_ex(screen, font, "- Touching an enemy will result in an instant death!", WIDTH/8, HEIGHT/4 + 80, WHITE, BLACK); textout_ex(screen, font, "- Easy gamemode will make enemies move at standard speed", WIDTH/8, HEIGHT/4 + 90, WHITE, BLACK); textout_ex(screen, font, "- Hard gamemode will make enemies move faster", WIDTH/8, HEIGHT/4 + 100, WHITE, BLACK); // Print game instructions textout_centre_ex(screen, font, "INSTRUCTIONS:", WIDTH/2, HEIGHT/2 + 40, WHITE, BLACK); textout_ex(screen, font, "1. Use the arrow keys to move your Character", WIDTH/8, HEIGHT/2 + 60, WHITE, BLACK); textout_ex(screen, font, " Use the LEFT key to move LEFT", WIDTH/8, HEIGHT/2 + 70, YELLOW, BLACK); textout_ex(screen, font, " Use the RIGHT key to move RIGHT", WIDTH/8, HEIGHT/2 + 80, YELLOW, BLACK); textout_ex(screen, font, "2. Use the SPACE bar key to JUMP", WIDTH/8, HEIGHT/2 + 90, WHITE, BLACK); textout_ex(screen, font, "3. Press Ctrl + h to bring up the instructions at any time!", WIDTH/8, HEIGHT/2 + 100, WHITE, BLACK); textout_ex(screen, font, "4. Press Ctrl + m to toggle the background music at any time!", WIDTH/8, HEIGHT/2 + 110, WHITE, BLACK); textout_ex(screen, font, "5. Press Esc to exit the game!", WIDTH/8, HEIGHT/2 + 120, WHITE, BLACK); // ENTER to return textout_centre_ex(screen, font, "Press ENTER to return", WIDTH/2, HEIGHT/2 + 200, WHITE, BLACK); // Slow down game rest(250); // Check input from user while(1) { if (key[KEY_ENTER]) { play_sample(click_sound, 128, 128, 1000, FALSE); break; } // Background music toggle if (key[KEY_LCONTROL] && key[KEY_M]) { if (sound == 1) { sound = 0; stop_sample(background_music); } else { sound = 1; play_sample(background_music, 128, 128, 1000, TRUE); } rest(80); } if (key[KEY_ESC]) { allegro_exit(); exit(0); } } } // Get Game menu input int getmenuinput() { // If user quits game if (key[KEY_ESC]) { allegro_exit(); exit(0); } // Move cursor for selection // Play sound for each movement if (key[KEY_DOWN] && selection != max_selection) { play_sample(click_sound, 128, 128, 1000, FALSE); rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + selection * 15 + 81, WIDTH/3 + 9, HEIGHT/2 + selection * 15 + 89, BLACK); selection++; rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + selection * 15 + 81, WIDTH/3 + 9, HEIGHT/2 + selection * 15 + 89, WHITE); } else if (key[KEY_UP] && selection != 0) { play_sample(click_sound, 128, 128, 1000, FALSE); rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + selection * 15 + 81, WIDTH/3 + 9, HEIGHT/2 + selection * 15 + 89, BLACK); selection--; rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + selection * 15 + 81, WIDTH/3 + 9, HEIGHT/2 + selection * 15 + 89, WHITE); } else if (key[KEY_ENTER]) { play_sample(click_sound, 128, 128, 1000, FALSE); return -1; } } // Print the welcome screen menu void welcome_screen() { // Blit the title blit(title, screen, 0, 0, 65, 50, title->w, title->h); // Options and insturctions textout_centre_ex(screen, font, "Press use your ARROW KEYS and ENTER to select an option!", WIDTH/2, HEIGHT/2 + 40, WHITE, BLACK); rect(screen, WIDTH/3, HEIGHT/2 + 80 , WIDTH/3 + 10, HEIGHT/2 + 90, WHITE); textout_ex(screen, font, "Start!", WIDTH/3 + 25, HEIGHT/2 + 82, WHITE, BLACK); rect(screen, WIDTH/3, HEIGHT/2 + 95, WIDTH/3 + 10, HEIGHT/2 + 105, WHITE); textout_ex(screen, font, "Instructions", WIDTH/3 + 25, HEIGHT/2 + 97, WHITE, BLACK); rect(screen, WIDTH/3, HEIGHT/2 + 110, WIDTH/3 + 10, HEIGHT/2 + 120, WHITE); textout_ex(screen, font, "Gamemode:", WIDTH/3 + 25, HEIGHT/2 + 112, WHITE, BLACK); selection = 0; rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + 81, WIDTH/3 + 9, HEIGHT/2 + 89, WHITE); // Check if user selects Hard or Easy mode if (hardmode == 0) { textout_ex(screen, font, "Easy", WIDTH/3 + 100, HEIGHT/2 + 112, YELLOW, BLACK); } else { textout_ex(screen, font, "Hard", WIDTH/3 + 100, HEIGHT/2 + 112, YELLOW, BLACK); } } // Draw initial start screen instructions void draw_startscreen() { // Run welcome screen print welcome_screen(); // Check for user input and update for user selection while (1) { if (getmenuinput() == -1) { if (selection == 0) { break; } else if (selection == 1) { instructions(); rectfill(screen, 0, 0, WIDTH, HEIGHT, BLACK); welcome_screen(); } else { hardmode = (hardmode + 1) % 2; if (hardmode == 0) { textout_ex(screen, font, "Easy", WIDTH/3 + 100, HEIGHT/2 + 112, YELLOW, BLACK); } else { textout_ex(screen, font, "Hard", WIDTH/3 + 100, HEIGHT/2 + 112, YELLOW, BLACK); } } } // Slow game down rest(100); } } // Setup initial files void setupscreen() { // Load title screen w/ Error checking title = (BITMAP *) data[GETMEMYFRUIT_BMP].dat; if (!title) { allegro_message("Error loading title screen"); return; } // Load sound files background_music = (SAMPLE *) data[BACKGROUND_WAV].dat; click_sound = (SAMPLE *) data[CLICK_WAV].dat; jump_sound = (SAMPLE *) data[BOING_WAV].dat; fruit_collect_sound = (SAMPLE *) data[FANFARE_WAV].dat; enemy_die_sound = (SAMPLE *) data[PLUCK_WAV].dat; game_over_sound = (SAMPLE *) data[SHUT_OFF_WAV].dat; splash_sound = (SAMPLE *) data[SPLASH_WAV].dat; game_win_sound = (SAMPLE *) data[YAY_WAV].dat; //install a digital sound driver if (install_sound(DIGI_AUTODETECT, MIDI_NONE, "") != 0) { allegro_message("Error initalizing sound system"); return; } // Check if sound files loaded if (!background_music || !click_sound || !jump_sound || !fruit_collect_sound || !enemy_die_sound || !game_over_sound || !splash_sound || !game_win_sound) { allegro_message("Error reading wave files"); return; } //load level if (MapLoad(GAME_WORLD)) { allegro_message("Error loading map"); return; } //create the double buffer buffer = create_bitmap(WIDTH, HEIGHT); clear(buffer); // Draw start screen draw_startscreen(); } // Setup game void setupgame() { // Loop variable int i, j; // Temporary variables BITMAP *temp; // Play Background music play_sample(background_music, 128, 128, 1000, TRUE); //Setup Player player_image[0] = (BITMAP *) data[CHARACTER_WAIT1_BMP].dat; player_image[1] = (BITMAP *) data[CHARACTER_WAIT2_BMP].dat; player_image[2] = (BITMAP *) data[CHARACTER_WALK1_BMP].dat; player_image[3] = (BITMAP *) data[CHARACTER_WALK2_BMP].dat; player_image[4] = (BITMAP *) data[CHARACTER_JUMP_BMP].dat; // Error checking if (!player_image[0] || !player_image[1] || !player_image[2] || !player_image[3] || !player_image[4]) { allegro_message("Error loading fruit sprites"); return; } // Player Sprite Setup player = malloc(sizeof(SPRITE)); player->x = START_POINT_X; player->y = START_POINT_Y; player->curframe= 0; player->framecount= 0; player->framedelay= FRAME_DELAY; player->maxframe= PLAYER_MAX_FRAME; player->width= player_image[0]->w; player->height= player_image[0]->h; player->alive = 1; // Setup Fruit fruits_image[0] = (BITMAP *) data[ORANGE_BMP].dat; fruits_image[1] = (BITMAP *) data[WATERMELON_BMP].dat; fruits_image[2] = (BITMAP *) data[APPLE_BMP].dat; fruits_image[3] = (BITMAP *) data[BERRIES_BMP].dat; // Error checking if (!fruits_image[0] || !fruits_image[1] || !fruits_image[2] || !fruits_image[3]) { allegro_message("Error loading fruit sprites"); return; } // Fruit allocation for (i = 0; i < FRUIT_MAX; i++) { fruits[i] = malloc(sizeof(SPRITE)); } // Setup fruit sprite locations fruits[0]->x = mapblockwidth; fruits[0]->y = mapblockheight * 3; fruits[0]->width = fruits_image[0]->w; fruits[0]->height = fruits_image[0]->h; fruits[0]->data = 0; fruits[0]->alive = 1; fruits[1]->x = mapblockwidth * 3; fruits[1]->y = mapblockheight * 26; fruits[1]->width = fruits_image[1]->w; fruits[1]->height = fruits_image[1]->h; fruits[1]->data = 1; fruits[1]->alive = 1; fruits[2]->x = mapblockwidth * 116; fruits[2]->y = mapblockheight * 7; fruits[2]->width = fruits_image[2]->w; fruits[2]->height = fruits_image[2]->h; fruits[2]->data = 2; fruits[2]->alive = 1; fruits[3]->x = mapblockwidth * 118; fruits[3]->y = mapblockheight * 26; fruits[3]->width = fruits_image[3]->w; fruits[3]->height = fruits_image[3]->h; fruits[3]->data = 3; fruits[3]->alive = 1; // Load green enemy temp = (BITMAP *) data[ENEMIES1_BMP].dat; // Error checking if (!temp) { allegro_message("Error loading enemy sprites"); return; } // Grabbing sprite frames for (i = 0; i < 6; i++) { green_enemy_image[i] = grabframe(temp, 16, 16, 0, 0, 6, i); } // Load green enemy temp = (BITMAP *) data[ENEMIES2_BMP].dat; // Error checking if (!temp) { allegro_message("Error loading enemy sprites"); return; } // Grabbing sprite frames for (i = 0; i < 6; i++) { orange_enemy_image[i] = grabframe(temp, 16, 16, 0, 0, 6, i); } // Load green enemy temp = (BITMAP *) data[ENEMIES3_BMP].dat; // Error checking if (!temp) { allegro_message("Error loading enemy sprites"); return; } // Grabbing sprite frames for (i = 0; i < 6; i++) { red_enemy_image[i] = grabframe(temp, 16, 16, 0, 0, 6, i); } // Load green enemy temp = (BITMAP *) data[ENEMIES4_BMP].dat; // Error checking if (!temp) { allegro_message("Error loading enemy sprites"); return; } // Grabbing sprite frames for (i = 0; i < 7; i++) { blue_enemy_image[i] = grabframe(temp, 16, 16, 0, 0, 6, i); } // Initalize enemies green_enemy = malloc(sizeof(SPRITE)); green_enemy->x = ENEMY1_START_X; green_enemy->y = ENEMY1_START_Y; green_enemy->min_x = ENEMY1_START_X; green_enemy->max_x = ENEMY1_END_X; green_enemy->dir = 1; green_enemy->curframe= 0; green_enemy->framecount= 0; green_enemy->framedelay= FRAME_DELAY_ENEMY; green_enemy->maxframe= 5; green_enemy->width= green_enemy_image[0]->w; green_enemy->height= green_enemy_image[0]->h; green_enemy->alive = 1; orange_enemy = malloc(sizeof(SPRITE)); orange_enemy->x = ENEMY2_START_X; orange_enemy->y = ENEMY2_START_Y; orange_enemy->min_x = ENEMY2_START_X; orange_enemy->max_x = ENEMY2_END_X; orange_enemy->dir = 1; orange_enemy->curframe= 0; orange_enemy->framecount= 0; orange_enemy->framedelay= FRAME_DELAY_ENEMY; orange_enemy->maxframe= 5; orange_enemy->width= orange_enemy_image[0]->w; orange_enemy->height= orange_enemy_image[0]->h; orange_enemy->alive = 1; red_enemy = malloc(sizeof(SPRITE)); red_enemy->x = ENEMY3_END_X; red_enemy->y = ENEMY3_START_Y; red_enemy->min_x = ENEMY3_START_X; red_enemy->max_x = ENEMY3_END_X; red_enemy->dir = -1; red_enemy->curframe= 0; red_enemy->framecount= 0; red_enemy->framedelay= FRAME_DELAY_ENEMY; red_enemy->maxframe= 5; red_enemy->width= red_enemy_image[0]->w; red_enemy->height= red_enemy_image[0]->h; red_enemy->alive = 1; blue_enemy = malloc(sizeof(SPRITE)); blue_enemy->x = ENEMY4_END_X; blue_enemy->y = ENEMY4_START_Y; blue_enemy->min_x = ENEMY4_START_X; blue_enemy->max_x = ENEMY4_END_X; blue_enemy->dir = -1; blue_enemy->curframe= 0; blue_enemy->framecount= 0; blue_enemy->framedelay= FRAME_DELAY_ENEMY; blue_enemy->maxframe= 5; blue_enemy->width= blue_enemy_image[0]->w; blue_enemy->height= blue_enemy_image[0]->h; blue_enemy->alive = 1; } // Player walking position and animation update void walk(int dir) { // Find direction and move accordingly facing = dir; player->x+= 2 * dir; // Animate Player w/ Delay if (++player->framecount > player->framedelay) { player->framecount=0; if (player->curframe > WALKFRAME_MAX || player->curframe < WALKFRAME_MIN) { player->curframe = WALKFRAME_MIN; } if (++player->curframe > WALKFRAME_MAX) { player->curframe=WALKFRAME_MIN; } } } // Enemy walking position and animation update void walk_enemies(SPRITE *enemy) { // Generate random number int random = rand() % 30; if (fruit_collected > 0) { if (random == 0) { enemy->dir = enemy->dir * - 1; } } if (fruit_collected > 1) { int xdifference = player->x - enemy->x; int ydifference = player->y - enemy->y; if (abs(xdifference) < 75 && abs(ydifference) < 50) { if (xdifference > 0) { enemy->dir = 1; } else { enemy->dir = -1; } } } // Check if speed should be fast or not if (hardmode == 1) { enemy->x+= HARD_MODE * enemy->dir; } else { enemy->x+= EASY_MODE * enemy->dir; } if (fruit_collected > 2) { enemy->x+= enemy->dir; } // Turning point of enemy movement if (enemy->x > enemy->max_x || enemy->x < enemy->min_x) { enemy->dir = enemy->dir * -1; if (enemy->x > enemy->max_x) { enemy->x = enemy->max_x; } if (enemy->x < enemy->min_x) { enemy->x = enemy->min_x; } } // Frame delay animation if (++enemy->framecount > enemy->framedelay) { enemy->framecount=0; if (++enemy->curframe > enemy->maxframe) { enemy->curframe = 0; } } } // Update Enemies void update_enemies() { // Position variables int x1,y1,x2,y2; // Player coordinates x1 = player->x; y1 = player->y; x2 = x1 + player->width; y2 = y1 + player->height; // Draw enemies if (green_enemy->alive == 1) { // Update enemy position and animation walk_enemies(green_enemy); // Get enemy bounding rectangle if (inside_box(green_enemy->x + green_enemy->width/2, green_enemy->y + green_enemy->height/2, x1, y1, x2, y2)) { play_sample(enemy_die_sound, 128, 128, 1000, FALSE); player->alive = 0; gameover = 1; } // Check if within screen to draw if (inside(green_enemy)) { if (green_enemy->dir == -1) { draw_sprite(buffer, green_enemy_image[green_enemy->curframe], green_enemy->x - mapxoff, green_enemy->y - mapyoff); } else { draw_sprite_h_flip(buffer, green_enemy_image[green_enemy->curframe], green_enemy->x - mapxoff, green_enemy->y - mapyoff); } } } if (red_enemy->alive == 1) { // Update enemy position and animation walk_enemies(red_enemy); //get enemy bounding rectangle if (inside_box(red_enemy->x + red_enemy->width/2, red_enemy->y + red_enemy->height/2, x1, y1, x2, y2)) { play_sample(enemy_die_sound, 128, 128, 1000, FALSE); player->alive = 0; gameover = 1; } // Check if within screen to draw if (inside(red_enemy)) { if (red_enemy->dir == -1) { draw_sprite(buffer, red_enemy_image[red_enemy->curframe], red_enemy->x - mapxoff, red_enemy->y - mapyoff); } else { draw_sprite_h_flip(buffer, red_enemy_image[red_enemy->curframe], red_enemy->x - mapxoff, red_enemy->y - mapyoff); } } } if (orange_enemy->alive == 1) { // Update enemy position and animation walk_enemies(orange_enemy); //get enemy bounding rectangle if (inside_box(orange_enemy->x + orange_enemy->width/2, orange_enemy->y + orange_enemy->height/2, x1, y1, x2, y2)) { play_sample(enemy_die_sound, 128, 128, 1000, FALSE); player->alive = 0; gameover = 1; } // Check if within screen to draw if (inside(orange_enemy)) { if (orange_enemy->dir == -1) { draw_sprite(buffer, orange_enemy_image[orange_enemy->curframe], orange_enemy->x - mapxoff, orange_enemy->y - mapyoff); } else { draw_sprite_h_flip(buffer, orange_enemy_image[orange_enemy->curframe], orange_enemy->x - mapxoff, orange_enemy->y - mapyoff); } } } if (blue_enemy->alive == 1) { // Update enemy position and animation walk_enemies(blue_enemy); //get enemy bounding rectangle if (inside_box(blue_enemy->x + blue_enemy->width/2, blue_enemy->y + blue_enemy->height/2, x1, y1, x2, y2)) { play_sample(enemy_die_sound, 128, 128, 1000, FALSE); player->alive = 0; gameover = 1; } // Check if within screen to draw if (inside(blue_enemy)) { if (blue_enemy->dir == -1) { draw_sprite(buffer, blue_enemy_image[blue_enemy->curframe], blue_enemy->x - mapxoff, blue_enemy->y - mapyoff); } else { draw_sprite_h_flip(buffer, blue_enemy_image[blue_enemy->curframe], blue_enemy->x - mapxoff, blue_enemy->y - mapyoff); } } } } // Player wait animation void wait() { // Update Player animation w/ delay if (++player->framecount > player->framedelay) { player->framecount=0; if (player->curframe > WAITFRAME_MAX || player->curframe < WAITFRAME_MIN) { player->curframe = WAITFRAME_MIN; } else if (++player->curframe > WAITFRAME_MAX) { player->curframe = WAITFRAME_MIN; } } } // General update function void update() { // Loop variable int i; // Position variables int x1,y1,x2,y2; // Old coordinates oldpy = player->y; oldpx = player->x; // Handle jumping if (jump==JUMPIT) { if (!map_collided(player->x + player->width/2, player->y + player->height + 5)) jump = 0; } else { player->curframe = JUMPFRAME; player->y -= jump/3; jump--; } if (jump<0) { if (map_collided(player->x + player->width/2, player->y + player->height)) { jump = JUMPIT; while (map_collided(player->x + player->width/2, player->y + player->height)) player->y -= 2; } } // Check for collided with foreground tiles if (facing == -1) { if (map_collided(player->x, player->y + player->height)) player->x = oldpx; } else { if (map_collided(player->x + player->width, player->y + player->height)) player->x = oldpx; } // Update the map scroll position mapxoff = player->x + player->width/2 - WIDTH/2 + 10; mapyoff = player->y + player->height/2 - HEIGHT/2 + 10; // Avoid moving beyond the map edge if (mapxoff < 0) { mapxoff = 0; } if (mapxoff > (mapwidth * mapblockwidth - WIDTH)) { mapxoff = mapwidth * mapblockwidth - WIDTH; } if (mapyoff < 0) { mapyoff = 0; } if (mapyoff > (mapheight * mapblockheight - HEIGHT)) { mapyoff = mapheight * mapblockheight - HEIGHT; } // Avoid player moving beyoard map edge (left and right) if (player->x < 0) { player->x = 0; } if (player->x > (mapwidth * mapblockwidth - player->width)) { player->x = (mapwidth * mapblockwidth - player->width); } if ((player->y + player->height) > (mapheight * mapblockheight - (mapblockheight / 2))) { play_sample(splash_sound, 128, 128, 1000, FALSE); gameover = 1; return; } if (player->y < 0) { player->y = 0; } if (oldpy == player->y & oldpx == player->x) { waitcount++; if (waitcount > WAITCOUNT_MAX) { wait(); waitcount = 0; } } else { waitcount = 0; } // Draw the background tiles MapDrawBG(buffer, mapxoff, mapyoff, 0, 0, WIDTH-1, HEIGHT-1); // Draw foreground tiles MapDrawFG(buffer, mapxoff, mapyoff, 0, 0, WIDTH-1, HEIGHT-1, 0); // Fruit Collection Status rect(buffer, WIDTH - 156, 1, WIDTH - 4, 41, BLACK); rect(buffer, WIDTH - 155, 2, WIDTH - 5, 40, BLACK); textout_ex(buffer, font, "FRUIT COLLECTED: ", WIDTH - 150, 5, BLACK, -1); // Player coordinates x1 = player->x; y1 = player->y; x2 = x1 + player->width; y2 = y1 + player->height; // Draw fruit for (i = 0; i < FRUIT_MAX; i++) { if (fruits[i]->alive == 1) { //get fruit bounding rectangl if (inside_box(fruits[i]->x + fruits[i]->width/2, fruits[i]->y + fruits[i]->height/2, x1, y1, x2, y2)) { play_sample(fruit_collect_sound, 128, 128, 1000, FALSE); fruits[i]->alive = 0; fruit_collected++; } if (inside(fruits[i])) { draw_sprite(buffer, fruits_image[i], fruits[i]->x - mapxoff, fruits[i]->y - mapyoff); } } else { draw_sprite(buffer, fruits_image[i], WIDTH - 125 + 25 * i, 15); } } // Update enemies update_enemies(); // Draw the player's sprite if (facing == 1) { if (player->y > player->width * -1) { draw_sprite(buffer, player_image[player->curframe], (player->x-mapxoff), (player->y-mapyoff+1)); } } else { if (player->y > player->width * -1) { draw_sprite_h_flip(buffer, player_image[player->curframe], (player->x-mapxoff), (player->y-mapyoff)); } } // Update sound cooldown if (sound_cooldown > 0) { sound_cooldown--; } } // Get game input from user void getinput() { //hit ESC to quit if (key[KEY_ESC]) { allegro_exit(); exit(0); } // Instruction screen if (key[KEY_LCONTROL] && key[KEY_H]) { instructions(); } // Background music toggle if (key[KEY_LCONTROL] && key[KEY_M]) { if (sound_cooldown == 0) { sound_cooldown = COOLDOWN; if (sound == 1) { sound = 0; stop_sample(background_music); } else { sound = 1; play_sample(background_music, 128, 128, 1000, TRUE); } } } //ARROW KEYS AND SPACE BAR CONTROL if (key[KEY_LEFT]) { walk(-1); } else if (key[KEY_RIGHT]) { walk(1); } if (key[KEY_SPACE]) { if (jump==JUMPIT) { play_sample(jump_sound, 128, 128, 1000, FALSE); jump = 30; } } } int main(void) { // Looping variable int i; //initialize Allegro allegro_init(); //initialize the keyboard install_keyboard(); //initalize timer install_timer(); //initialize random seed srand(time(NULL)); // Set Video mode set_color_depth(16); // Error variable int ret; // Graphics Error checking ret = set_gfx_mode(MODE, WIDTH, HEIGHT, 0, 0); if (ret != 0) { allegro_message(allegro_error); return; } //load the datfile data = load_datafile("data.dat"); // Setup screen setupscreen(); setupgame(); // Main loop while (!gameover) { // Check for keypresses if (keypressed()) { getinput(); } // Update update(); // Check win condition if (fruit_collected == 4) { win = 1; gameover = 1; } // Blit the double buffer vsync(); acquire_screen(); blit(buffer, screen, 0, 0, 0, 0, WIDTH-1, HEIGHT-1); release_screen(); rest(10); } // Clear Screen rectfill(screen, 0, 0, WIDTH, HEIGHT, BLACK); // Stop background stop_sample(background_music); // Print final result w/ Sound if (win == 1) { play_sample(game_win_sound, 128, 128, 1000, FALSE); textout_centre_ex(screen, font, "Congratulations! You have collected all the fruit!", WIDTH/2, HEIGHT/2, WHITE, BLACK); } else { play_sample(game_over_sound, 128, 128, 1000, FALSE); textprintf_centre_ex(screen, font, WIDTH/2, HEIGHT/2, WHITE, BLACK, "Sorry you have only collected %i fruit. Please try again!", fruit_collected); } textout_centre_ex(screen, font, "Please Press ESC to QUIT!", WIDTH/2, HEIGHT/2 + 20, WHITE, BLACK); // Slow down game rest(250); // Wait until user exits game while(!key[KEY_ESC]) { }; // Cleanup free(player); free(red_enemy); free(orange_enemy); free(blue_enemy); free(green_enemy); destroy_bitmap(buffer); destroy_bitmap(title); destroy_bitmap(blue_enemy_image[6]); for (i = 0; i < PLAYER_MAX_FRAME; i++) { destroy_bitmap(player_image[i]); } for (i = 0; i < FRUIT_MAX; i++) { destroy_bitmap(fruits_image[i]); free(fruits[i]); } for (i = 0; i < 6; i++) { destroy_bitmap(orange_enemy_image[i]); destroy_bitmap(red_enemy_image[i]); destroy_bitmap(blue_enemy_image[i]); destroy_bitmap(green_enemy_image[i]); } destroy_sample(background_music); destroy_sample(click_sound); destroy_sample(jump_sound); destroy_sample(fruit_collect_sound); destroy_sample(enemy_die_sound); destroy_sample(game_over_sound); destroy_sample(splash_sound); destroy_sample(game_win_sound); MapFreeMem(); allegro_exit(); return 0; } END_OF_MAIN() <file_sep>/project1/sprite.cpp #include <allegro.h> #include "sprite.h" sprite::sprite() { image = NULL; image2 = NULL; image3 = NULL; health = 0; alive = 0; direction = 0; animcolumns = 0; animstartx = 0; animstarty = 0; x = 0.0f; y = 0.0f; pointer_x = 0.0f; pointer_y = 0.0f; width = 0; height = 0; xdelay = 0; ydelay = 0; xcount = 0; ycount = 0; velx = 0.0; vely = 0.0; speed = 0.0; curframe = 0; totalframes = 1; framecount = 0; framedelay = 10; animdir = 1; faceAngle = 0; moveAngle = 0; } sprite::~sprite() { //remove bitmap from memory if (image != NULL) destroy_bitmap(image); } int sprite::load(BITMAP * bitmap_image) { image = bitmap_image; if (image == NULL) return 0; width = image->w; height = image->h; return 1; } int sprite::load2(BITMAP * bitmap_image) { image2 = bitmap_image; if (image2 == NULL) return 0; width = image->w; height = image->h; return 1; } int sprite::load3(BITMAP * bitmap_image) { image3 = bitmap_image; if (image3 == NULL) return 0; width = image->w; height = image->h; return 1; } void sprite::draw(BITMAP *dest) { draw_sprite(dest, image, (int)x, (int)y); } void sprite::drawframe(BITMAP *dest) { int fx = animstartx + (curframe % animcolumns) * width; int fy = animstarty + (curframe / animcolumns) * height; masked_blit(image,dest,fx,fy,(int)x,(int)y,width,height); } void sprite::updatePosition() { //update x position if (++xcount > xdelay) { xcount = 0; x += velx; } //update y position if (++ycount > ydelay) { ycount = 0; y += vely; } } void sprite::updateAnimation() { //update frame based on animdir if (++framecount > framedelay) { framecount = 0; curframe += animdir; if (curframe < 0) { curframe = totalframes-1; } if (curframe > totalframes-1) { curframe = 0; } } } int sprite::inside(int x,int y,int left,int top,int right,int bottom) { if (x > left && x < right && y > top && y < bottom) return 1; else return 0; } int sprite::pointInside(int px,int py) { return inside(px, py, (int)x, (int)y, (int)x+width, (int)y+height); } int sprite::collided(sprite *other, int shrink) { int wa = (int)x + width; int ha = (int)y + height; int wb = (int)other->x + other->width; int hb = (int)other->y + other->height; if (inside((int)x, (int)y, (int)other->x+shrink, (int)other->y+shrink, wb-shrink, hb-shrink) || inside((int)x, ha, (int)other->x+shrink, (int)other->y+shrink, wb-shrink, hb-shrink) || inside(wa, (int)y, (int)other->x+shrink, (int)other->y+shrink, wb-shrink, hb-shrink) || inside(wa, ha, (int)other->x+shrink, (int)other->y+shrink, wb-shrink, hb-shrink)) return 1; else return 0; } <file_sep>/project1/GalacticDefense.h // Pocket Trivia // <NAME> #include "spritehandler.h" #ifndef _GALACTICDEFENSE_H #define _GALACTICDEFENSE_H #define BLACK makecol(0,0,0) #define WHITE makecol(255,255,255) #define YELLOW makecol(255,216,0) #define RED makecol(255,0,0) #define ORANGE makecol(255,127.5,0) #define BLUE makecol(0,191,255) #define PI 3.1415926535 #define ACCELERATION 0.1f #define STEP 3 #define NUM 20 #define WIDTH 800 #define HEIGHT 600 #define MODE GFX_AUTODETECT_WINDOWED #define CHAR_PER_LENGTH 8 #define BULLET_CAP 15 #define BULLETSPEED 6 #define BULLETCOOLDOWN 10; #define SMALLASTEROID_COUNT 7 #define LARGEASTEROID_COUNT 3 #define ASTEROID_COUNT SMALLASTEROID_COUNT + LARGEASTEROID_COUNT #define ASTEROID_SPEED #define PULSE_DURATION 10 #define PULSE_COOLDOWN 100 #define DATA_FILE "data.dat" // Gameover variable int gameover = 0; int bullet_index = 0; int bullet_cooldown = 0; int score = 0; int hardmode = 0; int selection = 0; int max_selection = 2; int active_pulse = 0; int pulse_cooldown = 0; int sound = 1; int done = 0; //create a back buffer BITMAP *title; BITMAP *buffer; BITMAP *background; BITMAP *explosion; SAMPLE *background_music; SAMPLE *click_sound; SAMPLE *bullet_sound; SAMPLE *pulse_sound; sprite *pulse; sprite *spaceship; spritehandler *bullets; spritehandler *asteroids; DATAFILE *data; // Print in correct format void print_formated(const char* text, int x1, int x2, int y, int col, int bg); // Print insturction screen void instructions(); // Get Game menu input int getmenuinput(); // Print the welcome screen menu void welcome_screen(); // Draw initial start screen instructions void draw_startscreen(); //calculate X movement value based on direction angle double calcAngleMoveX(int angle); //calculate Y movement value based on direction angle double calcAngleMoveY(int angle); // Warp sprite if reaches end of screen void warpsprite(sprite *spr); // Respawn asteroid if destoryed void restart_asteroid(int num); // Check collisions with other asteroids. Only in hard mode void checkcollisions_asteroid(int num); // Check if bullet collided with any asteroids void checkcollisions_bullet(int num); // Check collisions with ship void checkcollisions_ship(); // Active pulse feature void activate_pulse(); // Used to move ship forward or backwards void thrusters(int dir); // Turn ship left void turnleft(); // Turn ship right void turnright(); // Fire weapon void fireweapon(); // Update bullet void updatebullet(int num); // Update asteroid void updateasteroid(int num); // Update health bar void updatehealth(); // Update pulse cooldown bar void updatepulse(); // Main update function void update(); // Get game input from user void getinput(); // Setup initial files void setupscreen(); // Setup game void setupgame(); #endif <file_sep>/project1/GalacticDefense.cpp // Author: <NAME> #include <pthread.h> #include <stdio.h> #include <allegro.h> #include "math.h" #include "sprite.h" #include "GalacticDefense.h" #include "spritehandler.h" #include "defines.h" //create a new thread mutex to protect variables pthread_mutex_t threadsafe = PTHREAD_MUTEX_INITIALIZER; // Print in correct format void print_formated(const char* text, int x1, int x2, int y, int col, int bg) { // Buffer and initial variables char line[256]; int end_position = strcspn(text, "\0"); int current_y = y; int length = x2 - x1; // Check if we need to format if ((end_position * CHAR_PER_LENGTH) > length) { // Inital variables int start = 0; int end; int curr_space = 0; int next_space = 0; // Cycle through spaces and print on next line if doesn't fit while(next_space < end_position - 1) { next_space += strcspn(&text[curr_space], " ") + 1; if (((next_space - start) * CHAR_PER_LENGTH) < length) { curr_space = next_space; } else { strncpy(line, &text[start], curr_space - start); strncpy(&line[curr_space - 1 - start], "\0", 1); textprintf_ex(screen, font, x1, y, col, bg, "%s", line); start = curr_space; y += 10; } } strncpy(line, &text[start], end_position - start); strncpy(&line[end_position - start], "\0", 1); textprintf_ex(screen, font, x1, y, col, bg, "%s", line); } else { textprintf_ex(screen, font, x1, y, col, bg, "%s", text); } } // Print insturction screen void instructions() { // Clear screen rectfill(screen, 0, 0, WIDTH, HEIGHT, BLACK); // Print game info textout_centre_ex(screen, font, "GAME INFO:", WIDTH/2, HEIGHT/4, WHITE, BLACK); textout_ex(screen, font, "- You are tasked with the defense of the Galaxy.", WIDTH/8, HEIGHT/4 + 20, WHITE, BLACK); textout_ex(screen, font, "- Your goal is to destory as much asteroids before your ship needs repairs", WIDTH/8, HEIGHT/4 + 30, WHITE, BLACK); textout_ex(screen, font, "- You can take a total of 3 hits before your ship needs repairs", WIDTH/8, HEIGHT/4 + 40, WHITE, BLACK); textout_ex(screen, font, "- Small Asteroids take 1 hit to destory. But Big Asteroids require 3 hits to destory.", WIDTH/8, HEIGHT/4 + 50, WHITE, BLACK); textout_ex(screen, font, "- Easy gamemode will allow asteroids to pass by each other in predictable movement", WIDTH/8, HEIGHT/4 + 70, WHITE, BLACK); textout_ex(screen, font, "- Hard gamemode will make asteroids have unpredictable movements due to magnetic", WIDTH/8, HEIGHT/4 + 80, WHITE, BLACK); textout_ex(screen, font, " properties of each asteroid", WIDTH/8, HEIGHT/4 + 90, WHITE, BLACK); // Print game instructions textout_centre_ex(screen, font, "INSTRUCTIONS:", WIDTH/2, HEIGHT/2 + 40, WHITE, BLACK); textout_ex(screen, font, "1. Use the arrow keys to navigate your space ship", WIDTH/8, HEIGHT/2 + 60, WHITE, BLACK); textout_ex(screen, font, " Use the UP and DOWN key to accelerate and decelerate", WIDTH/8, HEIGHT/2 + 70, YELLOW, BLACK); textout_ex(screen, font, " Use the LEFT and RIGHT key to TURN", WIDTH/8, HEIGHT/2 + 80, YELLOW, BLACK); textout_ex(screen, font, "2. Use the SPACE bar key to shoot", WIDTH/8, HEIGHT/2 + 90, WHITE, BLACK); print_formated("3. Use the 'g' key to activate a pulse that pushes all asteroids within a small area away. Make sure not to activate before asteroid is too close.", WIDTH/8, WIDTH - 10, HEIGHT/2 + 100, WHITE, BLACK); textout_ex(screen, font, "4. Press Ctrl + h to bring up the instructions at any time!", WIDTH/8, HEIGHT/2 + 120, WHITE, BLACK); textout_ex(screen, font, "5. Press Ctrl + m to toggle the background music at any time!", WIDTH/8, HEIGHT/2 + 130, WHITE, BLACK); textout_ex(screen, font, "6. Press Esc to exit the game!", WIDTH/8, HEIGHT/2 + 140, WHITE, BLACK); // ENTER to return textout_centre_ex(screen, font, "Press ENTER to return", WIDTH/2, HEIGHT/2 + 200, WHITE, BLACK); // Slow down game rest(250); // Check input from user while(1) { if (key[KEY_ENTER]) { play_sample(click_sound, 128, 128, 1000, FALSE); break; } // Background music toggle if (key[KEY_LCONTROL] && key[KEY_M]) { if (sound == 1) { sound = 0; stop_sample(background_music); } else { sound = 1; play_sample(background_music, 128, 128, 1000, TRUE); } rest(80); } if (key[KEY_ESC]) { allegro_exit(); exit(0); } } } // Get Game menu input int getmenuinput() { // If user quits game if (key[KEY_ESC]) { allegro_exit(); exit(0); } // Move cursor for selection // Play sound for each movement if (key[KEY_DOWN] && selection != max_selection) { play_sample(click_sound, 128, 128, 1000, FALSE); rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + selection * 15 + 81, WIDTH/3 + 9, HEIGHT/2 + selection * 15 + 89, BLACK); selection++; rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + selection * 15 + 81, WIDTH/3 + 9, HEIGHT/2 + selection * 15 + 89, WHITE); } else if (key[KEY_UP] && selection != 0) { play_sample(click_sound, 128, 128, 1000, FALSE); rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + selection * 15 + 81, WIDTH/3 + 9, HEIGHT/2 + selection * 15 + 89, BLACK); selection--; rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + selection * 15 + 81, WIDTH/3 + 9, HEIGHT/2 + selection * 15 + 89, WHITE); } else if (key[KEY_ENTER]) { play_sample(click_sound, 128, 128, 1000, FALSE); return -1; } } // Print the welcome screen menu void welcome_screen() { // Blit the title blit(title, screen, 0, 0, 150, 50, title->w, title->h); // Options and insturctions textout_centre_ex(screen, font, "Press use your ARROW KEYS and ENTER to select an option!", WIDTH/2, HEIGHT/2 + 40, WHITE, BLACK); rect(screen, WIDTH/3, HEIGHT/2 + 80 , WIDTH/3 + 10, HEIGHT/2 + 90, WHITE); textout_ex(screen, font, "Start!", WIDTH/3 + 25, HEIGHT/2 + 82, WHITE, BLACK); rect(screen, WIDTH/3, HEIGHT/2 + 95, WIDTH/3 + 10, HEIGHT/2 + 105, WHITE); textout_ex(screen, font, "Instructions", WIDTH/3 + 25, HEIGHT/2 + 97, WHITE, BLACK); rect(screen, WIDTH/3, HEIGHT/2 + 110, WIDTH/3 + 10, HEIGHT/2 + 120, WHITE); textout_ex(screen, font, "Gamemode:", WIDTH/3 + 25, HEIGHT/2 + 112, WHITE, BLACK); selection = 0; rectfill(screen, WIDTH/3 + 1, HEIGHT/2 + 81, WIDTH/3 + 9, HEIGHT/2 + 89, WHITE); // Check if user selects Hard or Easy mode if (hardmode == 0) { textout_ex(screen, font, "Easy", WIDTH/3 + 100, HEIGHT/2 + 112, YELLOW, BLACK); } else { textout_ex(screen, font, "Hard", WIDTH/3 + 100, HEIGHT/2 + 112, YELLOW, BLACK); } } // Draw initial start screen instructions void draw_startscreen() { // Run welcome screen print welcome_screen(); // Check for user input and update for user selection while (1) { if (getmenuinput() == -1) { if (selection == 0) { break; } else if (selection == 1) { instructions(); rectfill(screen, 0, 0, WIDTH, HEIGHT, BLACK); welcome_screen(); } else { hardmode = (hardmode + 1) % 2; if (hardmode == 0) { textout_ex(screen, font, "Easy", WIDTH/3 + 100, HEIGHT/2 + 112, YELLOW, BLACK); } else { textout_ex(screen, font, "Hard", WIDTH/3 + 100, HEIGHT/2 + 112, YELLOW, BLACK); } } } // Slow game down rest(100); } } //calculate X movement value based on direction angle double calcAngleMoveX(int angle) { return (double) cos(angle * PI / 180); } //calculate Y movement value based on direction angle double calcAngleMoveY(int angle) { return (double) sin(angle * PI / 180); } // Warp sprite if reaches end of screen void warpsprite(sprite *spr) { //simple screen warping behavior int w = spr->width; int h = spr->height; if (spr->x < 0 - w) { spr->x = SCREEN_W; } else if (spr->x > SCREEN_W) { spr->x = 0- w; } if (spr->y < 16) { spr->y = SCREEN_H; } else if (spr->y > SCREEN_H) { spr->y = 0 - h; } } // Respawn asteroid if destoryed void restart_asteroid(int num) { // Loop variables int collide; int i; // Check if respawn collides with other asteroids. If so, reposition while (1) { // Restart colision collide = 0; // Randomize placement if (rand() % 2 == 0) { if (rand() % 2 == 0) { asteroids->get(num)->x = 0; asteroids->get(num)->y = rand() % (SCREEN_H - asteroids->get(num)->height); } else { asteroids->get(num)->x = SCREEN_W - asteroids->get(num)->width; asteroids->get(num)->y = rand() % (SCREEN_H - asteroids->get(num)->height); } } else { if (rand() % 2 == 0) { asteroids->get(num)->x = rand() % (SCREEN_W - asteroids->get(num)->width); asteroids->get(num)->y = 0; } else { asteroids->get(num)->x = rand() % (SCREEN_W - asteroids->get(num)->width); asteroids->get(num)->y = SCREEN_H - asteroids->get(num)->height; } } // Check if collides with other sprites for (i = 0; i < ASTEROID_COUNT; i++) { if (i != num && asteroids->get(i)->collided(asteroids->get(num))) { collide = 1; break; } } if (collide == 0) { break; } } // Randomize speed and set to alive asteroids->get(num)->velx = (rand() % 12) - 6; asteroids->get(num)->vely = (rand() % 12) - 6; asteroids->get(num)->alive = 1; // Set health if (num >= SMALLASTEROID_COUNT) { asteroids->get(num)->health = 3; } else { asteroids->get(num)->health = 1; } } // Check collisions with other asteroids. Only in hard mode void checkcollisions_asteroid(int num) { // Loop and position variables int cx1,cy1,cx2,cy2; int i; // Loop through all asteroids for (i=0; i<ASTEROID_COUNT; i++) { // Check if current asteroid collided with others if (i != num && asteroids->get(i)->collided(asteroids->get(num))) { //calculate center of primary sprite cx1 = (int)asteroids->get(i)->x + asteroids->get(i)->width / 2; cy1 = (int)asteroids->get(i)->y + asteroids->get(i)->height / 2; //calculate center of secondary sprite cx2 = (int)asteroids->get(i)->x + asteroids->get(i)->width / 2; cy2 = (int)asteroids->get(i)->y + asteroids->get(i)->height / 2; //figure out which way the sprites collided if (cx1 <= cx2) { // Randomize in opposite directions asteroids->get(i)->velx = -1 * (rand() % 6) - 1; asteroids->get(num)->velx = rand() % 6 + 1; if (cy1 <= cy2) { asteroids->get(i)->vely = -1 * (rand() % 6) - 1; asteroids->get(num)->vely = rand() % 6 + 1; } else { asteroids->get(i)->vely = rand() % 6 + 1; asteroids->get(num)->vely = -1 * (rand() % 6) - 1; } } else { //cx1 is > cx2 asteroids->get(i)->velx = rand() % 6 + 1; asteroids->get(num)->velx = -1 * (rand() % 6) - 1; if (cy1 <= cy2) { asteroids->get(i)->vely = rand() % 6 + 1; asteroids->get(num)->vely = -1 * (rand() % 6) - 1; } else { asteroids->get(i)->vely = -1 * (rand() % 6) - 1; asteroids->get(num)->vely = rand() % 6 + 1; } } } } } // Check if bullet collided with any asteroids void checkcollisions_bullet(int num) { // Loop variable int i; // Cycle through all of the asteroids for (i=0; i<ASTEROID_COUNT; i++) { // Check if bullet collided with asteroid if (bullets->get(num)->collided(asteroids->get(i))) { // Minus asteroid health asteroids->get(i)->health--; // Check if asteroid is destoryed. if (asteroids->get(i)->health == 0) { draw_sprite(buffer, explosion, bullets->get(num)->x, bullets->get(num)->y); score += 100; asteroids->get(i)->alive = 0; } // Set bullet to dead bullets->get(num)->alive = 0; break; } } } // Check collisions with ship void checkcollisions_ship() { // Loop variable int i; // Check if pulse is active (no injury) if (active_pulse == 0) { // Cycle through all asteroids for (i=0; i<ASTEROID_COUNT; i++) { // Check if collided with asteroid if (spaceship->collided(asteroids->get(i))) { // Subtract health, destory asteroid and check if game over spaceship->health -= 1; asteroids->get(i)->alive = 0; if (spaceship->health == 0) { spaceship->alive = 0; gameover = 1; } } } } } // Active pulse feature void activate_pulse() { // Loop variable int i; // Set pulse to where the ship is pulse->x = spaceship->x + spaceship->width/2 - pulse->image->w/2; pulse->y = spaceship->y + spaceship->height/2 - pulse->image->h/2; // Draw the pulse draw_sprite(buffer, pulse->image, pulse->x, pulse->y); // Cycle through all of the asteroids. If collides, send in opposite direction for (i=0; i<ASTEROID_COUNT; i++) { if (pulse->collided(asteroids->get(i), 0)) { asteroids->get(i)->velx = asteroids->get(i)->velx * -1; asteroids->get(i)->vely = asteroids->get(i)->vely * -1; asteroids->get(i)->updatePosition(); asteroids->get(i)->updatePosition(); asteroids->get(i)->updatePosition(); asteroids->get(i)->updatePosition(); asteroids->get(i)->updatePosition(); asteroids->get(i)->updatePosition(); } } } // Used to move ship forward or backwards void thrusters(int dir) { //shift 0-degree orientation from right-face to up-face spaceship->moveAngle = spaceship->faceAngle - 90; //convert negative angle to wraparound if (spaceship->moveAngle < 0) spaceship->moveAngle = 359 + spaceship->moveAngle; //adjust velocity based on angle if (dir == 1) { spaceship->velx += calcAngleMoveX(spaceship->moveAngle) * ACCELERATION; spaceship->vely += calcAngleMoveY(spaceship->moveAngle) * ACCELERATION; } else { spaceship->velx -= calcAngleMoveX(spaceship->moveAngle) * ACCELERATION; spaceship->vely -= calcAngleMoveY(spaceship->moveAngle) * ACCELERATION; } //keep velocity down to a reasonable speed if (spaceship->velx > 4.0) { spaceship->velx = 4.0; } if (spaceship->velx < -4.0) { spaceship->velx = -4.0; } if (spaceship->vely > 4.0) { spaceship->vely = 4.0; } if (spaceship->vely < -4.0) { spaceship->vely = -4.0; } } // Turn ship left void turnleft() { // Alter angle spaceship->faceAngle -= STEP; if (spaceship->faceAngle < 0) { spaceship->faceAngle = 359; } } // Turn ship right void turnright() { // Alter angle spaceship->faceAngle += STEP; if (spaceship->faceAngle > 359) { spaceship->faceAngle = 0; } } // Fire weapon void fireweapon() { // Play sound play_sample(bullet_sound, 128, 128, 1000, FALSE); // Set bullet position and angle bullets->get(bullet_index)->x = spaceship->pointer_x - (bullets->get(bullet_index)->width / 2); bullets->get(bullet_index)->y = spaceship->pointer_y - (bullets->get(bullet_index)->height / 2); bullets->get(bullet_index)->faceAngle = spaceship->faceAngle; //shift 0-degree orientation from right-face to up-face bullets->get(bullet_index)->moveAngle = bullets->get(bullet_index)->faceAngle - 90; //convert negative angle to wraparound if (bullets->get(bullet_index)->moveAngle < 0) { bullets->get(bullet_index)->moveAngle = 359 + bullets->get(bullet_index)->moveAngle; } // Calculate velocity and set alive bullets->get(bullet_index)->velx = calcAngleMoveX(bullets->get(bullet_index)->moveAngle) * BULLETSPEED; bullets->get(bullet_index)->vely = calcAngleMoveY(bullets->get(bullet_index)->moveAngle) * BULLETSPEED; bullets->get(bullet_index)->alive = 1; // Cycle bullets bullet_index++; if (bullet_index > BULLET_CAP - 1) { bullet_index = 0; } // Set cooldown bullet_cooldown = BULLETCOOLDOWN; } // Update bullet void updatebullet(int num) { // Temp position variables int x, y, tx, ty; //move the bullet bullets->get(num)->updatePosition(); x = bullets->get(num)->x; y = bullets->get(num)->y; //stay within the screen if (x < 6 || x > SCREEN_W-6 || y < 20 || y > SCREEN_H-6) { bullets->get(num)->alive = 0; return; } // Check if collide with asteroid checkcollisions_bullet(num); // Draw bullet if alive if (bullets->get(num)->alive) { rotate_sprite(buffer, bullets->get(num)->image, (int)bullets->get(num)->x, bullets->get(num)->y, itofix((int)(bullets->get(num)->faceAngle / 0.7f / 2.0f))); } } // Update asteroid void updateasteroid(int num) { // Draw correct sprite based on health and index if (asteroids->get(num)->health == 3 || num < SMALLASTEROID_COUNT) { draw_sprite(buffer, asteroids->get(num)->image, (int)asteroids->get(num)->x, asteroids->get(num)->y); } else if (asteroids->get(num)->health == 2) { draw_sprite(buffer, asteroids->get(num)->image2, (int)asteroids->get(num)->x, asteroids->get(num)->y); } else { draw_sprite(buffer, asteroids->get(num)->image3, (int)asteroids->get(num)->x, asteroids->get(num)->y); } //move the asteroid asteroids->get(num)->updatePosition(); // Check if hardmode for collision is active if (hardmode == 1) { checkcollisions_asteroid(num); } // Warp asteroid warpsprite(asteroids->get(num)); } // Update health bar void updatehealth() { // Health outline rect(buffer, 60, 2, 90, 14, RED); rect(buffer, 90, 2, 120, 14, RED); rect(buffer, 120, 2, 150, 14, RED); // Health filler if (spaceship->health > 0) { rectfill(buffer, 62, 4, 88, 12, RED); } if (spaceship->health > 1) { rectfill(buffer, 92, 4, 118, 12, RED); } if (spaceship->health > 2) { rectfill(buffer, 122, 4, 148, 12, RED); } } // Update pulse cooldown bar void updatepulse() { // Actively refill based on cooldown rect(buffer, WIDTH/2 - 75, 2, WIDTH/2 + 75, 14, BLUE); rectfill(buffer, WIDTH/2 - 73, 4, WIDTH/2 + 73 - (pulse_cooldown) * 1.46, 12, BLUE); } // Main update function void update() { //Loop variable int i; // Status bar rectfill(buffer, 0, 0, WIDTH, 16, BLACK); textout_ex(buffer, font, "Health:", 1, 4, WHITE, BLACK); textout_ex(buffer, font, "Pulse:", WIDTH/2 - 125, 4, WHITE, BLACK); textprintf_centre_ex(buffer, font, WIDTH - 50, 4, WHITE, BLACK, "Score: %i", score); // Update health and pulse bars updatehealth(); updatepulse(); // Check collisions with spaceship checkcollisions_ship(); //move the spaceship spaceship->updatePosition(); // Update blaster of ship spaceship->pointer_x = spaceship->x + spaceship->width / 2 + calcAngleMoveX(spaceship->faceAngle - 90) * (spaceship->height / 2); spaceship->pointer_y = spaceship->y + spaceship->height / 2 + calcAngleMoveY(spaceship->faceAngle - 90) * (spaceship->height / 2); //rotate sprite with adjust for Allegro's 16.16 fixed trig //(256 / 360 = 0.7), then divide by 2 radians rotate_sprite(buffer, spaceship->image, (int)spaceship->x, (int)spaceship->y, itofix((int)(spaceship->faceAngle / 0.7f / 2.0f))); // Update pulse variables if (active_pulse == 0) { pulse->alive = 0; } else { activate_pulse(); active_pulse--; } // Pulse cooldown countdown if (pulse_cooldown != 0) { pulse_cooldown--; } // Warp spaceship warpsprite(spaceship); } // Get game input from user void getinput() { //hit ESC to quit if (key[KEY_ESC]) { gameover = 1; } // Instruction screen if (key[KEY_LCONTROL] && key[KEY_H]) { instructions(); } // Background music toggle if (key[KEY_LCONTROL] && key[KEY_M]) { if (sound == 1) { sound = 0; stop_sample(background_music); } else { sound = 1; play_sample(background_music, 128, 128, 1000, TRUE); } rest(20); } //ARROW KEYS AND SPACE BAR CONTROL for spaceship if (key[KEY_UP]) { thrusters(1); } if (key[KEY_DOWN]) { thrusters(-1); } if (key[KEY_LEFT]) { turnleft(); } if (key[KEY_RIGHT]) { turnright(); } if (key[KEY_SPACE]) { if (bullet_cooldown == 0) { fireweapon(); } } // Pulse active if (key[KEY_G]) { if (pulse_cooldown == 0) { play_sample(pulse_sound, 128, 128, 1000, FALSE); active_pulse = PULSE_DURATION; pulse_cooldown = PULSE_COOLDOWN; } } //short delay after keypress rest(20); } // Setup initial files void setupscreen() { //load background buffer title = (BITMAP *) data[GALATICDEFENSE_BMP].dat; if (!title) { allegro_message("Error loading sprites"); return; } // Load sound files background_music = (SAMPLE *) data[BACKGROUND_WAV].dat; click_sound = (SAMPLE *) data[CLICK_WAV].dat; bullet_sound = (SAMPLE *) data[BULLET_WAV].dat; pulse_sound = (SAMPLE *) data[PULSE_WAV].dat; //install a digital sound driver if (install_sound(DIGI_AUTODETECT, MIDI_NONE, "") != 0) { allegro_message("Error initalizing sound system"); return; } // Check if sound files loaded if (!background_music || !click_sound || !bullet_sound || !pulse_sound) { allegro_message("Error reading wave files"); return; } // Draw start screen draw_startscreen(); } // Setup game void setupgame() { //Loop variable int i; int j; int collide; //Play background music play_sample(background_music, 128, 128, 1000, TRUE); //Create a back buffer buffer = create_bitmap(WIDTH, HEIGHT); //load background buffer background = (BITMAP *)data[BACKGROUND_BMP].dat; //load explosion bitmap explosion = (BITMAP *)data[EXPLOSION_BMP].dat; //Create a spaceship sprite spaceship = new sprite(); if (!spaceship->load((BITMAP *) data[SPACESHIP_BMP].dat) || !background || !explosion) { allegro_message("Error loading sprites"); return; } // Set spaceship variables spaceship->width = spaceship->image->w; spaceship->height = spaceship->image->h; spaceship->health = 3; spaceship->xdelay = 0; spaceship->ydelay = 0; spaceship->x = SCREEN_W / 2 - spaceship->width/2; spaceship->y = SCREEN_H / 2 - spaceship->height/2; spaceship->moveAngle = 0; spaceship->faceAngle = 0; // Set pulse variables pulse = new sprite(); if (!pulse->load((BITMAP *) data[PULSE_BMP].dat)) { allegro_message("Error loading sprites"); return; } pulse->width = pulse->image->w + 20; pulse->height = pulse->image->h + 20; pulse->x = 0; pulse->y = 0; pulse->alive = 0; // Set bullet variables bullets = new spritehandler(); for (i = 0; i < BULLET_CAP; i++) { bullets->create(); bullets->get(i)->load((BITMAP *) data[BULLET_BMP].dat); bullets->get(i)->width = bullets->get(i)->image->w; bullets->get(i)->height = bullets->get(i)->image->h; bullets->get(i)->xdelay = 0; bullets->get(i)->ydelay = 0; bullets->get(i)->x = 0; bullets->get(i)->y = 0; } // Set asteroid variables asteroids = new spritehandler(); // Small asteroids for (i = 0; i < SMALLASTEROID_COUNT; i++) { asteroids->create(); asteroids->get(i)->load((BITMAP *) data[ASTEROID1_BMP].dat); asteroids->get(i)->health = 1; asteroids->get(i)->width = asteroids->get(i)->image->w; asteroids->get(i)->height = asteroids->get(i)->image->h; asteroids->get(i)->xdelay = 1; asteroids->get(i)->ydelay = 1; asteroids->get(i)->alive = 1; // Check if initial spawn collides with other asteroids. If so, reposition while (1) { collide = 0; if (rand() % 2 == 0) { asteroids->get(i)->x = rand() % ((SCREEN_W / 2) - (asteroids->get(i)->width + spaceship->width)); } else { asteroids->get(i)->x = rand() % ((SCREEN_W / 2) - (asteroids->get(i)->width + spaceship->width)) + ((SCREEN_W / 2) + (asteroids->get(i)->width + spaceship->width)); } if (rand() % 2 == 0) { asteroids->get(i)->y = rand() % (SCREEN_H / 2) - (asteroids->get(i)->height + spaceship->height); } else { asteroids->get(i)->y = rand() % ((SCREEN_H / 2) - (asteroids->get(i)->height + spaceship->height)) + ((SCREEN_H / 2) + (asteroids->get(i)->height + spaceship->height)); } for (j = 0; j < i; j++) { if (asteroids->get(j)->collided(asteroids->get(i))) { collide = 1; break; } } if (collide == 0) { break; } } // Randomize velocity asteroids->get(i)->velx = (rand() % 12) - 6; asteroids->get(i)->vely = (rand() % 12) - 6; } // Large asteroids for (i = SMALLASTEROID_COUNT; i < ASTEROID_COUNT; i++) { asteroids->create(); asteroids->get(i)->load((BITMAP *) data[ASTEROID20_BMP].dat); asteroids->get(i)->load2((BITMAP *) data[ASTEROID21_BMP].dat); asteroids->get(i)->load3((BITMAP *) data[ASTEROID22_BMP].dat); asteroids->get(i)->health = 3; asteroids->get(i)->width = asteroids->get(i)->image->w; asteroids->get(i)->height = asteroids->get(i)->image->h; asteroids->get(i)->xdelay = 1; asteroids->get(i)->ydelay = 1; asteroids->get(i)->alive = 1; // Check if initial spawn collides with other asteroids. If so, reposition while (1) { collide = 0; if (rand() % 2 == 0) { asteroids->get(i)->x = rand() % ((SCREEN_W / 2) - (asteroids->get(i)->width + spaceship->width)); } else { asteroids->get(i)->x = rand() % ((SCREEN_W / 2) - (asteroids->get(i)->width + spaceship->width)) + ((SCREEN_W / 2) + (asteroids->get(i)->width + spaceship->width)); } if (rand() % 2 == 0) { asteroids->get(i)->y = rand() % (SCREEN_H / 2) - (asteroids->get(i)->height + spaceship->height); } else { asteroids->get(i)->y = rand() % ((SCREEN_H / 2) - (asteroids->get(i)->height + spaceship->height)) + ((SCREEN_H / 2) + (asteroids->get(i)->height + spaceship->height)); } for (j = 0; j < i; j++) { if (asteroids->get(j)->collided(asteroids->get(i))) { collide = 1; break; } } if (collide == 0) { break; } } // Randomize velocity asteroids->get(i)->velx = calcAngleMoveX(asteroids->get(i)->moveAngle) * ((rand() % (ASTEROID_SPEED - 1)) + 1); asteroids->get(i)->vely = calcAngleMoveY(asteroids->get(i)->moveAngle) * ((rand() % (ASTEROID_SPEED - 1)) + 1); } } //this thread updates asteroids void* thread0(void* data) { // Loop variable int i; //get this thread id int my_thread_id = *((int*)data); //thread's main loop while(!done) { //lock the mutex to protect variables pthread_mutex_lock(&threadsafe); // Update asteroid is alive, else respawn it for (i = 0; i < ASTEROID_COUNT; i++) { if (asteroids->get(i)->alive == 1) { updateasteroid(i); } else { restart_asteroid(i); } } //unlock the mutex pthread_mutex_unlock(&threadsafe); //slow down (this thread only!) rest(10); } // terminate the thread pthread_exit(NULL); return NULL; } //this thread updates bullets void* thread1(void* data) { // Loop variable int i; //get this thread id int my_thread_id = *((int*)data); //thread's main loop while(!done) { //lock the mutex to protect variables pthread_mutex_lock(&threadsafe); // Update bullet if alive for (i = 0; i < BULLET_CAP; i++) { if (bullets->get(i)->alive == 1) { updatebullet(i); } } // Bullet cooldown timer if (bullet_cooldown > 0) { bullet_cooldown--; } //unlock the mutex pthread_mutex_unlock(&threadsafe); //slow down (this thread only!) rest(10); } // terminate the thread pthread_exit(NULL); return NULL; } //this thread updates game ship and GUI void* thread2(void* data) { //get this thread id int my_thread_id = *((int*)data); //thread's main loop while(!done) { //lock the mutex to protect variables pthread_mutex_lock(&threadsafe); update(); //unlock the mutex pthread_mutex_unlock(&threadsafe); //slow down (this thread only!) rest(10); } // terminate the thread pthread_exit(NULL); return NULL; } int main(void) { //initialize Allegro allegro_init(); //initialize the keyboard install_keyboard(); //initalize timer install_timer(); //initialize random seed srand(time(NULL)); //set video mode set_color_depth(16); //pthreads pthread_t pthread0; pthread_t pthread1; pthread_t pthread2; int threadid0 = 0; int threadid1 = 1; int threadid2 = 2; // Error variable int ret; int id; ret = set_gfx_mode(MODE, WIDTH, HEIGHT, 0, 0); if (ret != 0) { allegro_message(allegro_error); return 0; } // Setup datafiles // load the datfile data = load_datafile(DATA_FILE); // Error checking on load if (data == NULL) { allegro_message("Error loading datafile"); return 0; } // Setup screen setupscreen(); // Setup game setupgame(); // Clear Screen rectfill(screen, 0, 0, WIDTH, HEIGHT, BLACK); //create the thread for Asteroid handling id = pthread_create(&pthread0, NULL, thread0, (void*)&threadid0); //create the thread for Bullet handling id = pthread_create(&pthread1, NULL, thread1, (void*)&threadid1); //create the thread for game ship and GUI handling id = pthread_create(&pthread2, NULL, thread2, (void*)&threadid2); // Game loop while(!gameover) { //lock the mutex to protect double buffer pthread_mutex_lock(&threadsafe); //refresh the screen acquire_screen(); blit(buffer, screen, 0, 0, 0, 0, WIDTH, HEIGHT); release_screen(); //check for keypresses if (keypressed()) { getinput(); } //Clear background blit(background, buffer, 0, 0, 0, 0, WIDTH, HEIGHT); //unlock the mutex pthread_mutex_unlock(&threadsafe); } //tell threads it's time to quit done++; rest(100); //kill the mutex (thread protection) pthread_mutex_destroy(&threadsafe); // Clear Screen rectfill(screen, 0, 0, WIDTH, HEIGHT, BLACK); // Print final score textprintf_centre_ex(screen, font, WIDTH/2, HEIGHT/2, WHITE, BLACK, "Final User Score: %i", score); textout_centre_ex(screen, font, "Please Press ESC to QUIT!", WIDTH/2, HEIGHT/2 + 20, WHITE, BLACK); // Slow down game rest(250); // Wait until user exits game while(!key[KEY_ESC]) { }; // Cleanup destroy_bitmap(title); destroy_bitmap(buffer); destroy_bitmap(background); destroy_bitmap(explosion); destroy_sample(background_music); destroy_sample(click_sound); destroy_sample(bullet_sound); destroy_sample(pulse_sound); delete pulse; delete spaceship; //end program allegro_exit(); return 0; } END_OF_MAIN() <file_sep>/project1/sprite.h #ifndef _SPRITE_H #define _SPRITE_H 1 #include <allegro.h> class sprite { private: public: int alive; int state; int objecttype; int direction; double x,y; double pointer_x, pointer_y; int width,height; double speed; double velx, vely; int xdelay,ydelay; int xcount,ycount; int curframe,totalframes,animdir; int framecount,framedelay; int animcolumns; int animstartx, animstarty; int faceAngle, moveAngle; int health; BITMAP *image; BITMAP *image2; BITMAP *image3; public: sprite(); ~sprite(); int load(BITMAP * bitmap_image); int load2(BITMAP * bitmap_image); int load3(BITMAP * bitmap_image); void draw(BITMAP *dest); void drawframe(BITMAP *dest); void updatePosition(); void updateAnimation(); int inside(int x,int y,int left,int top,int right,int bottom); int pointInside(int px,int py); int collided(sprite *other = NULL, int shrink = 5); }; #endif <file_sep>/project1/spritehandler.h #pragma once #include "sprite.h" class spritehandler { private: int count; sprite *sprites[15]; public: spritehandler(void); ~spritehandler(void); void add(sprite *spr); void create(); sprite *get(int index); int size() { return count; } }; <file_sep>/project2/defines.h /* Allegro datafile object indexes, produced by dat v4.4.2, MinGW32 */ /* Datafile: data.dat */ /* Date: Mon Oct 09 18:32:32 2017 */ /* Do not hand edit! */ #define APPLE_BMP 0 /* BMP */ #define BACKGROUND_WAV 1 /* SAMP */ #define BERRIES_BMP 2 /* BMP */ #define BOING_WAV 3 /* SAMP */ #define CHARACTER_JUMP_BMP 4 /* BMP */ #define CHARACTER_WAIT1_BMP 5 /* BMP */ #define CHARACTER_WAIT2_BMP 6 /* BMP */ #define CHARACTER_WALK1_BMP 7 /* BMP */ #define CHARACTER_WALK2_BMP 8 /* BMP */ #define CLICK_WAV 9 /* SAMP */ #define ENEMIES1_BMP 10 /* BMP */ #define ENEMIES2_BMP 11 /* BMP */ #define ENEMIES3_BMP 12 /* BMP */ #define ENEMIES4_BMP 13 /* BMP */ #define FANFARE_WAV 14 /* SAMP */ #define GETMEMYFRUIT_BMP 15 /* BMP */ #define ORANGE_BMP 16 /* BMP */ #define PLUCK_WAV 17 /* SAMP */ #define SHUT_OFF_WAV 18 /* SAMP */ #define SPLASH_WAV 19 /* SAMP */ #define WATERMELON_BMP 20 /* BMP */ #define YAY_WAV 21 /* SAMP */
36c31a3ff08ab96794206c23cdfa4bf5b0ce5bb8
[ "C", "C++" ]
10
C
kwong4/UpgradedGames
29cca32259add8d3085f6444f15d93ae940583ca
14569b721ce0e92c45457112ee48a55270ec32f5
refs/heads/master
<repo_name>dariomiceli/Project-2<file_sep>/app/controllers/events_controller.rb class EventsController < ApplicationController $events = Event.all def index @events = $events end def show @events = $events @event = Event.find params[:id] @artist = Artist.find(@event.artist_id) @shareables = Shareable.all end def new @events = $events @event = current_artist.events.new end def create @event = current_artist.events.new event_params @event.save redirect_to root_path end def edit @events = $events @event = Event.find(params[:id]) end def update @event = Event.find(params[:id]) @event.venue = params[:event][:venue] @event.date = params[:event][:date] @event.url = params[:event][:url] @event.save redirect_to root_path end def destroy @event = Event.find(params[:id]) @event.destroy redirect_to root_path end def authorize_post_view @event = Event.find params[:id] if @event.user_id != current_artist.id redirect_to root_path end end private def event_params return params.require(:event).permit(:venue, :date, :url) end end <file_sep>/config/routes.rb Rails.application.routes.draw do root 'shareables#index' resources :artists resources :epks resources :events resources :shareables resources :sessions, only: [:new, :create] delete '/logout' => 'sessions#destroy', as: :logout end <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery with: :exception helper_method :current_artist, :logged_in? def current_artist @current_artist ||= Artist.find(session[:artist_id]) if session[:artist_id] end def logged_in? !!current_artist end def authorize redirect_to new_session_path unless logged_in? end end <file_sep>/db/migrate/20180226190129_create_artists.rb class CreateArtists < ActiveRecord::Migration[5.1] def change create_table :artists do |t| t.string :name t.string :email t.string :password_digest t.string :sc_link t.string :ig_link t.string :fb_link t.string :dme_link t.boolean :admin t.timestamps end end end <file_sep>/app/controllers/shareables_controller.rb class ShareablesController < ApplicationController before_action :authorize_shareable_view, only: :show def index @artists = Artist.all @shareables = Shareable.all @events = Event.all end def show @shareables = Shareable.all @events = Event.all @shareable = Shareable.find params[:id] @artist = Artist.find(@shareable.artist_id) end def new @shareables = Shareable.all @shareable = current_artist.shareables.new @events = Event.all end def create @shareable = current_artist.shareables.new shareable_params @shareable.save redirect_to root_path end def edit @events = Event.all @shareables = Shareable.all @shareable = Shareable.find params[:id] end def update @shareable = Shareable.find params[:id] @shareable.description = params[:shareable][:description] @shareable.url = params[:shareable][:url] @shareable.save redirect_to root_path end def destroy @shareable = Shareable.find params[:id] @shareable.destroy redirect_to root_path end def authorize_shareable_view @shareable = Shareable.find params[:id] if @shareable.artist.id != current_artist.id end end private def shareable_params return params.require(:shareable).permit(:description, :url) end end <file_sep>/app/controllers/epks_controller.rb class EpksController < ApplicationController def index @shareables = Shareable.all @events = Event.all @epks = Epk.all end def show #@shareables = Shareable.all @events = Event.all #@epks = Epk.all #@artist = Artist.find(@epks.artist.id) end def new @shareables = Shareable.all @events = Event.all @epk = current_artist.epks.new end def create @shareables = Shareable.all @events = Event.all @epk = current_artist.epks.new epk_params @epk.save flash[:success] = "EPK change request submitted." redirect_to root_path end def edit end def update end def destroy end def authorize_post_view @epk = EPK.find params[:id] if @epk.artist_id != current_artist.id redirect_to root_path end end private def epk_params return params.require(:epk).permit(:description, :url) end end<file_sep>/README.md # DMEconnect ![alt text](./ReadMeImages/screenshot.png "Homepage Screenshot") DMEconnect is a web application optimized to facilitate communication within an arist management firm. It allows users to submit (1) upcoming events with quick access to event details, (2) "shareables" which are items they would like other users to share on social media and (3) Electronic Press Kit change requests to an admin. In the past, getting everyone on the same page was difficult and involved sifting through a deluge of events and links on different social media platforms. DMEconnect's simplistic design and minimalist functionality greatly ease this process. [Visit DMEconnect](https://infinite-inlet-15903.herokuapp.com/ "DMEconnect") ### Technologies Used * HTML * CSS * Ruby on Rails * [Bootstrap](http://getbootstrap.com/) * Bcrypt * [PostgreSQL](https://www.postgresql.org/) * [Heroku](https://www.heroku.com/) * [Balsamiq](https://balsamiq.com/) ### Approach The idea for this web app came from a real-world need to better communicate within my organization. Scattered text and Facebook messages led to an unorganized and inefficient process. I began by wireframing with Balsamiq. This helped me develop a general design and also aided in user flow. ![alt text](./ReadMeImages/ERD.png "Homepage Screenshot") ERD ![alt text](./ReadMeImages/Wire-frame-flow.png "Homepage Screenshot") User Flow ![alt text](./ReadMeImages/Wire-frame-homepage.png "Homepage Screenshot") Homepage ![alt text](./ReadMeImages/Wire-frame-EPK.png "Homepage Screenshot") Adding an EPK Work began with basic design, then moved to functionality. Adding events, shareables and EPK change requests was the first function to be compelted. I then moved onto admin permissions and user authentication and authorization. ### Installation To run DMEconnect locally: * Clone this repo to your machine * Cd into the app * Run 'bundle install' * Run 'rails db:create' * Run 'rails db:migrate' * Open 'localhost:3000' in your browser ### Next Steps In the future DMEconnect will be more integrated with social media platforms, allowing for quick-share links and importation of user profile information. The design can be improved to give better visibility and access to users. ### Task Management Trello was the primary task manager for this project. Before I began design any code work I laid out user stories for two different [View Trello board here.](https://trello.com/b/JZuSXEjV/project-2 "Project 2 Trello Board") <file_sep>/test/controllers/epks_controller_test.rb require 'test_helper' class EpksControllerTest < ActionDispatch::IntegrationTest test "should get index" do get epks_index_url assert_response :success end test "should get show" do get epks_show_url assert_response :success end test "should get new" do get epks_new_url assert_response :success end test "should get create" do get epks_create_url assert_response :success end test "should get edit" do get epks_edit_url assert_response :success end test "should get update" do get epks_update_url assert_response :success end test "should get destroy" do get epks_destroy_url assert_response :success end end <file_sep>/app/controllers/artists_controller.rb class ArtistsController < ApplicationController before_action :authorize, only: [:show, :edit, :update, :destroy] def index @artists = Artist.all @events = Event.all @shareables = Shareable.all end def show # @artist = Artist.find params[:id] @events = Event.all @shareables = Shareable.all end def new @artist = Artist.new end def create @artist = Artist.new artist_params if @artist.save session[:artist_id] = @artist.id redirect_to artist_path @artist.id else flash[:warning] = "Check email and password." redirect_to new_artist_path end end def edit @events = Event.all @artists = Artist.all @artist = Artist.find(params[:id]) end def update @artist = Artist.find(params[:id]) @artist.name = params[:artist][:name] @artist.email = params[:artist][:email] @artist.sc_link = params[:artist][:sc_link] @artist.ig_link = params[:artist][:ig_link] @artist.fb_link = params[:artist][:fb_link] @artist.dme_link = params[:artist][:dme_link] @artist.save redirect_to root_path end def destroy end private def artist_params return params.require(:artist).permit(:name, :email, :password, :sc_link, :ig_link, :fb_link, :dme_link) end end<file_sep>/app/models/artist.rb class Artist < ApplicationRecord has_secure_password has_many :epks has_many :events has_many :shareables validates :name, presence: true validates :email, presence: true validates :fb_link, presence: true validates :sc_link, presence: true validates :ig_link, presence: true validates :dme_link, presence: true end
2881881cd0ab98a51315f0b22eaa29728a906d3c
[ "Markdown", "Ruby" ]
10
Ruby
dariomiceli/Project-2
093b211382b352664d5d7b2a95e6d8417649892a
f884049dac5fac2e43faf5624eb52cb03432a23f
refs/heads/master
<repo_name>depapp/peminjaman<file_sep>/app/Http/Controllers/AsisstantController.php <?php namespace App\Http\Controllers; use App\asisstant; use App\Http\Requests; use App\Http\Controllers\Controller; use Request; class AsisstantController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function __construct() { $this->middleware('auth',['except' => ['view']]); } public function index() { $asisstants=asisstant::all(); return view('listAsisstant',compact('asisstants')); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('AddAsisstant'); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $destinationPath = public_path('images'); $fileName = str_random(20) . '.' . Request::file('foto')->getClientOriginalExtension(); $asisstants = new asisstant; $asisstants->nim = Request::get('nim'); $asisstants->nama = Request::get('nama'); $asisstants->jurusan = Request::get('jurusan'); $asisstants->angkatan = Request::get('angkatan'); $asisstants->hp = Request::get('hp'); $asisstants->email = Request::get('email'); $asisstants->divisi = Request::get('divisi'); $asisstants->deskripsi = Request::get('deskripsi'); $asisstants->foto = $fileName; $asisstants->save(); Request::file('foto')->move($destinationPath, $fileName); return redirect('listAsisstant'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { asisstant::find($id)->delete(); return redirect('listAsisstant'); } public function view() { $asisstants=asisstant::all(); return view('assistant',compact('asisstants')); } } <file_sep>/app/Http/Controllers/LoanController.php <?php namespace App\Http\Controllers; use App\loan; use App\Http\Requests; use App\Http\Controllers\Controller; use Request; class LoanController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function __construct() { $this->middleware('auth',['except' => ['create', 'store']]); } public function index() { $loans=loan::all(); return view('loan',compact('loans')); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('formLoan'); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $loans = new loan; $loans->nama = Request::get('nama'); $loans->nim = Request::get('nim'); $loans->jurusan = Request::get('jurusan'); $loans->fakultas = Request::get('fakultas'); $loans->institusi = Request::get('institusi'); $loans->tlp = Request::get('tlp'); $loans->keperluan = Request::get('keperluan'); $loans->tgl_pinjam = Request::get('tgl_pinjam'); $loans->tgl_kembali = Request::get('tgl_kembali'); $loans->alat = Request::get('alat'); $loans->status = 'waiting'; $loans->save(); return redirect('formLoan'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $loans = loan::find($id); $loans->status = 'Accept'; $loans->save(); return redirect('loan'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { loan::find($id)->delete(); return redirect('loan'); } } <file_sep>/app/Http/Controllers/ArticleController.php <?php namespace App\Http\Controllers; use App\article; use App\Http\Requests; use App\Http\Controllers\Controller; use Request; class ArticleController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function __construct() { $this->middleware('auth',['except' => ['view','viewArticle','show']]); } public function index() { $articles=article::all(); return view('dashboard',compact('articles')); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('AddArticle'); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $destinationPath = public_path('images'); $fileName = str_random(20) . '.' . Request::file('img')->getClientOriginalExtension(); $articles = new article; $articles->title = Request::get('title'); $articles->category = Request::get('category'); $articles->content = Request::get('content'); $articles->img = $fileName; $articles->save(); Request::file('img')->move($destinationPath, $fileName); return redirect('dashboard'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show() { $articles=article::all(); return view('article',compact('articles')); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { article::find($id)->delete(); return redirect('dashboard'); } public function view() { $articles=article::all()->take(4); return view('awal',compact('articles')); } public function viewArticle($id) { $articles=article::find($id); return view('viewpost',compact('articles')); } } <file_sep>/app/asisstant.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class asisstant extends Model { protected $fillable=[ 'nim', 'nama', 'jurusan', 'angkatan', 'hp', 'email', 'divisi', 'deskripsi', 'foto', ]; } <file_sep>/app/Http/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('dashboard',['as'=>'article.index','uses'=>'ArticleController@index']); Route::get('article',['as'=>'article.create','uses'=>'ArticleController@create']); Route::post('/article',['as'=>'article.store','uses'=>'ArticleController@store']); Route::get('article/{article}',['as'=>'article.destroy','uses'=>'ArticleController@destroy']); Route::get('index',['as'=>'article.index','uses'=>'ArticleController@view']); Route::get('viewarticle/{id}', 'ArticleController@viewArticle'); Route::get('listarticle', 'ArticleController@show'); Route::get('addAsisstant',['as'=>'asisstant.create','uses'=>'AsisstantController@create']); Route::post('/addAsisstant',['as'=>'asisstant.store','uses'=>'AsisstantController@store']); Route::get('/listAsisstant',['as'=>'asisstant.index','uses'=>'AsisstantController@index']); Route::get('listAsisstant/{listAsisstant}',['as'=>'asisstant.destroy','uses'=>'AsisstantController@destroy']); Route::get('assistant/', 'AsisstantController@view'); Route::get('loan',['as'=>'loan.index','uses'=>'LoanController@index']); Route::get('formLoan',['as'=>'loan.create','uses'=>'LoanController@create']); Route::post('/formLoan',['as'=>'loan.store','uses'=>'LoanController@store']); Route::get('formLoan/{formLoan}/update',['as'=>'loan.update','uses'=>'LoanController@update']); Route::get('formLoan/{formLoan}',['as'=>'loan.destroy','uses'=>'LoanController@destroy']); route::get('login','userController@index'); route::post('auth','userController@store'); route::get('logout','userController@logout'); Route::get('/', 'WelcomeController@index'); Route::get('home', 'HomeController@index'); Route::controllers([ 'auth' => 'Auth\AuthController', 'password' => '<PASSWORD>', ]);
49ef408bbb2be5665126ee833e6144dc74bea6b9
[ "PHP" ]
5
PHP
depapp/peminjaman
b82b72c1bc596917d2d012eeab119c299e6b178b
d3f4c19ca60d8c7be5a4708f86b9a0cb3d4e94f8
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Product; class ProductController extends Controller { public function index() { return Product::all(); } public function auth(Request $request) { $data = [ 'login' => $request->get('user'), 'password' => $request->get('password') ]; return $data; } } <file_sep><?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Database\Eloquent\SoftDeletes; use App\Models\Store; class User extends Authenticatable { use Notifiable; use SoftDeletes; public $timestamps = true; protected $table = 'users'; protected $fillable = [ 'store_id', 'name', 'login', 'password', 'status' ]; protected $hidden = ['password', 'remember_token',]; public function store() { return $this->belongsTo(Store::class); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Cont extends Model { use SoftDeletes; //comentario teste protected $fillable = [ 'list_cont_id', 'product_id', 'stock_sell', 'stock_dep', 'stock_total' ]; } <file_sep><?php use Illuminate\Database\Seeder; class ProductSeeder extends Seeder { /** * Selecione quantos itens fakes a tabela vai ter * * @return void */ public function run() { factory(\App\Product::class, 10)->create(); } } <file_sep>const misc = { uppercaseValue: function(text) { return text.toUpperCase(); } }; export default misc; <file_sep><h1 align="center"> Um sistema que será utilizado para coleta de dados. </h1> <h4 align="center"> ☕ Code and coffee </h4> <p align="center"> <a href="#rocket-tecnologias">Tecnologias</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#-projeto">Projeto</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#-como-contribuir">Como contribuir</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; </p> <br> ## :rocket: Tecnologias Esse projeto foi desenvolvido com as seguintes tecnologias: - [Laravel](https://laravel.com/) - [vue](https://vuejs.org/) - [React Native](https://facebook.github.io/react-native/) ## 💻 Projeto CodePlus – Projeto pessoal que está em desenvolvimento para supermercados. O Codeplus é um sistema que será utilizado para coleta de dados com o objetivo de se realizar inventário de estoque, controle de validade e listagem para alteração de produtos. Vai contar com um painel administrativo online com níveis de acesso, permitindo ao usuário maior controle no gerenciamento dos dados coletados e importação e exportação dos mesmos e o aplicativo para Android (Futuramente iOS) responsável por adicionar diferentes listagens, fazendo a leitura dos códigos de barras utilizando a câmera do dispositivo e fazendo a comunicação (consumindo API) com o painel administrativo. O backend do painel está sendo desenvolvido com Laravel e o frontend utilizando Vue.js, e o aplicativo com React Native. ## 🤔 Como contribuir - Faça um fork desse repositório; - Cria uma branch com a sua feature: `git checkout -b minha-feature`; - Faça commit das suas alterações: `git commit -m 'feat: Minha nova feature'`; - Faça push para a sua branch: `git push origin minha-feature`. Depois que o merge da sua pull request for feito, você pode deletar a sua branch. <file_sep><?php namespace App\Http\Controllers\Dashboard; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\Store; use Auth; use App\User; class DashController extends Controller { protected $redirectTo = '/dashboard'; public function __construct() { } public function index() { return view('dashboard.painels.homeDash', compact('user')); } } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\Store; class StoreTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Store::create([ 'name' => '<NAME>', 'name_fantasy' => 'SUPERMERCADO PRIMAVERA LOJA 1', 'cnpj' => '37610722000178' ]); } } <file_sep>import axios from 'axios'; import { NotificationManager } from 'react-notifications'; const headers = { 'content-type': 'application/x-www-form-urlencoded' }; const crud = { list: async function(url) { const response = await axios.get(url); return response.data; }, add: async function(url, idForm) { var form = $('#' + idForm).serialize(); const response = await axios.post(url, { form }, { headers: headers }); return response.data; } }; export default crud; <file_sep>export function addItemAction(element) { return { type: 'ADD_ITEM', data: element }; } <file_sep><?php namespace App\Http\Controllers\Dashboard; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\User; use Illuminate\Support\Facades\Auth; class UsersController extends Controller { protected $redirectTo = '/dashboard'; private $store_id; public function __construct() { $this->middleware(function ($request, $next) { $this->store_id = Auth::user()->store_id; return $next($request); }); } public function index() { return view('dashboard.painels.usuarios'); } public function show(Request $request) { return json_encode(User::select('id', 'name', 'login', 'status')->where('store_id', $this->store_id)->get()); } public function store(Request $request) { try { $data = $request->all(); $request->validate([ 'name' => 'required|string|max:50', 'password' => '<PASSWORD>', 'login' => 'required', ]); $data['password'] = <PASSWORD>($data['<PASSWORD>']); $data['store_id'] = $this->store_id; User::create($data); return 'ok'; } catch (\Exception $th) { return response()->json(['errors' => $th->getMessage()]); } } } <file_sep>import React, { Component } from 'react'; export default class Table extends Component { constructor(props) { super(props); this.state = { keys: [], data: [] }; this.filterData = this.filterData.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.data != this.props.data) { this.setState({ data: nextProps.data }); this.setState({ keys: Object.keys(nextProps.data[0]) }); } this.filterData(nextProps.search); } filterData(query) { var result = this.props.data; if (query.length > 0) { result = result.filter(function(res) { var text = JSON.stringify(res); return text.toUpperCase().includes(query.toUpperCase()); }); this.setState({ data: result }); } else { if (this.props.data.length > 0) { this.setState({ data: this.props.data }); } } } render() { return ( <div> <table class="table table-striped table-borderless table-hover table-sm"> <thead> <tr> {this.state.keys.map((key) => ( <th key={key} scope="col"> {this.props.head[key] || key} </th> ))} {this.state.keys.length > 1 && (this.props.action && <th scope="col">Ação</th>)} </tr> </thead> <tbody> {this.state.data.map((value) => ( <tr key={value.id}> {Object.keys(value).map((item) => <td key={item}>{value[item]}</td>)} {this.props.action && ( <td> <ul class="btnActions"> {this.props.view && ( <li> <ion-icon class="btnView" name="eye" /> </li> )} {this.props.edit && ( <li> <ion-icon class="btnEdit" name="create" /> </li> )} {this.props.delete && ( <li> <ion-icon class="btnRemove" name="trash" /> </li> )} </ul> </td> )} </tr> ))} </tbody> </table> </div> ); } } <file_sep><?php use Illuminate\Database\Seeder; use App\User; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { User::create([ 'store_id' => 1, 'name' => '<NAME>', 'login' => 'miguelaugusto', 'password' => bcrypt('<PASSWORD>'), ]); } } <file_sep><?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; class LoginController extends Controller { use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '/dashboard'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } public function index() { return view('auth.login'); } public function auth(Request $request) { $user = $request->only('store_id', 'login', 'password'); $msg = \Auth::attempt($user) ? "success" : "error"; return $msg; } } <file_sep>import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { NotificationContainer } from 'react-notifications'; export default class Notification extends Component { render() { return ( <div> <NotificationContainer /> </div> ); } } if (document.getElementById('notification')) { ReactDOM.render(<Notification />, document.getElementById('notification')); } <file_sep>import React, { Component, useState } from 'react'; import ReactDOM from 'react-dom'; import { NotificationManager } from 'react-notifications'; import axios from 'axios'; export default (Login = (props) => { const [ store_id, setStoreId ] = useState(''); const [ login, setLogin ] = useState(''); const [ password, setPassword ] = useState(''); const [ token, setToken ] = useState(props.token); function onChange(ev) { ev.target.name == 'store_id' ? setStoreId(ev.target.value) : null; ev.target.name == 'login' ? setLogin(ev.target.value) : null; ev.target.name == 'password' ? setPassword(ev.target.value) : null; } function validarUsuario() { var error = false; store_id == '' ? (NotificationManager.warning('O campo Estabelecimento deve ser preenchido!', 'Aviso'), (error = true)) : null; login == '' ? (NotificationManager.warning('O campo Usuário deve ser preenchido!', 'Aviso'), (error = true)) : null; password == '' ? (NotificationManager.warning('O campo Senha deve ser preenchido!', 'Aviso'), (error = true)) : null; !error ? verificarUsuario() : null; } function verificarUsuario() { axios .post('http://codeplus.desenv:80/', { user: login, store_id: store_id, password: <PASSWORD>, token: token }) .then((response) => { response.data == 'error' ? NotificationManager.error('Usuário não cadastrado!', 'Erro') : window.location.reload(); }) .catch((error) => { NotificationManager.error('Erro inesperado - ' + error + ' Contate suporte!', 'Erro'); }); } return ( <div class="loginBox bg-white text-center"> <div class="codePlusLogo text-center d-inline-block justify-content-center"> <img class="text-center" src={props.img} /> <ion-icon class="dropIcon" name="arrow-dropdown" /> </div> <form class="d-inline-block formLogin" method="POST"> <input type="hidden" name="_token" value={props.token} /> <div class="groupInput"> <div class="iconLogin"> <ion-icon name="apps" /> </div> <input type="number" name="store_id" value={store_id} onChange={onChange} placeholder="Código do Estabelecimento" /> </div> <div class="groupInput"> <div class="iconLogin"> <ion-icon name="person" /> </div> <input type="text" name="login" value={login} onChange={onChange} placeholder="Usuário" /> </div> <div class="groupInput"> <div class="iconLogin"> <ion-icon name="key" /> </div> <input type="<PASSWORD>" name="password" value={password} onChange={onChange} placeholder="<PASSWORD>" /> </div> </form> <div class="buttons"> <button class="btnLogin" onClick={validarUsuario}> Login </button> </div> <p class="text-capitalize textSuport"> <small class="font-weight-light">{props.msg}</small> </p> </div> ); }); if (document.getElementById('login')) { var msg = document.getElementById('login').getAttribute('msgSuport'); var token = document.getElementById('login').getAttribute('token'); var img = document.getElementById('login').getAttribute('img'); ReactDOM.render(<Login msg={msg} token={token} img={img} />, document.getElementById('login')); } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'Auth\LoginController@index')->name('rt.telaLogin'); Route::post('/', 'Auth\LoginController@auth')->name('rt.authUser'); Route::get('/login', function () { return redirect()->route('rt.telaLogin'); }); Route::group(['namespace' => 'Dashboard', 'middleware' => 'auth', 'prefix' => 'dashboard'], function () { Route::get('/', 'DashController@index')->name('rt.dashboard'); Route::resource('/usuarios', 'UsersController'); }); <file_sep>import React, { Component } from 'react'; import ReactDOM from 'react-dom'; export default class Bread extends Component { constructor(props) { super(props); this.state = { caminho: this.props.caminho }; } render() { return ( <div> <span>{this.props.caminho}</span> </div> ); } } if (document.getElementById('breadcrumbs')) { var caminho = document.getElementById('breadcrumbs').getAttribute('caminho'); ReactDOM.render(<Bread caminho={caminho} />, document.getElementById('breadcrumbs')); } <file_sep>import React, { Component } from 'react'; import Crud from '../../services/Crud'; import { NotificationManager } from 'react-notifications'; import { bindActionCreators } from 'redux'; import * as actionsCrud from '../../actions/actCrud'; import { connect } from 'react-redux'; class Modal extends Component { constructor(props) { super(props); this.state = {}; this.add = this.add.bind(this); //add model } async add() { var response = await Crud.add(this.props.url, this.props.idForm); if (response == 'ok') { NotificationManager.success('Dados salvos com sucesso!', 'Aviso!'); $('.modal').modal('toggle'); $('.modal-backdrop').remove(); } else { NotificationManager.error(response['erro'] + ' Contate suporte!', 'Erro'); } } render() { return ( <div> <div class="modal fade" id={this.props.idModal} tabindex="-1" role="dialog" aria-labelledby={'modalLabel'} aria-hidden="true" > <div className={this.props.size + ' modal-dialog modal-dialog-centered'} role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modalLabel"> {this.props.title} </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Fechar"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body">{this.props.children}</div> <div class="modal-footer"> {this.props.function == 'add' && ( <button type="button" class="btn btn-primary" onClick={this.add}> {this.props.actionText || 'Salvar'} </button> )} <button type="button" class="btn btn-secondary" data-dismiss="modal"> {this.props.cancelText || 'Sair'} </button> </div> </div> </div> </div> </div> ); } } const mapDispatchToProps = (dispatch) => bindActionCreators(actionsCrud, dispatch); export default connect(null, mapDispatchToProps)(Modal);
684c639c0160e8d0161fc61770ac22a74ac7ed29
[ "JavaScript", "Markdown", "PHP" ]
19
PHP
joaoaugustojr/codeplus
08dd69352e5c1977a9c291eccf7d355a9f23b4d9
8518d5ecb889619cdf51a6970fc3d90407fd046d
refs/heads/master
<file_sep># Prerequisites for ansible to communicate with a Windows Host. yum install python-pip -y && pip install --upgrade pip && pip install pywinrm && # Stop the creation of .retry files when a playbook fails to run. sed -i "s:#retry_files_enabled = False:retry_files_enabled = False:g" /etc/ansible/ansible.cfg <file_sep># -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.ssh.insert_key = false config.vm.define "control" do |ctrl| ctrl.vm.box = "ansible/tower" ctrl.vm.hostname = "ubuntu-control" ctrl.vm.network "private_network", ip: "192.168.24.2" ctrl.vm.synced_folder "./", "/vagrant" ctrl.vm.provision "shell", path: "provision/control.sh", privileged: true ctrl.vm.provider "virtualbox" do |vb| vb.memory = 1024 end end config.vm.define "windows" do |win| win.vm.box = "christophershoemaker/win2k8r2sp1.box" win.vm.hostname = "dev-box" win.vm.communicator = "winrm" win.vm.network "private_network", ip: "192.168.24.3" win.winrm.username = "vagrant" win.winrm.password = "<PASSWORD>" win.vm.provider "virtualbox" do |vb| vb.memory = 2048 vb.cpus = 2 end end end
172a557d0fbafe05d98d819bf8072b21ea1d758e
[ "Ruby", "Shell" ]
2
Shell
GarethOates/ansible-workshop
013fef1d32c822980baf238642f2ff3db6a3b1a4
0c7bab2336fc015b8815409b9fe3dd89f7fb59d4
refs/heads/master
<file_sep># Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ s = 0 c = 0 prev = ListNode(0) prev1 = prev while l1 and l2: s = l1.val + l2.val + c c = s/10 Node = ListNode(s%10) prev1.next = Node prev1 = Node l1 = l1.next l2 = l2.next while l1: s = l1.val + c c = s/10 Node = ListNode(s%10) prev1.next = Node prev1 = Node l1 = l1.next while l2: s = l2.val + c c = s/10 Node = ListNode(s%10) prev1.next = Node prev1 = Node l2 = l2.next if c == 1: prev1.next = ListNode(1) return prev.next
920f63b270db44976fe6c548e7597971f8a70548
[ "Python" ]
1
Python
100piyushsingh/Journey
2eacf1c725ca0c2173282c1419b9d599b8af226f
f689266ef8fb480946422113af764b55c6e981a9
refs/heads/master
<repo_name>bsiegfreid/tkdraw<file_sep>/tkdraw/config.py import os from appdirs import AppDirs class Config: def __init__(self): self.app_dir = get_app_dir() def save_geometry(self, window): path = os.path.join(self.app_dir, 'geometry.conf') print(path) with open(path, "w") as conf: conf.write(window.geometry()) def read_geometry(self): path = os.path.join(self.app_dir, 'geometry.conf') try: with open(path, "w") as conf: geometry = conf.read() # TODO Validate! except IOError: geometry = '' print(geometry) return geometry def get_app_dir(): app_dirs = AppDirs('tkdraw', 'tkdraw') user_config_dir = os.path.normpath(app_dirs.user_config_dir) if not os.path.isdir(user_config_dir): os.makedirs(user_config_dir) return user_config_dir <file_sep>/tkdraw/app.py from tkinter import * from tkinter.ttk import * from tkdraw.config import Config from tkdraw.tools import SelectTool from tkdraw.tools import CreateLineTool from tkdraw.tools import CreateRectangleTool class App(Frame): """\ Main application window. """ def __init__(self, master=None): """\ Initialize an object instance. """ super().__init__(master) self.config = Config() # Instance Variables self.last_x, self.last_y = 0, 0 # Track last location self.fill_color = "black" # Current fill color # Window Layout self.init_menus() self.init_layout() self.init_tools(self.frame_tools) def init_menus(self): """\ Build the menu bar. """ # Menu Bar: Instantiate, keep a reference and register with Frame. self.menu = Menu(self.master) self.master.config(menu=self.menu) # File Menu: Instantiate, keep a reference and register with menu bar. self.menu_file = Menu(self.menu, tearoff=0) self.menu.add_cascade(label="File", menu=self.menu_file) # File > Exit self.menu_file.add_command(label="Exit", command=self.exit) def init_layout(self): # Declare all Frames self.frame_option = Frame(self.master, width=200, height=30, borderwidth=2, relief="groove") self.frame_tools = Frame(self.master, width=50, height=200, borderwidth=2, relief="groove") self.frame_canvas = Frame(self.master, width=200, height=200) # Layout all Frames self.master.grid_rowconfigure(1, weight=1) self.master.grid_columnconfigure(1, weight=1) # Place all Frames self.frame_option.grid(row=0, column=0, columnspan=2, sticky="we") self.frame_tools.grid(row=1, column=0, sticky="nsw") self.frame_canvas.grid(row=1, column=1, sticky="nsew") # Instantiate canvas with scroll bars x_scrollbar = Scrollbar(self.frame_canvas, orient=HORIZONTAL) y_scrollbar = Scrollbar(self.frame_canvas, orient=VERTICAL) # Create canvas as a child of the canvas frame self.canvas = Canvas(self.frame_canvas, scrollregion=(0, 0, 1000, 1000), yscrollcommand=y_scrollbar.set, xscrollcommand=x_scrollbar.set) x_scrollbar['command'] = self.canvas.xview y_scrollbar['command'] = self.canvas.yview # Set the stickiness of the canvas cell self.canvas.grid(column=0, row=0, sticky=(N, W, E, S)) # Set the expandability of the canvas cell self.frame_canvas.grid_columnconfigure(0, weight=1) self.frame_canvas.grid_rowconfigure(0, weight=1) x_scrollbar.grid(column=0, row=1, sticky=(W, E)) y_scrollbar.grid(column=1, row=0, sticky=(N, S)) def init_tools(self, parent): self.tools = [] # Select select_tool = SelectTool(self) self.tools.append(select_tool) select_tool_button = Button(parent, text="Select", command=select_tool.activate) select_tool_button.pack() # Line create_line_tool = CreateLineTool(self) self.tools.append(create_line_tool) button_create_line = Button(parent, text="Line", command=create_line_tool.activate) button_create_line.pack() # Rectangle create_rectangle_tool = CreateRectangleTool(self) self.tools.append(create_rectangle_tool) button_create_rectangle = Button(parent, text="Rectangle", command=create_rectangle_tool.activate) button_create_rectangle.pack() # Register Select as current tool select_tool.activate() self.current_tool = select_tool def build_color_swatches(self): self.swatch_red = self.canvas.create_rectangle((0, 0, 30, 30), fill="red", tags=('palette', 'palette_red')) self.canvas.tag_bind(self.swatch_red, "<Button-1>", lambda x: self.set_fill_color("red")) self.swatch_blue = self.canvas.create_rectangle((35, 0, 35, 30), fill="blue", tags=('palette', 'palette_blue')) self.canvas.tag_bind(self.swatch_blue, "<Button-1>", lambda x: self.set_fill_color("blue")) self.swatch_black = self.canvas.create_rectangle((70, 0, 70, 30), fill="black", tags=('palette', 'palette_black', 'palette_selected')) self.canvas.tag_bind(self.swatch_black, "<Button-1>", lambda x: self.set_fill_color("black")) self.set_fill_color('black') self.canvas.itemconfigure('palette', width=5) def set_fill_color(self, color): self.fill_color = color self.canvas.dtag('all', 'palette_selected') self.canvas.itemconfigure('palette', outline='white') self.canvas.addtag('palette_selected', 'withtag', 'palette_%s' % color) self.canvas.itemconfigure('palette_selected', outline='#999999') def save_size(self, event): app_config = Config() app_config.save_geometry(self) def exit(self): """\ Exit the application. """ self.master.quit() <file_sep>/tkdraw/tools/create_rectangle.py from tkdraw.tools.tool import Tool class CreateRectangleTool(Tool): def __init__(self, app): super().__init__(app) self.drawing = False # If True a shape is currently being drawn self.pair1 = None self.pair2 = None self.object_id = -1 # If -1 then no current shape def activate(self, ): # First step on activate should always be switch. self.switch() # Register all callable actions self.register_binding("<Button-1>", self.left_click) self.register_binding("<Motion>", self.motion) self.register_binding("<ButtonRelease-1>", self.left_click_release) def left_click(self, event): """\ Start a new rectangle. """ # Get canvas coordinates instead of window self.pair1 = self.canvas_coordinates(event) # Flag that we are now drawing self.drawing = True def motion(self, event): """\ Preview rectangle. """ # Function is called even when a shape hasn't been started. Only proceed if drawing if self.drawing: # Get canvas coordinates instead of window x, y = self.canvas_coordinates(event) # Remove temporary shape if self.object_id > -1: self.app.canvas.delete(self.object_id) # Draw new line with preview segment self.object_id = self.draw_rectangle(self.pair1, (x, y)) def left_click_release(self, event): """\ Finish the rectangle and reset for next rectangle. """ # Get canvas coordinates instead of window self.pair2 = self.canvas_coordinates(event) # Draw the line on the canvas self.draw_rectangle(self.pair1, self.pair2) # Reset object variables for next line self.pair1 = None self.pair2 = None self.object_id = -1 self.drawing = False def draw_rectangle(self, pair1, pair2): """\ Draw rectangle and return object id. """ return self.app.canvas.create_rectangle(pair1[0], pair1[1], pair2[0], pair2[1], fill=self.app.fill_color, width=1) <file_sep>/tkdraw/__init__.py from tkdraw.app import App from tkdraw.optionframe import OptionFrame <file_sep>/tkdraw/tools/__init__.py from tkdraw.tools.create_line import CreateLineTool from tkdraw.tools.create_rectangle import CreateRectangleTool from tkdraw.tools.select import SelectTool<file_sep>/README.md # tkdraw An exercise in creating a drawing program using Tkinter. <file_sep>/tkdraw/optionframe.py from tkinter.ttk import * class OptionFrame(Frame): """\ Frame that contains the currently selected tool's options. """ def __init__(self, master=None): super().__init__(master) <file_sep>/tkdraw/tools/select.py from tkinter import * from tkdraw.tools.tool import Tool class SelectTool(Tool): def __init__(self, app): super().__init__(app) def activate(self): # First step on activate should always be switch. self.switch() # Register all callable actions self.register_binding("<Button-1>", self.click) def click(self, event): item = self.app.canvas.find_closest(event.x, event.y) print(item) current_fill = self.app.canvas.itemcget(item, 'fill') self.app.canvas.itemconfig(CURRENT, fill="blue") self.app.canvas.update_idletasks() self.app.canvas.after(200) self.app.canvas.itemconfig(CURRENT, fill=current_fill) <file_sep>/tkdraw/tools/tool.py class Tool: """\ Base class for tools. """ def __init__(self, app): # Maintain a reference to the parent application self.app = app # Actions bound by the current tool self.actions = {} def switch(self): """\ Deactivate the previous tool and set the current tool within the parent application. """ if hasattr(self.app, 'current_tool'): self.app.current_tool.deactivate() self.app.current_tool = self def register_binding(self, action, call): """\ Bind available actions to the current canvas and save references for unbinding later. """ function_id = self.app.canvas.bind(action, call) self.actions[function_id] = action def deactivate(self): """\ Unbind all actions and clear saved actions. """ # Unbind all event listeners for function_id, action in self.actions.items(): self.app.canvas.unbind(action, function_id) # Clear all saved actions self.actions.clear() # Clear Tool Options Frame for widget in self.app.frame_option.winfo_children(): widget.destroy() def canvas_coordinates(self, event): return self.app.canvas.canvasx(event.x), self.app.canvas.canvasy(event.y) <file_sep>/tkdraw/tools/create_line.py from tkinter import * #from tkinter.ttk import * from tkdraw.tools.tool import Tool class CreateLineTool(Tool): """\ Multiple segment, straight line tool. Left click to start and create segments. Right click to end. """ def __init__(self, app): super().__init__(app) self.drawing = False # If True a line is currently being drawn self.coordinate_pairs = [] self.object_id = -1 # If -1 then no current line def activate(self, ): # First step on activate should always be switch. self.switch() # Register all callable actions self.register_binding("<Button-1>", self.left_click) self.register_binding("<Motion>", self.motion) self.register_binding("<Button-3>", self.right_click) # Display Tool Options self.line_width = Scale(self.app.frame_option, from_=1, to=10, orient=HORIZONTAL) self.line_width.pack(anchor=W) def left_click(self, event): """\ Start a new line. """ # Get canvas coordinates instead of window x, y = self.canvas_coordinates(event) # Append to the actual line coordinates self.coordinate_pairs.append((x, y)) # Flag that we are now drawing self.drawing = True def motion(self, event): """\ Draw existing segments and preview next segment. """ # Function is called even when a line hasn't been started. Only proceed if drawing if self.drawing: # Get canvas coordinates instead of window x, y = self.canvas_coordinates(event) # Create a temporary copy of the line and append preview coordinates temp_list = self.coordinate_pairs[:] temp_list.append((x, y)) # Remove old temporary line if self.object_id > -1: self.app.canvas.delete(self.object_id) # Draw new line with preview segment self.object_id = self.draw_line(temp_list) def right_click(self, event): """\ Finish the line and reset for next line. """ # Get canvas coordinates instead of window x, y = self.canvas_coordinates(event) # Append to the actual line coordinates self.coordinate_pairs.append((x, y)) # Draw the line on the canvas self.draw_line(self.coordinate_pairs) # Reset object variables for next line self.coordinate_pairs.clear() self.object_id = -1 self.drawing = False def draw_line(self, coordinate_pairs): """\ Draw line and return object id. """ line_width = self.line_width.get() return self.app.canvas.create_line(*coordinate_pairs, # Expand List to arguments fill=self.app.fill_color, width=line_width) <file_sep>/tkdraw/main.py from tkinter import * from tkinter.ttk import * from tkdraw.app import App from tkdraw.config import Config root = Tk() def save_size(event, window): app_config = Config() app_config.save_geometry(window) if __name__ == "__main__": config = Config() # Style Support root.style = Style() # Define window properties root.title('tkdraw') geometry = config.read_geometry() print(geometry) if len(geometry) > 0: root.geometry(geometry) else: root.geometry('200x200') root.bind("<Configure>", save_size) app = App(master=root) app.mainloop()
77e583c4c0aec4c14f55197a29bf9c970a650c13
[ "Markdown", "Python" ]
11
Python
bsiegfreid/tkdraw
a5f75c00679f14a4dff76a49ab2c737f49d87808
e5dec16ae30c075e72525140696803bafda9df53
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.entity; /** * * @author badhr */ public class User { private String username; private String password; private String acc_type; public User() { } public User(String username, String password, String acc_type) { this.username = username; this.password = <PASSWORD>; this.acc_type = acc_type; } /** * @return the user */ public String getUsername() { return username; } /** * @param user the user to set */ public void setUsername(String username) { this.username = username; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the acc_type */ public String getAcc_type() { return acc_type; } /** * @param acc_type the acc_type to set */ public void setAcc_type(String acc_type) { this.acc_type = acc_type; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import lk.beempz.tf.business.SuperBO; import lk.beempz.tf.dto.DebitDTO; import lk.beempz.tf.dto.MonthlyRateDTO; import lk.beempz.tf.dto.UnprocessedDebitDTO; /** * * @author badhr */ public interface MonthlyRateBO extends SuperBO{ //public boolean insertMonthlyRates(MonthlyRateDTO debitDTO)throws Exception; public MonthlyRateDTO getRates(UnprocessedDebitDTO debitDTO)throws Exception; public boolean updateMonthlyRates(MonthlyRateDTO monthlyRateDTO)throws Exception; public ArrayList<MonthlyRateDTO> getAllRates()throws Exception; } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dto; /** * * @author badhr */ public class RouteDTO { private int routeid; private String route; public RouteDTO() { } public RouteDTO(int routeid, String route) { this.routeid = routeid; this.route = route; } /** * @return the routeid */ public int getRouteid() { return routeid; } /** * @param routeid the routeid to set */ public void setRouteid(int routeid) { this.routeid = routeid; } /** * @return the route */ public String getRoute() { return route; } /** * @param route the route to set */ public void setRoute(String route) { this.route = route; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dto; import java.math.BigDecimal; import java.util.Date; /** * * @author badhr */ public class PurchaseDTO { private int purchaseid; private Date date; private int supplierid; private String suppliername; private BigDecimal aKg; private BigDecimal bKg; public PurchaseDTO(int purchaseid, Date date, int supplierid, String suppliername, BigDecimal aKg, BigDecimal bKg) { this.purchaseid = purchaseid; this.date = date; this.supplierid = supplierid; this.suppliername = suppliername; this.aKg = aKg; this.bKg = bKg; } public PurchaseDTO() { } /** * @return the purchaseid */ public int getPurchaseid() { return purchaseid; } /** * @param purchaseid the purchaseid to set */ public void setPurchaseid(int purchaseid) { this.purchaseid = purchaseid; } /** * @return the date */ public Date getDate() { return date; } /** * @param date the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the supplierid */ public int getSupplierid() { return supplierid; } /** * @param supplierid the supplierid to set */ public void setSupplierid(int supplierid) { this.supplierid = supplierid; } /** * @return the suppliername */ public String getSuppliername() { return suppliername; } /** * @param suppliername the suppliername to set */ public void setSuppliername(String suppliername) { this.suppliername = suppliername; } /** * @return the aKg */ public BigDecimal getaKg() { return aKg; } /** * @param aKg the aKg to set */ public void setaKg(BigDecimal aKg) { this.aKg = aKg; } /** * @return the bKg */ public BigDecimal getbKg() { return bKg; } /** * @param bKg the bKg to set */ public void setbKg(BigDecimal bKg) { this.bKg = bKg; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.controller; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXTextField; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import lk.beempz.tf.business.custom.BankBO; import lk.beempz.tf.business.custom.BranchBO; import lk.beempz.tf.business.custom.impl.BankBOImpl; import lk.beempz.tf.business.custom.impl.BranchBOImpl; import lk.beempz.tf.dto.BankDTO; import lk.beempz.tf.dto.BranchDTO; import lk.beempz.tf.main.Startup; import lk.beempz.tf.view.tblmodel.BankTM; import lk.beempz.tf.view.tblmodel.BranchTM; /** * FXML Controller class * * @author badhr */ public class BanksAndBranchesController implements Initializable { @FXML private JFXTextField txtBank; @FXML private JFXButton btnBankAdd; @FXML private JFXButton btnBankRemove; @FXML private JFXButton btnBankEdit; @FXML private TableView<BankTM> tblBanks; @FXML private JFXTextField txtBranch; @FXML private JFXComboBox<String> cmbBank; @FXML private TableView<BranchTM> tblBranch; @FXML private JFXButton txtBRanchRemove; @FXML private JFXButton txtBranchEdit; @FXML private JFXButton txtBranchAdd; /** * Initializes the controller class. */ BankBO bankBO; BranchBO branchBO; public BanksAndBranchesController() { this.branchBO = Startup.getCtx().getBean(BranchBOImpl.class); this.bankBO = Startup.getCtx().getBean(BankBOImpl.class); } @Override public void initialize(URL url, ResourceBundle rb) { tblBanks.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("bankid")); tblBanks.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("bankName")); tblBranch.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("branchid")); tblBranch.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("branchName")); tblBranch.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("bankName")); loadBanks(); loadBranch(); } private void loadBanks(){ ArrayList<BankTM> banks = new ArrayList<>(); ArrayList<String> bankNames = new ArrayList<>(); try { ArrayList<BankDTO> allBanks = bankBO.getAllBanks(); for (BankDTO allBank : allBanks) { banks.add(new BankTM(allBank.getBankid(), allBank.getBankName())); bankNames.add(allBank.getBankName()); } } catch (Exception ex) { Logger.getLogger(BanksAndBranchesController.class.getName()).log(Level.SEVERE, null, ex); } tblBanks.setItems(FXCollections.observableArrayList(banks)); cmbBank.setItems(FXCollections.observableArrayList(bankNames)); } @FXML private void bank_Add(ActionEvent event) { try { BankDTO saveBank = bankBO.saveBank(new BankDTO(-1, txtBank.getText())); if(saveBank == null){ new Alert(Alert.AlertType.ERROR, "Inserting failed", ButtonType.OK).show(); } else{ new Alert(Alert.AlertType.INFORMATION,"Bank added successfully!",ButtonType.OK).show(); } } catch (Exception ex) { Logger.getLogger(BanksAndBranchesController.class.getName()).log(Level.SEVERE, null, ex); } loadBanks(); } @FXML private void bank_Remove(ActionEvent event) { if(tblBanks.getSelectionModel().getSelectedIndex() == -1){ return; } Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Are you sure that you want to delete the bank?", ButtonType.YES,ButtonType.NO); alert.showAndWait(); if(alert.getResult() == ButtonType.NO) return; BankTM bank = tblBanks.getSelectionModel().getSelectedItem(); try { boolean result = bankBO.deleteBank(bank.getBankid()); if(result){ new Alert(Alert.AlertType.INFORMATION, "Bank deleted successfully!", ButtonType.OK).show(); }else{ new Alert(Alert.AlertType.ERROR, "Something went wrong!", ButtonType.OK).show(); } } catch (Exception ex) { Logger.getLogger(BanksAndBranchesController.class.getName()).log(Level.SEVERE, null, ex); } loadBanks(); } @FXML private void bank_Edit(ActionEvent event) { if(tblBanks.getSelectionModel().getSelectedIndex() == -1){ return; } if (txtBank.getText().equals("")) { return; } BankTM bank = tblBanks.getSelectionModel().getSelectedItem(); try { boolean result = bankBO.updateBank(new BankDTO(bank.getBankid(), txtBank.getText())); if (result) { new Alert(Alert.AlertType.INFORMATION, "Bank name updated successfully", ButtonType.OK).show(); txtBank.setText(""); } else{ new Alert(Alert.AlertType.ERROR, "Update failed!", ButtonType.OK).show(); } } catch (Exception ex) { Logger.getLogger(BanksAndBranchesController.class.getName()).log(Level.SEVERE, null, ex); } loadBanks(); } @FXML private void tblBank_Clicked(MouseEvent event) { if(tblBanks.getSelectionModel().getSelectedIndex() == -1){ txtBank.setText(""); return; } BankTM bank = tblBanks.getSelectionModel().getSelectedItem(); txtBank.setText(bank.getBankName()); } @FXML private void tblBranch_Clicked(MouseEvent event) { BranchTM selectedItem = tblBranch.getSelectionModel().getSelectedItem(); txtBranch.setText(selectedItem.getBranchName()); cmbBank.getSelectionModel().select(selectedItem.getBankName()); } @FXML private void branch_Remove(ActionEvent event) { if(tblBranch.getSelectionModel().getSelectedIndex() == -1) return; Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Are you sure that you want to delete the branch?", ButtonType.YES,ButtonType.NO); alert.showAndWait(); if(alert.getResult() == ButtonType.NO) return; try { boolean result = branchBO.deleteBranch(tblBranch.getSelectionModel().getSelectedItem().getBranchid()); if(result){ new Alert(Alert.AlertType.INFORMATION, "Deleted!", ButtonType.OK).show(); txtBranch.setText(""); cmbBank.getSelectionModel().clearSelection(); }else{ new Alert(Alert.AlertType.ERROR, "Delete failed!", ButtonType.OK).show(); } } catch (Exception ex) { Logger.getLogger(BanksAndBranchesController.class.getName()).log(Level.SEVERE, null, ex); } loadBranch(); } @FXML private void branch_Edit(ActionEvent event) { if(tblBranch.getSelectionModel().getSelectedIndex() ==-1){ return; } BranchTM branchTM = tblBranch.getSelectionModel().getSelectedItem(); try { boolean update = branchBO.updateBranch(new BranchDTO(branchTM.getBranchid(), -1, txtBranch.getText(), cmbBank.getValue())); if (update) { new Alert(Alert.AlertType.INFORMATION, "Updated!", ButtonType.OK).show(); txtBranch.setText(""); cmbBank.getSelectionModel().clearSelection(); }else{ new Alert(Alert.AlertType.ERROR, "Updating failed", ButtonType.OK).show(); } } catch (Exception ex) { Logger.getLogger(BanksAndBranchesController.class.getName()).log(Level.SEVERE, null, ex); } loadBranch(); } @FXML private void branch_Add(ActionEvent event) { if(txtBranch.getText().equals("") || cmbBank.getSelectionModel().getSelectedIndex() ==-1) return; try { boolean result = branchBO.saveBranch(new BranchDTO(-1, -1, txtBranch.getText(), cmbBank.getValue())); if(result){ new Alert(Alert.AlertType.INFORMATION, "Branch added successfully!", ButtonType.OK).show(); txtBranch.setText(""); cmbBank.getSelectionModel().clearSelection(); } else{ new Alert(Alert.AlertType.ERROR, "Adding branch failed!", ButtonType.OK).show(); } } catch (Exception ex) { Logger.getLogger(BanksAndBranchesController.class.getName()).log(Level.SEVERE, null, ex); } loadBranch(); } private void loadBranch(){ ArrayList<BranchTM> branchTMs = new ArrayList<>(); try { ArrayList<BranchDTO> branches = branchBO.getBranches(); for (BranchDTO branch : branches) { branchTMs.add(new BranchTM(branch.getBranchid(), branch.getBranchName(), branch.getBankName())); } } catch (Exception ex) { Logger.getLogger(BanksAndBranchesController.class.getName()).log(Level.SEVERE, null, ex); } tblBranch.setItems(FXCollections.observableArrayList(branchTMs)); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.db; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author badhr */ public class DBConnection { private Connection connection; private static DBConnection dbconn; private DBConnection() throws ClassNotFoundException, SQLException, FileNotFoundException, IOException { File dbprop = new File("resources/dbproperties.properties"); FileReader filer = new FileReader(dbprop); Properties prop = new Properties(); prop.load(filer); String host = prop.getProperty("host"); String port = prop.getProperty("port"); String dbname = prop.getProperty("dbname"); String user = prop.getProperty("user"); String pass = prop.getProperty("pass"); Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+dbname, user, pass); } public static DBConnection getInstance() throws ClassNotFoundException, SQLException, FileNotFoundException, IOException{ if(dbconn == null) dbconn = new DBConnection(); return dbconn; } public Connection getConnection(){ return connection; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.entity; import java.math.BigDecimal; import java.util.Date; /** * * @author badhr */ public class Debit { private int debitid; private int purchaseid; private Date debitdate; private int supplierid; private BigDecimal amount; public Debit() { } public Debit(int debitid, int purchaseid, Date debitdate, int supplierid, BigDecimal amount) { this.debitid = debitid; this.purchaseid = purchaseid; this.debitdate = debitdate; this.supplierid = supplierid; this.amount = amount; } /** * @return the debitid */ public int getDebitid() { return debitid; } /** * @param debitid the debitid to set */ public void setDebitid(int debitid) { this.debitid = debitid; } /** * @return the purchaseid */ public int getPurchaseid() { return purchaseid; } /** * @param purchaseid the purchaseid to set */ public void setPurchaseid(int purchaseid) { this.purchaseid = purchaseid; } /** * @return the debitdate */ public Date getDebitdate() { return debitdate; } /** * @param debitdate the debitdate to set */ public void setDebitdate(Date debitdate) { this.debitdate = debitdate; } /** * @return the supplierid */ public int getSupplierid() { return supplierid; } /** * @param supplierid the supplierid to set */ public void setSupplierid(int supplierid) { this.supplierid = supplierid; } /** * @return the amount */ public BigDecimal getAmount() { return amount; } /** * @param amount the amount to set */ public void setAmount(BigDecimal amount) { this.amount = amount; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.view.tblmodel; import java.math.BigDecimal; import java.util.Date; /** * * @author badhr */ public class RateTM { private Date month; private BigDecimal transportRate; private BigDecimal grdAtea; private BigDecimal grdBtea; public RateTM() { } public RateTM(Date month, BigDecimal transportRate, BigDecimal grdAtea, BigDecimal grdBtea) { this.month = month; this.transportRate = transportRate; this.grdAtea = grdAtea; this.grdBtea = grdBtea; } /** * @return the month */ public Date getMonth() { return month; } /** * @param month the month to set */ public void setMonth(Date month) { this.month = month; } /** * @return the transportRate */ public BigDecimal getTransportRate() { return transportRate; } /** * @param transportRate the transportRate to set */ public void setTransportRate(BigDecimal transportRate) { this.transportRate = transportRate; } /** * @return the grdAtea */ public BigDecimal getGrdAtea() { return grdAtea; } /** * @param grdAtea the grdAtea to set */ public void setGrdAtea(BigDecimal grdAtea) { this.grdAtea = grdAtea; } /** * @return the grdBtea */ public BigDecimal getGrdBtea() { return grdBtea; } /** * @param grdBtea the grdBtea to set */ public void setGrdBtea(BigDecimal grdBtea) { this.grdBtea = grdBtea; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dao.custom.impl; import java.sql.ResultSet; import java.util.ArrayList; import lk.beempz.tf.dao.CrudUtil; import lk.beempz.tf.dao.custom.Supplier_BankDAO; import lk.beempz.tf.entity.Supplier_Bank; import lk.beempz.tf.entity.Supplier_Bank_PK; import org.springframework.stereotype.Component; @Component public class Supplier_BankDAOImpl implements Supplier_BankDAO { @Override public boolean save(Supplier_Bank entity) throws Exception { return CrudUtil.executeUpdate("insert into supplier_bank values(?,?,?)", entity.getSupplier_Bank_PK().getBranchid(),entity.getSupplier_Bank_PK().getSupplierid(),entity.getAcc_no()); } @Override public boolean delete(Supplier_Bank_PK id) throws Exception { return CrudUtil.executeUpdate("delete from supplier_bank where branchid = ? and supplierid = ?", id.getBranchid(),id.getSupplierid()); } @Override public boolean update(Supplier_Bank entity) throws Exception { return CrudUtil.executeUpdate("update supplier_bank set acc_no = ? where branchid = ? and supplierid = ?", entity.getAcc_no(),entity.getSupplier_Bank_PK().getBranchid(),entity.getSupplier_Bank_PK().getSupplierid()); } @Override public ArrayList<Supplier_Bank> getAll() throws Exception { ArrayList<Supplier_Bank> supplier_banks = new ArrayList<>(); ResultSet rs = CrudUtil.executeQuery("select * from supplier_bank"); while (rs.next()) { supplier_banks.add(new Supplier_Bank(new Supplier_Bank_PK(rs.getInt(1), rs.getInt(2)), rs.getString(3))); } return supplier_banks; } @Override public Supplier_Bank findById(Supplier_Bank_PK id) throws Exception { ResultSet rs = CrudUtil.executeQuery("select * from supplier_bank where branchid = ? and supplierid = ?", id.getBranchid(),id.getSupplierid()); if (rs.next()) { return new Supplier_Bank(new Supplier_Bank_PK(rs.getInt(1), rs.getInt(2)), rs.getString(3)); } return null; } @Override public Supplier_Bank saveAndGetGenerated(Supplier_Bank entity) throws Exception { return null; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dto; /** * * @author badhr */ public class CreditTypeDTO { private int creditTypeid; private String creditType; public CreditTypeDTO() { } public CreditTypeDTO(int creditTypeid, String creditType) { this.creditTypeid = creditTypeid; this.creditType = creditType; } /** * @return the creditTypeid */ public int getCreditTypeid() { return creditTypeid; } /** * @param creditTypeid the creditTypeid to set */ public void setCreditTypeid(int creditTypeid) { this.creditTypeid = creditTypeid; } /** * @return the creditType */ public String getCreditType() { return creditType; } /** * @param creditType the creditType to set */ public void setCreditType(String creditType) { this.creditType = creditType; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom.impl; import java.util.logging.Level; import java.util.logging.Logger; import lk.beempz.tf.business.custom.Supplier_BankBO; import lk.beempz.tf.dao.custom.Supplier_BankDAO; import lk.beempz.tf.dto.Supplier_BankDTO; import lk.beempz.tf.entity.Supplier_Bank; import lk.beempz.tf.entity.Supplier_Bank_PK; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Supplier_BankBOImpl implements Supplier_BankBO { @Autowired private Supplier_BankDAO supplier_BankDAO; public Supplier_BankBOImpl() { } @Override public boolean addSuplierBank(Supplier_BankDTO supplier_BankDTO) { boolean result = false; try { result = supplier_BankDAO.save(new Supplier_Bank(new Supplier_Bank_PK(supplier_BankDTO.getBranchid(), supplier_BankDTO.getSupplierid()), supplier_BankDTO.getAcc_no())); } catch (Exception ex) { Logger.getLogger(Supplier_BankBOImpl.class.getName()).log(Level.SEVERE, null, ex); } return result; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.controller; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.animation.ScaleTransition; import javafx.animation.TranslateTransition; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.util.Duration; /** * FXML Controller class * * @author badhr */ public class MainPageFormController implements Initializable { @FXML private Pane paneCustomer; @FXML private AnchorPane root; @FXML private Pane paneBanks; @FXML private Pane panePayment; @FXML private Pane panePurchase; @FXML private Pane paneRoutes; @FXML private Pane paneRates; @FXML private Pane paneReports; @FXML private Pane paneAccounts; @FXML private Pane paneSettings; @FXML private Pane paneSettings2; @FXML private Pane paneSettings1; @FXML private Pane paneExit; @FXML private Pane paneRoutes1; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { TranslateTransition tt = new TranslateTransition(Duration.millis(2000), root); tt.setFromX(0); tt.setToX(1.0); tt.play(); } @FXML private void onIconEntered(MouseEvent event) { if (event.getSource() instanceof Pane) { Pane pane = (Pane) event.getSource(); ScaleTransition st = new ScaleTransition(Duration.millis(200), pane); st.setFromX(1.0); st.setFromY(1.0); st.setToX(1.3); st.setToY(1.3); st.play(); } } @FXML private void onIconClicked(MouseEvent event) { Parent root = null; String title = "TeaFactory | "; if (event.getSource() instanceof Pane) { try { Pane pane = (Pane) event.getSource(); switch (pane.getId()) { case "paneCustomer": root = FXMLLoader.load(getClass().getResource("/lk/beempz/tf/view/CustomerForm.fxml")); title += "Customer Details"; break; case "paneBanks": root = FXMLLoader.load(getClass().getResource("/lk/beempz/tf/view/BanksAndBranches.fxml")); title += "Bank Details"; break; case "panePayment": root = FXMLLoader.load(getClass().getResource("/lk/beempz/tf/view/SupplierAccounts.fxml")); title += "Supplier Details"; break; case "panePurchase": root = FXMLLoader.load(getClass().getResource("/lk/beempz/tf/view/PurchasesForm.fxml")); title += "Purchases"; break; case "paneRoutes": root = FXMLLoader.load(getClass().getResource("/lk/beempz/tf/view/Routes.fxml")); title += "Routes"; break; case "paneReports": root = FXMLLoader.load(getClass().getResource("/lk/beempz/tf/view/Banks.fxml")); title += "Reports"; break; case "paneRates": root = FXMLLoader.load(getClass().getResource("/lk/beempz/tf/view/Rates.fxml")); title += "Monthly Rates"; break; case "paneAccounts": root = FXMLLoader.load(getClass().getResource("/lk/beempz/tf/view/Reports.fxml")); title += "Accounts"; break; case "paneExit": Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Are you sure that you need to exit?", ButtonType.YES,ButtonType.NO); alert.showAndWait(); if(alert.getResult() == ButtonType.NO) return; System.exit(0); break; } } catch (IOException ex) { Logger.getLogger(MainPageFormController.class.getName()).log(Level.SEVERE, null, ex); } } if (root == null) { return; } Scene scene = new Scene(root); Stage stage = new Stage(); stage.setScene(scene); stage.setResizable(false); stage.setTitle(title); stage.showAndWait(); } @FXML private void onIconExited(MouseEvent event) { if (event.getSource() instanceof Pane) { Pane pane = (Pane) event.getSource(); ScaleTransition st = new ScaleTransition(Duration.millis(200), pane); st.setFromX(1.3); st.setFromY(1.3); st.setToX(1.0); st.setToY(1.0); st.play(); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.controller; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXDatePicker; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.sql.SQLException; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import lk.beempz.tf.business.custom.SupplierBO; import lk.beempz.tf.business.custom.impl.SupplierBOImpl; import lk.beempz.tf.db.DBConnection; import lk.beempz.tf.dto.SupplierDTO; import lk.beempz.tf.main.Startup; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperPrintManager; import net.sf.jasperreports.view.JasperViewer; /** * FXML Controller class * * @author badhr */ public class ReportsController implements Initializable { @FXML private JFXDatePicker dtFrom; @FXML private JFXDatePicker dtTo; @FXML private JFXComboBox<String> cmbReport; @FXML private JFXComboBox<String> cmbSupplier; SupplierBO supplierBO; public ReportsController() { this.supplierBO = Startup.getCtx().getBean(SupplierBOImpl.class); } /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO setCmbs(); } private void setCmbs(){ ArrayList<String> suppliers = new ArrayList<>(); ArrayList<String> reports = new ArrayList<>(); try { ArrayList<SupplierDTO> suppliers1 = supplierBO.getSuppliers(); for (SupplierDTO supplierDTO : suppliers1) { suppliers.add(supplierDTO.getSupplierid()+""); } reports.add("Credit Report"); reports.add("Debit Report"); } catch (Exception ex) { Logger.getLogger(ReportsController.class.getName()).log(Level.SEVERE, null, ex); } cmbSupplier.setItems(FXCollections.observableArrayList(suppliers)); cmbReport.setItems(FXCollections.observableArrayList(reports)); } @FXML private void btnPrint_OnAction(ActionEvent event) { InputStream strm = getInput(cmbReport.getValue()); HashMap map = setHashes(); try { JasperPrint fillReport = JasperFillManager.fillReport(strm, map,DBConnection.getInstance().getConnection()); JasperPrintManager.printReport(fillReport, true); } catch (ClassNotFoundException | SQLException | JRException ex) { Logger.getLogger(BanksController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ReportsController.class.getName()).log(Level.SEVERE, null, ex); } } private InputStream getInput(String input){ String path = ""; switch(input){ case "Credit Report": path = "/lk/beempz/tf/reports/CreditReport.jasper"; break; case "Debit Report": path = "/lk/beempz/tf/reports/DebitReport.jasper"; break; default: return null; } InputStream strm = getClass().getResourceAsStream(path); return strm; } private HashMap setHashes(){ HashMap map = new HashMap(); map.put("fromdate", Date.from(dtFrom.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant())); map.put("todate", Date.from(dtTo.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant())); map.put("supid", Integer.parseInt(cmbSupplier.getValue())); return map; } @FXML private void btnView_OnAction(ActionEvent event) { InputStream strm = getInput(cmbReport.getValue()); HashMap map = setHashes(); try { JasperPrint fillReport = JasperFillManager.fillReport(strm, map,DBConnection.getInstance().getConnection()); File pdf = File.createTempFile("output.", ".pdf"); JasperViewer.viewReport(fillReport, false); JasperExportManager.exportReportToPdfStream(fillReport,new FileOutputStream(pdf)); } catch (ClassNotFoundException | SQLException | JRException | IOException ex) { Logger.getLogger(BanksController.class.getName()).log(Level.SEVERE, null, ex); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.view.tblmodel; /** * * @author badhr */ public class BranchTM { private int branchid; private String branchName; private String bankName; public BranchTM() { } public BranchTM(int branchid, String branchName, String bankName) { this.branchid = branchid; this.branchName = branchName; this.bankName = bankName; } /** * @return the branchid */ public int getBranchid() { return branchid; } /** * @param branchid the branchid to set */ public void setBranchid(int branchid) { this.branchid = branchid; } /** * @return the branchName */ public String getBranchName() { return branchName; } /** * @param branchName the branchName to set */ public void setBranchName(String branchName) { this.branchName = branchName; } /** * @return the bankName */ public String getBankName() { return bankName; } /** * @param bankName the bankName to set */ public void setBankName(String bankName) { this.bankName = bankName; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dao.custom.impl; import java.sql.ResultSet; import java.util.ArrayList; import lk.beempz.tf.dao.CrudUtil; import lk.beempz.tf.dao.custom.SupplierDAO; import lk.beempz.tf.entity.Supplier; import org.springframework.stereotype.Component; @Component public class SupplierDAOImpl implements SupplierDAO { @Override public boolean save(Supplier entity) throws Exception { return CrudUtil.executeUpdate("insert into supplier values(?,?,?,?,?)", entity.getSupplierno(),entity.getName(),entity.getRoute(),entity.getPhone(),entity.getAddress()); } @Override public boolean delete(Integer id) throws Exception { return CrudUtil.executeUpdate("delete from supplier where supplierno = ?", id); } @Override public boolean update(Supplier entity) throws Exception { return CrudUtil.executeUpdate("update supplier set name = ? , route = ? , phone = ? , address = ? where supplierno = ?", entity.getName(),entity.getRoute(),entity.getPhone(),entity.getAddress(),entity.getSupplierno()); } @Override public ArrayList<Supplier> getAll() throws Exception { ArrayList<Supplier> suppliers = new ArrayList<>(); ResultSet rs = CrudUtil.executeQuery("select * from supplier"); while (rs.next()) { suppliers.add(new Supplier(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4), rs.getString(5))); } return suppliers; } @Override public Supplier findById(Integer id) throws Exception { ResultSet rs = CrudUtil.executeQuery("Select * from supplier where supplierno = ?", id); if (rs.next()) { return new Supplier(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4), rs.getString(5)); } return null; } @Override public Supplier saveAndGetGenerated(Supplier entity) throws Exception { ResultSet rs = CrudUtil.executeUpdateWithGeneratedKeys("insert into supplier(name, route, phone,address) values(?,?,?,?)", entity.getName(),entity.getRoute(),entity.getPhone(),entity.getAddress()); if(rs.next()){ return new Supplier(rs.getInt(1), entity.getName(), entity.getRoute(), entity.getPhone(), entity.getAddress()); } return null; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dto; /** * * @author badhr */ public class BankDTO { private int bankid; private String bankName; public BankDTO() { } public BankDTO(int bankid, String bankName) { this.bankid = bankid; this.bankName = bankName; } /** * @return the bankid */ public int getBankid() { return bankid; } /** * @param bankid the bankid to set */ public void setBankid(int bankid) { this.bankid = bankid; } /** * @return the bankName */ public String getBankName() { return bankName; } /** * @param bankName the bankName to set */ public void setBankName(String bankName) { this.bankName = bankName; } }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.controller; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXTextField; import java.math.BigDecimal; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import lk.beempz.tf.business.custom.PurchaseBO; import lk.beempz.tf.business.custom.SupplierBO; import lk.beempz.tf.business.custom.impl.PurchaseBOImpl; import lk.beempz.tf.business.custom.impl.SupplierBOImpl; import lk.beempz.tf.dto.PurchaseDTO; import lk.beempz.tf.dto.SupplierDTO; import lk.beempz.tf.main.Startup; /** * FXML Controller class * * @author badhr */ public class AddNewTransactionController implements Initializable { @FXML private JFXComboBox<String> cmbSupplier; @FXML private JFXTextField txtSupplier; @FXML private JFXTextField txtGradeA; @FXML private JFXTextField txtGradeB; @FXML private JFXButton btnAdd; SupplierBO supplierBO; PurchaseBO purchaseBO; public AddNewTransactionController() { this.purchaseBO = Startup.getCtx().getBean(PurchaseBOImpl.class); this.supplierBO = Startup.getCtx().getBean(SupplierBOImpl.class); } /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO setCmb(); } private void setCmb(){ ArrayList<String> supplierids = new ArrayList<>(); try { ArrayList<SupplierDTO> suppliers = supplierBO.getSuppliers(); for (SupplierDTO supplier : suppliers) { supplierids.add(supplier.getSupplierid()+""); } } catch (Exception ex) { Logger.getLogger(AddNewTransactionController.class.getName()).log(Level.SEVERE, null, ex); } cmbSupplier.setItems(FXCollections.observableArrayList(supplierids)); } @FXML private void cmbChanged(ActionEvent event) { try { SupplierDTO findSupplier = supplierBO.findSupplier(Integer.parseInt(cmbSupplier.getValue())); if(findSupplier == null || findSupplier.getName().equals("")) return; txtSupplier.setText(findSupplier.getName()); } catch (Exception ex) { Logger.getLogger(AddNewTransactionController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void btnAdd_OnAction(ActionEvent event) { if(!txtGradeA.getText().matches("^\\d*(\\.?\\d{0,3})$") || !txtGradeB.getText().matches("^\\d*(\\.?\\d{0,3})$")){ new Alert(Alert.AlertType.ERROR, "Please enter a valid quantity", ButtonType.OK).show(); return; } try { boolean result = purchaseBO.addPurchase(new PurchaseDTO(-1, new Date(), Integer.parseInt(cmbSupplier.getValue()), txtSupplier.getText(), new BigDecimal(txtGradeA.getText()), new BigDecimal(txtGradeB.getText()))); if(result){ new Alert(Alert.AlertType.INFORMATION, "Transaction added successfully!", ButtonType.OK).show(); clearData(); }else{ new Alert(Alert.AlertType.ERROR, "Transaction not added.. Please try again!", ButtonType.OK).show(); } } catch (Exception ex) { Logger.getLogger(AddNewTransactionController.class.getName()).log(Level.SEVERE, null, ex); } } private void clearData(){ txtSupplier.setText(""); txtGradeA.setText(""); txtGradeB.setText(""); cmbSupplier.getSelectionModel().clearSelection(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom; import java.util.ArrayList; import java.util.Date; import lk.beempz.tf.business.SuperBO; import lk.beempz.tf.dto.DebitDTO; import lk.beempz.tf.dto.UnprocessedDebitDTO; /** * * @author badhr */ public interface DebitBO extends SuperBO{ public ArrayList<DebitDTO> getDebitList(Date from , Date to)throws Exception; public boolean insertDebit(DebitDTO debitDTO)throws Exception; public boolean updateDebit(DebitDTO debitDTO)throws Exception; public boolean deleteDebit(int debitId)throws Exception; public boolean deleteByPurchase(int purchaseid)throws Exception; // public ArrayList<DebitDTO> getByMonth(Date date)throws Exception; public DebitDTO getAllByPurchaseID(int purchaseid)throws Exception; } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dao.custom.impl; import java.sql.ResultSet; import java.util.ArrayList; import lk.beempz.tf.dao.CrudUtil; import lk.beempz.tf.dao.custom.BranchDAO; import lk.beempz.tf.entity.Branch; import org.springframework.stereotype.Component; @Component public class BranchDAOImpl implements BranchDAO { @Override public boolean save(Branch entity) throws Exception { return CrudUtil.executeUpdate("insert into branch values(?,?,?)", entity.getBranchid(),entity.getBankid(),entity.getBranchName()); } @Override public boolean delete(Integer id) throws Exception { return CrudUtil.executeUpdate("delete from branch where branchid = ?", id); } @Override public boolean update(Branch entity) throws Exception { return CrudUtil.executeUpdate("update branch set bankid = ? , branchName = ? where branchid = ?", entity.getBankid(),entity.getBranchName(),entity.getBranchid()); } @Override public ArrayList<Branch> getAll() throws Exception { ArrayList<Branch> branches = new ArrayList<>(); ResultSet rs = CrudUtil.executeQuery("select * from branch"); while(rs.next()){ branches.add(new Branch(rs.getInt(1), rs.getInt(2), rs.getString(3))); } return branches; } @Override public Branch findById(Integer id) throws Exception { ResultSet rs = CrudUtil.executeQuery("select * from branch where branchid = ?", id); if(rs.next()){ return new Branch(rs.getInt(1), rs.getInt(2), rs.getString(3)); } return null; } @Override public Branch saveAndGetGenerated(Branch entity) throws Exception { ResultSet rs = CrudUtil.executeUpdateWithGeneratedKeys("insert into branch(bankid,branchName) values(?,?)", entity.getBankid(),entity.getBranchName()); if(rs.next()){ return new Branch(rs.getInt(1), entity.getBankid(), entity.getBranchName()); } return null; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dto; import java.math.BigDecimal; import java.util.Date; /** * * @author badhr */ public class CreditDTO { private int creditid; private int supplierid; private String suppliername; private int creditType; private String credit_typename; private Date date; private BigDecimal amount; public CreditDTO() { } public CreditDTO(int creditid, int supplierid, String suppliername, int creditType, String credit_typename, Date date, BigDecimal amount) { this.creditid = creditid; this.supplierid = supplierid; this.suppliername = suppliername; this.creditType = creditType; this.credit_typename = credit_typename; this.date = date; this.amount = amount; } /** * @return the creditid */ public int getCreditid() { return creditid; } /** * @param creditid the creditid to set */ public void setCreditid(int creditid) { this.creditid = creditid; } /** * @return the supplierid */ public int getSupplierid() { return supplierid; } /** * @param supplierid the supplierid to set */ public void setSupplierid(int supplierid) { this.supplierid = supplierid; } /** * @return the suppliername */ public String getSuppliername() { return suppliername; } /** * @param suppliername the suppliername to set */ public void setSuppliername(String suppliername) { this.suppliername = suppliername; } /** * @return the creditType */ public int getCreditType() { return creditType; } /** * @param creditType the creditType to set */ public void setCreditType(int creditType) { this.creditType = creditType; } /** * @return the credit_typename */ public String getCredit_typename() { return credit_typename; } /** * @param credit_typename the credit_typename to set */ public void setCredit_typename(String credit_typename) { this.credit_typename = credit_typename; } /** * @return the date */ public Date getDate() { return date; } /** * @param date the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the amount */ public BigDecimal getAmount() { return amount; } /** * @param amount the amount to set */ public void setAmount(BigDecimal amount) { this.amount = amount; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom; import java.util.ArrayList; import java.util.Date; import lk.beempz.tf.business.SuperBO; import lk.beempz.tf.dto.CreditDTO; /** * * @author badhr */ public interface CreditBO extends SuperBO{ public boolean insertCredit(CreditDTO creditDTO)throws Exception; public ArrayList<CreditDTO> getAllCredits(Date from , Date to)throws Exception; public boolean deleteCredit(CreditDTO creditDTO)throws Exception; } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dto; import java.math.BigDecimal; import java.util.Date; /** * * @author badhr */ public class DebitDTO { private int debitid; private Date date; private int purchaseid; private int supplierid; private String name; private BigDecimal amount; public DebitDTO() { } public DebitDTO(int debitid, Date date, int purchaseid, int supplierid, String name, BigDecimal amount) { this.debitid = debitid; this.date = date; this.purchaseid = purchaseid; this.supplierid = supplierid; this.name = name; this.amount = amount; } /** * @return the debitid */ public int getDebitid() { return debitid; } /** * @param debitid the debitid to set */ public void setDebitid(int debitid) { this.debitid = debitid; } /** * @return the date */ public Date getDate() { return date; } /** * @param date the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the purchaseid */ public int getPurchaseid() { return purchaseid; } /** * @param purchaseid the purchaseid to set */ public void setPurchaseid(int purchaseid) { this.purchaseid = purchaseid; } /** * @return the supplierid */ public int getSupplierid() { return supplierid; } /** * @param supplierid the supplierid to set */ public void setSupplierid(int supplierid) { this.supplierid = supplierid; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the amount */ public BigDecimal getAmount() { return amount; } /** * @param amount the amount to set */ public void setAmount(BigDecimal amount) { this.amount = amount; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.controller; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXDatePicker; import java.io.IOException; import java.net.URL; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import lk.beempz.tf.business.custom.CreditBO; import lk.beempz.tf.business.custom.impl.CreditBOImpl; import lk.beempz.tf.dto.CreditDTO; import lk.beempz.tf.main.Startup; import lk.beempz.tf.view.tblmodel.CreditTM; /** * FXML Controller class * * @author badhr */ public class SupplierAccountsController implements Initializable { @FXML private JFXDatePicker dateFrom; @FXML private JFXDatePicker dateTo; @FXML private JFXButton btnShow; @FXML private JFXComboBox<String> cmbSortBy; @FXML private Label lblTotal; @FXML private TableView<CreditTM> tblTransaction; ArrayList<CreditTM> debits = new ArrayList<>(); @FXML private AnchorPane root; CreditBO creditBO; public SupplierAccountsController() { this.creditBO = Startup.getCtx().getBean(CreditBOImpl.class); } /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { tblTransaction.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("date")); tblTransaction.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("supplierno")); tblTransaction.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("name")); tblTransaction.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("description")); tblTransaction.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("amount")); loadTable(); } @FXML private void btn_Show_OnClick(ActionEvent event) { if(dateFrom.getValue() == null || dateTo.getValue() == null) return; ArrayList<CreditTM> creditTMs = new ArrayList<>(); Date from = Date.from(dateFrom.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant()); Date to = Date.from(dateTo.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant()); try { ArrayList<CreditDTO> credits = creditBO.getAllCredits(from, to); for (CreditDTO credit : credits) { creditTMs.add(new CreditTM(credit.getCreditid(), credit.getDate(), credit.getSupplierid(), credit.getSuppliername(), credit.getCredit_typename(), credit.getAmount())); } } catch (Exception ex) { Logger.getLogger(SupplierAccountsController.class.getName()).log(Level.SEVERE, null, ex); } setTable(creditTMs); } @FXML private void tblClicked(MouseEvent event) { } private void loadTable() { ArrayList<CreditTM> creditTMs = new ArrayList<>(); try { ArrayList<CreditDTO> allCredits = creditBO.getAllCredits(null, null); for (CreditDTO allCredit : allCredits) { creditTMs.add(new CreditTM(allCredit.getCreditid(), allCredit.getDate(), allCredit.getSupplierid(), allCredit.getSuppliername(), allCredit.getCredit_typename(), allCredit.getAmount())); } } catch (Exception ex) { Logger.getLogger(SupplierAccountsController.class.getName()).log(Level.SEVERE, null, ex); } setTable(creditTMs); } public void setTable(ArrayList<CreditTM> creditTMs){ tblTransaction.setItems(FXCollections.observableArrayList(creditTMs)); } @FXML private void btnClickhere_OnAction(ActionEvent event) { try { Parent root = FXMLLoader.load(getClass().getResource("/lk/beempz/tf/view/TodayTransactions.fxml")); Scene scene = new Scene(root); Stage primaryStage = (Stage) this.root.getScene().getWindow(); primaryStage.setScene(scene); primaryStage.show(); } catch (IOException ex) { Logger.getLogger(SupplierAccountsController.class.getName()).log(Level.SEVERE, null, ex); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.entity; /** * * @author badhr */ public class Route { private int routeid; private String routename; public Route() { } public Route(int routeid, String routename) { this.routeid = routeid; this.routename = routename; } /** * @return the routeid */ public int getRouteid() { return routeid; } /** * @param routeid the routeid to set */ public void setRouteid(int routeid) { this.routeid = routeid; } /** * @return the routename */ public String getRoutename() { return routename; } /** * @param routename the routename to set */ public void setRoutename(String routename) { this.routename = routename; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom.impl; import java.util.ArrayList; import lk.beempz.tf.business.custom.BankBO; import lk.beempz.tf.dao.custom.BankDAO; import lk.beempz.tf.dto.BankDTO; import lk.beempz.tf.entity.Bank; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BankBOImpl implements BankBO { @Autowired BankDAO bankDAO; public BankBOImpl(){} @Override public BankDTO saveBank(BankDTO bank) throws Exception { Bank bankent = bankDAO.saveAndGetGenerated(new Bank(bank.getBankid(), bank.getBankName())); if(bankent == null) return null; return new BankDTO(bankent.getBankid(), bankent.getBankName()); } @Override public boolean updateBank(BankDTO bank) throws Exception { return bankDAO.update(new Bank(bank.getBankid(), bank.getBankName())); } @Override public boolean deleteBank(int bankid) throws Exception { return bankDAO.delete(bankid); } @Override public ArrayList<BankDTO> getAllBanks() throws Exception { ArrayList<BankDTO> bankDTOs = new ArrayList<>(); ArrayList<Bank> banks = bankDAO.getAll(); for (Bank bank : banks) { bankDTOs.add(new BankDTO(bank.getBankid(), bank.getBankName())); } return bankDTOs; } @Override public int getBankID(String bankName) throws Exception { return bankDAO.getID(bankName); } @Override public String findBankName(int bankid) throws Exception { return bankDAO.findById(bankid).getBankName(); } void mymethod(){ System.out.println("This is mymethod"); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.controller; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXDatePicker; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.sql.SQLException; import java.time.ZoneId; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import lk.beempz.tf.db.DBConnection; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperPrintManager; import net.sf.jasperreports.view.JasperViewer; /** * FXML Controller class * * @author badhr */ public class BanksController implements Initializable { @FXML private JFXDatePicker dtFrom; @FXML private JFXDatePicker dtTo; @FXML private JFXComboBox<String> cmbReport; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { setCmb(); } private void setCmb(){ ArrayList<String> reports = new ArrayList<>(); reports.add("Purchase Report"); reports.add("Bank Report"); cmbReport.setItems(FXCollections.observableArrayList(reports)); } @FXML private void btnPrint_OnAction(ActionEvent event) { InputStream strm = getInput(cmbReport.getValue()); HashMap map = setHashes(); try { JasperPrint fillReport = JasperFillManager.fillReport(strm, map,DBConnection.getInstance().getConnection()); JasperPrintManager.printReport(fillReport, true); } catch (ClassNotFoundException | SQLException | JRException | IOException ex) { Logger.getLogger(BanksController.class.getName()).log(Level.SEVERE, null, ex); } } private InputStream getInput(String input){ String path = ""; switch(input){ case "Purchase Report": path = "/lk/beempz/tf/reports/PurchasesReports_1.jasper"; break; case "Bank Report": path = "/lk/beempz/tf/reports/Bank_1.jasper"; break; default: return null; } InputStream strm = getClass().getResourceAsStream(path); return strm; } private HashMap setHashes(){ HashMap map = new HashMap(); map.put("fromdate", Date.from(dtFrom.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant())); map.put("todate", Date.from(dtTo.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant())); return map; } @FXML private void btnView_OnAction(ActionEvent event) { InputStream strm = getInput(cmbReport.getValue()); HashMap map = setHashes(); try { JasperPrint fillReport = JasperFillManager.fillReport(strm, map,DBConnection.getInstance().getConnection()); File pdf = File.createTempFile("output.", ".pdf"); JasperViewer.viewReport(fillReport, false); JasperExportManager.exportReportToPdfStream(fillReport,new FileOutputStream(pdf)); } catch (ClassNotFoundException | SQLException | JRException | IOException ex) { Logger.getLogger(BanksController.class.getName()).log(Level.SEVERE, null, ex); } } } <file_sep>-- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 5.7.17-log - MySQL Community Server (GPL) -- Server OS: Win64 -- HeidiSQL Version: 9.5.0.5196 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping database structure for teafactory CREATE DATABASE IF NOT EXISTS `teafactory` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `teafactory`; -- Dumping structure for table teafactory.bank CREATE TABLE IF NOT EXISTS `bank` ( `bankid` int(11) NOT NULL AUTO_INCREMENT, `bankName` varchar(100) NOT NULL, PRIMARY KEY (`bankid`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.bank: ~4 rows (approximately) /*!40000 ALTER TABLE `bank` DISABLE KEYS */; INSERT INTO `bank` (`bankid`, `bankName`) VALUES (1, 'Commercial Credit'), (3, 'HSBC'), (4, 'DFCC'), (5, 'HNB'); /*!40000 ALTER TABLE `bank` ENABLE KEYS */; -- Dumping structure for table teafactory.branch CREATE TABLE IF NOT EXISTS `branch` ( `branchid` int(11) NOT NULL AUTO_INCREMENT, `bankid` int(11) DEFAULT NULL, `branchName` varchar(100) DEFAULT NULL, PRIMARY KEY (`branchid`), KEY `FK_branch_bank` (`bankid`), CONSTRAINT `FK_branch_bank` FOREIGN KEY (`bankid`) REFERENCES `bank` (`bankid`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.branch: ~5 rows (approximately) /*!40000 ALTER TABLE `branch` DISABLE KEYS */; INSERT INTO `branch` (`branchid`, `bankid`, `branchName`) VALUES (2, 1, 'Walampuri'), (3, 1, 'Wallawaththa'), (4, 3, 'Kasagahawaththa'), (5, 4, 'Gampaha'), (6, 3, 'kelaniya'); /*!40000 ALTER TABLE `branch` ENABLE KEYS */; -- Dumping structure for table teafactory.credit CREATE TABLE IF NOT EXISTS `credit` ( `creditid` int(11) NOT NULL AUTO_INCREMENT, `supplierid` int(11) NOT NULL, `credit_type` int(11) NOT NULL, `date` date NOT NULL, `amount` decimal(10,2) NOT NULL, PRIMARY KEY (`creditid`), KEY `FK_credit_supplier` (`supplierid`), KEY `FK_credit_credit_type` (`credit_type`), CONSTRAINT `FK_credit_credit_type` FOREIGN KEY (`credit_type`) REFERENCES `credit_type` (`typeid`), CONSTRAINT `FK_credit_supplier` FOREIGN KEY (`supplierid`) REFERENCES `supplier` (`supplierno`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.credit: ~3 rows (approximately) /*!40000 ALTER TABLE `credit` DISABLE KEYS */; INSERT INTO `credit` (`creditid`, `supplierid`, `credit_type`, `date`, `amount`) VALUES (3, 3, 1, '2018-06-29', 20000.00), (4, 3, 1, '2018-06-29', 200.00), (5, 3, 1, '2018-06-30', 122.00); /*!40000 ALTER TABLE `credit` ENABLE KEYS */; -- Dumping structure for table teafactory.credit_type CREATE TABLE IF NOT EXISTS `credit_type` ( `typeid` int(11) NOT NULL AUTO_INCREMENT, `type_name` varchar(50) DEFAULT NULL, PRIMARY KEY (`typeid`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.credit_type: ~1 rows (approximately) /*!40000 ALTER TABLE `credit_type` DISABLE KEYS */; INSERT INTO `credit_type` (`typeid`, `type_name`) VALUES (1, 'PAYMENT'); /*!40000 ALTER TABLE `credit_type` ENABLE KEYS */; -- Dumping structure for table teafactory.debit CREATE TABLE IF NOT EXISTS `debit` ( `debitid` int(11) NOT NULL AUTO_INCREMENT, `purchaseid` int(11) NOT NULL DEFAULT '0', `debitdate` date NOT NULL, `supplierid` int(11) NOT NULL, `amount` decimal(10,2) NOT NULL, PRIMARY KEY (`debitid`), KEY `FK_debit_supplier` (`supplierid`), KEY `FK_debit_purchase` (`purchaseid`), CONSTRAINT `FK_debit_purchase` FOREIGN KEY (`purchaseid`) REFERENCES `purchase` (`purchase_id`), CONSTRAINT `FK_debit_supplier` FOREIGN KEY (`supplierid`) REFERENCES `supplier` (`supplierno`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.debit: ~3 rows (approximately) /*!40000 ALTER TABLE `debit` DISABLE KEYS */; INSERT INTO `debit` (`debitid`, `purchaseid`, `debitdate`, `supplierid`, `amount`) VALUES (4, 4, '2018-06-28', 3, 1960.00), (5, 5, '2018-06-28', 3, 3136.00), (7, 7, '2018-06-29', 3, 1960.00); /*!40000 ALTER TABLE `debit` ENABLE KEYS */; -- Dumping structure for table teafactory.purchase CREATE TABLE IF NOT EXISTS `purchase` ( `purchase_id` int(11) NOT NULL AUTO_INCREMENT, `purchase_date` date NOT NULL, `supplierid` int(11) NOT NULL, `akg` decimal(10,3) NOT NULL, `bkg` decimal(10,3) NOT NULL, PRIMARY KEY (`purchase_id`), KEY `FK_purchase_supplier` (`supplierid`), CONSTRAINT `FK_purchase_supplier` FOREIGN KEY (`supplierid`) REFERENCES `supplier` (`supplierno`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.purchase: ~3 rows (approximately) /*!40000 ALTER TABLE `purchase` DISABLE KEYS */; INSERT INTO `purchase` (`purchase_id`, `purchase_date`, `supplierid`, `akg`, `bkg`) VALUES (4, '2018-06-28', 3, 10.000, 10.000), (5, '2018-06-28', 3, 22.000, 10.000), (7, '2018-06-29', 3, 10.000, 10.000); /*!40000 ALTER TABLE `purchase` ENABLE KEYS */; -- Dumping structure for table teafactory.rate CREATE TABLE IF NOT EXISTS `rate` ( `rateMonth` date NOT NULL, `akgper` decimal(10,2) DEFAULT NULL, `bkgper` decimal(10,2) DEFAULT NULL, `travelling` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`rateMonth`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.rate: ~4 rows (approximately) /*!40000 ALTER TABLE `rate` DISABLE KEYS */; INSERT INTO `rate` (`rateMonth`, `akgper`, `bkgper`, `travelling`) VALUES ('2018-06-27', 100.00, 100.00, 2.00), ('2018-07-03', 200.00, 240.00, 22.00), ('2018-08-01', 123.00, 122.00, 21.00), ('2018-09-01', 12.33, 120.55, 2.55); /*!40000 ALTER TABLE `rate` ENABLE KEYS */; -- Dumping structure for table teafactory.route CREATE TABLE IF NOT EXISTS `route` ( `routeid` int(11) NOT NULL AUTO_INCREMENT, `routename` varchar(50) DEFAULT NULL, PRIMARY KEY (`routeid`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.route: ~1 rows (approximately) /*!40000 ALTER TABLE `route` DISABLE KEYS */; INSERT INTO `route` (`routeid`, `routename`) VALUES (1, 'Pelenda'); /*!40000 ALTER TABLE `route` ENABLE KEYS */; -- Dumping structure for table teafactory.supplier CREATE TABLE IF NOT EXISTS `supplier` ( `supplierno` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL, `route` int(11) DEFAULT NULL, `phone` varchar(10) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, PRIMARY KEY (`supplierno`), KEY `FK_supplier_route` (`route`), CONSTRAINT `FK_supplier_route` FOREIGN KEY (`route`) REFERENCES `route` (`routeid`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.supplier: ~1 rows (approximately) /*!40000 ALTER TABLE `supplier` DISABLE KEYS */; INSERT INTO `supplier` (`supplierno`, `name`, `route`, `phone`, `address`) VALUES (3, 'Sangakkara Palihawadana', 1, '1484511', 'Ampara'); /*!40000 ALTER TABLE `supplier` ENABLE KEYS */; -- Dumping structure for table teafactory.supplier_bank CREATE TABLE IF NOT EXISTS `supplier_bank` ( `branchid` int(11) NOT NULL, `supplierid` int(11) NOT NULL, `acc_no` varchar(75) NOT NULL, PRIMARY KEY (`branchid`,`supplierid`), KEY `FK_supplier_bankdetails_supplier` (`supplierid`), CONSTRAINT `FK_supplier_bankdetails_branch` FOREIGN KEY (`branchid`) REFERENCES `branch` (`branchid`), CONSTRAINT `FK_supplier_bankdetails_supplier` FOREIGN KEY (`supplierid`) REFERENCES `supplier` (`supplierno`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.supplier_bank: ~0 rows (approximately) /*!40000 ALTER TABLE `supplier_bank` DISABLE KEYS */; /*!40000 ALTER TABLE `supplier_bank` ENABLE KEYS */; -- Dumping structure for table teafactory.user CREATE TABLE IF NOT EXISTS `user` ( `username` varchar(50) NOT NULL, `password` varchar(50) DEFAULT NULL, `acc_type` varchar(5) DEFAULT NULL, PRIMARY KEY (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table teafactory.user: ~1 rows (approximately) /*!40000 ALTER TABLE `user` DISABLE KEYS */; INSERT INTO `user` (`username`, `password`, `acc_type`) VALUES ('admin', '<PASSWORD>', '<PASSWORD>'); /*!40000 ALTER TABLE `user` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom.impl; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import lk.beempz.tf.business.custom.DebitBO; import lk.beempz.tf.business.custom.MonthlyRateBO; import lk.beempz.tf.business.custom.PurchaseBO; import lk.beempz.tf.business.custom.SupplierBO; import lk.beempz.tf.dao.custom.PurchaseDAO; import lk.beempz.tf.db.DBConnection; import lk.beempz.tf.dto.DebitDTO; import lk.beempz.tf.dto.MonthlyRateDTO; import lk.beempz.tf.dto.PurchaseDTO; import lk.beempz.tf.dto.UnprocessedDebitDTO; import lk.beempz.tf.entity.Purchase; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class PurchaseBOImpl implements PurchaseBO { @Autowired PurchaseDAO purchaseDAO; @Autowired SupplierBO supplierBO; @Autowired DebitBO debitBO; @Autowired MonthlyRateBO monthlyRateBO; public PurchaseBOImpl() { } @Override public boolean addPurchase(PurchaseDTO purchaseDTO) throws Exception { try { DBConnection.getInstance().getConnection().setAutoCommit(false); MonthlyRateDTO rates = monthlyRateBO.getRates(new UnprocessedDebitDTO(purchaseDTO.getDate(), purchaseDTO.getSupplierid(), null, purchaseDTO.getaKg(), purchaseDTO.getbKg())); BigDecimal payforA = rates.getaGrade().multiply(purchaseDTO.getaKg()); BigDecimal payforB = rates.getbGrade().multiply(purchaseDTO.getbKg()); BigDecimal totalSize = purchaseDTO.getaKg().add(purchaseDTO.getbKg()); BigDecimal payforTravel = rates.getTravelling().multiply(totalSize); BigDecimal totalAmount = payforA.add(payforB.subtract(payforTravel)); Purchase purchase = purchaseDAO.saveAndGetGenerated(new Purchase(-1, purchaseDTO.getDate(), purchaseDTO.getSupplierid(), purchaseDTO.getaKg(), purchaseDTO.getbKg())); if (purchase == null) { return false; } boolean result = debitBO.insertDebit(new DebitDTO(-1, purchaseDTO.getDate(), purchase.getPurchase_id(), purchaseDTO.getSupplierid(), purchaseDTO.getSuppliername(), totalAmount)); if (result) { DBConnection.getInstance().getConnection().commit(); return true; } else { DBConnection.getInstance().getConnection().rollback(); return false; } } catch (Exception e) { DBConnection.getInstance().getConnection().rollback(); throw e; } finally { DBConnection.getInstance().getConnection().setAutoCommit(true); } } @Override public boolean deletePurchase(int pid, Date date) throws Exception { try { DBConnection.getInstance().getConnection().setAutoCommit(false); Purchase result = purchaseDAO.findById(pid); Calendar c1 = Calendar.getInstance(); c1.setTime(result.getPurchase_date()); Calendar c2 = Calendar.getInstance(); c2.setTime(new Date()); long diff = (c2.getTimeInMillis() - c1.getTimeInMillis()) / (60000 * 60 * 24); if (diff > 1) { return false; } boolean res = debitBO.deleteByPurchase(pid); if(!res){ DBConnection.getInstance().getConnection().rollback(); return false; } res = purchaseDAO.delete(pid); if(!res){ DBConnection.getInstance().getConnection().rollback(); return false; } DBConnection.getInstance().getConnection().commit(); return true; } catch (Exception e) { DBConnection.getInstance().getConnection().rollback(); throw e; } finally{ DBConnection.getInstance().getConnection().setAutoCommit(true); } } @Override public ArrayList<PurchaseDTO> getAll() throws Exception { ArrayList<PurchaseDTO> purchaseDTOs = new ArrayList<>(); ArrayList<Purchase> all = purchaseDAO.getAll(); for (Purchase purchase : all) { purchaseDTOs.add(new PurchaseDTO(purchase.getPurchase_id(), purchase.getPurchase_date(), purchase.getSupplierid(), supplierBO.findSupplier(purchase.getSupplierid()).getName(), purchase.getAkg(), purchase.getBkg())); } return purchaseDTOs; } @Override public ArrayList<PurchaseDTO> getAllByMonth(Date date) throws Exception { ArrayList<PurchaseDTO> purchaseDTOs = new ArrayList<>(); ArrayList<Purchase> purchases = purchaseDAO.getAllByMonth(date); for (Purchase purchase : purchases) { purchaseDTOs.add(new PurchaseDTO(purchase.getPurchase_id(), purchase.getPurchase_date(), purchase.getSupplierid(), supplierBO.findSupplier(purchase.getSupplierid()).getName(), purchase.getAkg(), purchase.getBkg())); } return purchaseDTOs; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom; import java.util.ArrayList; import lk.beempz.tf.business.SuperBO; import lk.beempz.tf.dto.RouteDTO; /** * * @author badhr */ public interface RouteBO extends SuperBO{ public RouteDTO findRoute(int routeid)throws Exception; public ArrayList<RouteDTO> getRoutes() throws Exception; public RouteDTO getRouteByName(String name)throws Exception; public boolean saveRoute(RouteDTO routeDTO)throws Exception; public boolean updateRoute(RouteDTO routeDTO)throws Exception; public boolean deleteRoute(int routeid)throws Exception; } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dto; import java.math.BigDecimal; import java.util.Date; /** * * @author badhr */ public class UnprocessedDebitDTO { private Date date; private int supplierid; private String description; private BigDecimal aGrd; private BigDecimal bGrd; public UnprocessedDebitDTO() { } public UnprocessedDebitDTO(Date date, int supplierid, String description, BigDecimal aGrd, BigDecimal bGrd) { this.date = date; this.supplierid = supplierid; this.description = description; this.aGrd = aGrd; this.bGrd = bGrd; } /** * @return the date */ public Date getDate() { return date; } /** * @param date the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the supplierid */ public int getSupplierid() { return supplierid; } /** * @param supplierid the supplierid to set */ public void setSupplierid(int supplierid) { this.supplierid = supplierid; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the aGrd */ public BigDecimal getaGrd() { return aGrd; } /** * @param aGrd the aGrd to set */ public void setaGrd(BigDecimal aGrd) { this.aGrd = aGrd; } /** * @return the bGrd */ public BigDecimal getbGrd() { return bGrd; } /** * @param bGrd the bGrd to set */ public void setbGrd(BigDecimal bGrd) { this.bGrd = bGrd; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom; import lk.beempz.tf.business.SuperBO; import lk.beempz.tf.dto.Supplier_BankDTO; /** * * @author beempz */ public interface Supplier_BankBO extends SuperBO{ public boolean addSuplierBank(Supplier_BankDTO supplier_BankDTO); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.dao.custom.impl; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import lk.beempz.tf.dao.CrudUtil; import lk.beempz.tf.dao.custom.DebitDAO; import lk.beempz.tf.entity.Debit; import org.springframework.stereotype.Component; @Component public class DebitDAOImpl implements DebitDAO { @Override public boolean save(Debit entity) throws Exception { return CrudUtil.executeUpdate("insert into debit values(?,?,?,?,?)", entity.getDebitid(), entity.getPurchaseid(), entity.getDebitdate(), entity.getSupplierid(), entity.getAmount()); } @Override public boolean delete(Integer id) throws Exception { return CrudUtil.executeUpdate("delete from debit where debitid = ?", id); } @Override public boolean update(Debit entity) throws Exception { return CrudUtil.executeUpdate("update debit set detail = ? , purchaseid = ? , supplierid = ? , amount = ? where debitid = ?", entity.getPurchaseid(), entity.getDebitdate(), entity.getSupplierid(), entity.getAmount(), entity.getDebitid()); } @Override public ArrayList<Debit> getAll() throws Exception { ArrayList<Debit> debits = new ArrayList<>(); ResultSet rs = CrudUtil.executeQuery("select * from debit"); while (rs.next()) { debits.add(new Debit(rs.getInt(1), rs.getInt(2), rs.getDate(3), rs.getInt(4), rs.getBigDecimal(5))); } return debits; } @Override public Debit findById(Integer id) throws Exception { ResultSet rs = CrudUtil.executeQuery("select * from debit where debitid = ?", id); if (rs.next()) { return new Debit(rs.getInt(1), rs.getInt(2), rs.getDate(3), rs.getInt(4), rs.getBigDecimal(5)); } return null; } @Override public Debit saveAndGetGenerated(Debit entity) throws Exception { ResultSet rs = CrudUtil.executeUpdateWithGeneratedKeys("insert into debit(purchaseid,debitdate,supplierid,amount) values(?,?,?,?)", entity.getPurchaseid(), entity.getDebitdate(), entity.getSupplierid(), entity.getAmount()); if (rs.next()) { return new Debit(rs.getInt(1), entity.getPurchaseid(), entity.getDebitdate(), entity.getSupplierid(), entity.getAmount()); } return null; } @Override public ArrayList<Debit> getSortAndFiltered(Date from, Date to) throws Exception { ArrayList<Debit> debits = new ArrayList<>(); String query = "select * from debit where debitdate between ? and ? "; ResultSet rs = CrudUtil.executeQuery(query, from, to); while (rs.next()) { debits.add(new Debit(rs.getInt(1), rs.getInt(2), rs.getDate(3), rs.getInt(4), rs.getBigDecimal(5))); } return debits; } @Override public boolean deleteByPurchaseid(int purchaseid) throws Exception { return CrudUtil.executeUpdate("delete from debit where purchaseid = ?", purchaseid); } @Override public Debit selectByPurchaseID(int purchaseid) throws Exception { ResultSet rs = CrudUtil.executeQuery("select * from debit where purchaseid = ?", purchaseid); if (rs.next()) { return new Debit(rs.getInt(1), rs.getInt(2), rs.getDate(3), rs.getInt(4), rs.getBigDecimal(5)); } return null; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom.impl; import java.util.ArrayList; import lk.beempz.tf.business.custom.RouteBO; import lk.beempz.tf.dao.custom.RouteDAO; import lk.beempz.tf.dto.RouteDTO; import lk.beempz.tf.entity.Route; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class RouteBOImpl implements RouteBO { @Autowired RouteDAO routeDAO; public RouteBOImpl(){} @Override public RouteDTO findRoute(int routeid)throws Exception{ Route routeResult = routeDAO.findById(routeid); if(routeResult == null){ return null; } return new RouteDTO(routeResult.getRouteid(), routeResult.getRoutename()); } @Override public ArrayList<RouteDTO> getRoutes() throws Exception { ArrayList<RouteDTO> routeDTOs = new ArrayList<>(); ArrayList<Route> routes = routeDAO.getAll(); for (Route route : routes) { routeDTOs.add(new RouteDTO(route.getRouteid(), route.getRoutename())); } return routeDTOs; } @Override public RouteDTO getRouteByName(String name) throws Exception { Route routeID = routeDAO.getRouteID(name); return new RouteDTO(routeID.getRouteid(), name); } @Override public boolean saveRoute(RouteDTO routeDTO) throws Exception { return routeDAO.saveAndGetGenerated(new Route(routeDTO.getRouteid(), routeDTO.getRoute())) != null; } @Override public boolean updateRoute(RouteDTO routeDTO) throws Exception { return routeDAO.update(new Route(routeDTO.getRouteid(), routeDTO.getRoute())); } @Override public boolean deleteRoute(int routeid) throws Exception { return routeDAO.delete(routeid); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom.impl; import java.util.ArrayList; import lk.beempz.tf.business.custom.RouteBO; import lk.beempz.tf.business.custom.SupplierBO; import lk.beempz.tf.dao.custom.SupplierDAO; import lk.beempz.tf.dto.RouteDTO; import lk.beempz.tf.dto.SupplierDTO; import lk.beempz.tf.entity.Supplier; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class SupplierBOImpl implements SupplierBO { @Autowired SupplierDAO supplierDAO; @Autowired RouteBO routeBO; public SupplierBOImpl() { } @Override public ArrayList<SupplierDTO> getSuppliers() throws Exception { ArrayList<Supplier> suppliers = supplierDAO.getAll(); ArrayList<SupplierDTO> supplierDTOs = new ArrayList<>(); for (Supplier supplier : suppliers) { RouteDTO route = routeBO.findRoute(supplier.getRoute()); supplierDTOs.add(new SupplierDTO(supplier.getSupplierno(), supplier.getName(), supplier.getRoute(), route.getRoute(), supplier.getPhone(), supplier.getAddress())); } return supplierDTOs; } @Override public SupplierDTO findSupplier(int Id) throws Exception { Supplier supplier = supplierDAO.findById(Id); return new SupplierDTO(supplier.getSupplierno(), supplier.getName(), supplier.getRoute(), routeBO.findRoute(supplier.getRoute()).getRoute(), supplier.getPhone(), supplier.getAddress()); } @Override public boolean addNewSupplier(SupplierDTO supplier) throws Exception { if(supplier.getRouteid() == -1){ supplier.setRouteid(routeBO.getRouteByName(supplier.getRoute()).getRouteid()); } if(supplier.getSupplierid() == -1){ Supplier id = supplierDAO.saveAndGetGenerated(new Supplier(-1, supplier.getName(), supplier.getRouteid(), supplier.getContact(), supplier.getAddress())); if(id == null) return false; return true; } return supplierDAO.save(new Supplier(supplier.getSupplierid(), supplier.getName(), supplier.getRouteid(), supplier.getContact(), supplier.getAddress())); } @Override public boolean updateSupplier(SupplierDTO supplier) throws Exception { if(supplier.getRouteid() == -1){ supplier.setRouteid(routeBO.getRouteByName(supplier.getRoute()).getRouteid()); } return supplierDAO.update(new Supplier(supplier.getSupplierid(), supplier.getName(), supplier.getRouteid(), supplier.getContact(), supplier.getAddress())); } @Override public boolean deleteSupplier(int id)throws Exception{ return supplierDAO.delete(id); } @Override public int addAndReturnGenerated(SupplierDTO supplier) throws Exception{ if(supplier.getRouteid() == -1){ supplier.setRouteid(routeBO.getRouteByName(supplier.getRoute()).getRouteid()); } if(supplier.getSupplierid() == -1){ Supplier id = supplierDAO.saveAndGetGenerated(new Supplier(-1, supplier.getName(), supplier.getRouteid(), supplier.getContact(), supplier.getAddress())); if(id == null) return -1; return id.getSupplierno(); } return -1; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.entity; import java.math.BigDecimal; import java.util.Date; /** * * @author badhr */ public class Credit { private int creditid; private int supplierid; private int credit_type; private Date date; private BigDecimal amount; public Credit() { } public Credit(int creditid, int supplierid, int credit_type, Date date, BigDecimal amount) { this.creditid = creditid; this.supplierid = supplierid; this.credit_type = credit_type; this.date = date; this.amount = amount; } /** * @return the creditid */ public int getCreditid() { return creditid; } /** * @param creditid the creditid to set */ public void setCreditid(int creditid) { this.creditid = creditid; } /** * @return the supplierid */ public int getSupplierid() { return supplierid; } /** * @param supplierid the supplierid to set */ public void setSupplierid(int supplierid) { this.supplierid = supplierid; } /** * @return the credit_type */ public int getCredit_type() { return credit_type; } /** * @param credit_type the credit_type to set */ public void setCredit_type(int credit_type) { this.credit_type = credit_type; } /** * @return the date */ public Date getDate() { return date; } /** * @param date the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the amount */ public BigDecimal getAmount() { return amount; } /** * @param amount the amount to set */ public void setAmount(BigDecimal amount) { this.amount = amount; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.beempz.tf.business.custom.impl; import java.util.ArrayList; import lk.beempz.tf.business.custom.CreditTypeBO; import lk.beempz.tf.dao.custom.Credit_TypeDAO; import lk.beempz.tf.dto.CreditTypeDTO; import lk.beempz.tf.entity.Credit_Type; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CreditTypeBOImpl implements CreditTypeBO { @Autowired Credit_TypeDAO credit_TypeDAO; public CreditTypeBOImpl() { } @Override public CreditTypeDTO getCreditType(int id)throws Exception { Credit_Type ctype = credit_TypeDAO.findById(id); if(ctype == null) return null; return new CreditTypeDTO(ctype.getTypeid(), ctype.getType_name()); } @Override public ArrayList<CreditTypeDTO> getCredits() throws Exception { ArrayList<CreditTypeDTO> creditTypeDTOs = new ArrayList<>(); ArrayList<Credit_Type> all = credit_TypeDAO.getAll(); for (Credit_Type credit_Type : all) { creditTypeDTOs.add(new CreditTypeDTO(credit_Type.getTypeid(), credit_Type.getType_name())); } return creditTypeDTOs; } @Override public int getIdByName(String type_Name) throws Exception { return credit_TypeDAO.getCreditTypeid(type_Name); } }
cbef6b242612474eb52398788709ae95dee27dfb
[ "Java", "SQL" ]
36
Java
Badhrajith-Pathirana/fx-teafactory-spring
a914a8cb721f9be781e46b1c670a2f88e56236a9
cdacf08d0d5086f66bedb019b73f13d7f1a4be59
refs/heads/master
<repo_name>kamchy/covidstat<file_sep>/covidstat/src/main/java/com/kamilachyla/gui/CovidView.java package com.kamilachyla.gui; import com.kamilachyla.model.Country; import com.kamilachyla.viewmodel.CovidViewModel; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.util.Callback; import javafx.util.StringConverter; import javafx.util.converter.NumberStringConverter; import java.time.LocalDate; public class CovidView extends VBox { private final GridPane gp = new GridPane(); private final CovidViewModel viewModel; private final ListView<Country> listView = new ListView<>(); private final Label laConfirmed = new Label(); private final Label laDeaths = new Label(); private final Label laActive = new Label(); private final Label laRecovered = new Label(); private final Label laDate = new Label(); private ChartView chartView; public CovidView(CovidViewModel viewModel) { this.viewModel = viewModel; createView(); bindViewModel(); Platform.runLater(() -> { listView.getSelectionModel().selectFirst(); }); } private void bindViewModel() { listView.setEditable(false); listView.itemsProperty().bind(viewModel.countriesProperty()); listView.setCellFactory(new CountryCellFactory()); listView.getSelectionModel().selectedItemProperty().addListener((o, ov, nv)-> { viewModel.update(nv); }); laConfirmed.textProperty().bindBidirectional(viewModel.confirmedProperty(), new NumberStringConverter()); laDeaths.textProperty().bindBidirectional(viewModel.deathsProperty(), new NumberStringConverter()); laActive.textProperty().bindBidirectional(viewModel.activeProperty(), new NumberStringConverter()); laRecovered.textProperty().bindBidirectional(viewModel.recoveredProperty(), new NumberStringConverter()); laDate.textProperty().bindBidirectional(viewModel.getDateProperty(), new LocalDateConverter()); } private void createView() { var gpwrap = new VBox(); chartView = new ChartView(viewModel.selectedCountryCasesProperty()); gpwrap.setAlignment(Pos.CENTER); gp.setPadding(new Insets(20)); gp.setVgap(4); gp.setHgap(10); gp.add(listView, 0, 0, 1, 6); addRow(1,0, "Confirmed", laConfirmed); addRow(1, 1, "Deaths", laDeaths); addRow(1, 2, "Active", laActive); addRow(1,3, "Recovered", laRecovered); addRow(1,4, "Date", laDate); gp.add(chartView, 1, 5, 3, 1); final ColumnConstraints col = new ColumnConstraints(); col.setPercentWidth(30); final ColumnConstraints chartCol = new ColumnConstraints(); col.setHgrow(Priority.NEVER); chartCol.setHgrow(Priority.ALWAYS); gp.getColumnConstraints().addAll( col, col, col, chartCol); gpwrap.getChildren().add( gp ); VBox.setVgrow(gpwrap, Priority.ALWAYS ); this.getChildren().add(gpwrap); } private void addRow(int col, int row, String label, Label display) { gp.add(new Label(label), 0 + col, row); gp.add(display, 1 + col, row); } private static class CountryCellFactory implements Callback<ListView<Country>, ListCell<Country>>{ @Override public ListCell<Country> call(ListView<Country> list) { return new ListCell<>() { @Override protected void updateItem(Country country, boolean b) { super.updateItem(country, b); if (country != null) { setText(String.format("%s [%s]", country.name(), country.iso2())); } } }; } } private static class LocalDateConverter extends StringConverter<LocalDate> { @Override public String toString(LocalDate localDate) { return localDate == null ? "UNKNOWN" : localDate.toString(); } @Override public LocalDate fromString(String s) { return LocalDate.parse(s); } } } <file_sep>/covidstat/src/main/java/com/kamilachyla/deserialize/CaseDeserializer.java package com.kamilachyla.deserialize; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.kamilachyla.model.Case; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class CaseDeserializer extends StdDeserializer<Case> { public CaseDeserializer() { this(null); } public CaseDeserializer(Class<?> vc) { super(vc); } @Override public Case deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); int confirmed = node.get("Confirmed").intValue(); int deaths = node.get("Deaths").intValue(); int recovered = node.get("Recovered").intValue(); int active = node.get("Active").intValue(); String dateStr = node.get("Date").asText(); LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_DATE_TIME); return new Case(date, confirmed, deaths, recovered, active); } }<file_sep>/README.md # Application This sample application is an accompying resource for mini-series of javafx tutorials available at: * [Prosta aplikacja w javafx -statystyki covid - tutorial](https://kamilachyla.com/posts/prosta-aplikacja-w-javafx-statystyki-covid-tutorial/) * [Posta aplikacja w javafx (2) - czytamy dane z pliku](https://kamilachyla.com/posts/prosta-aplikacja-w-javafx-2-czytamy-dane-z-pliku/) * [Prosta aplikacja w javafx (3) - sięgamy po dane przy użyciu klasy httpclient](https://kamilachyla.com/posts/prosta-aplikacja-w-javafx-3-siegamy-po-dane-przy-uzyciu-klasy-httpclient/) Its aim is to display some covid-related data in javafx desktop application. # API usage ## GET countries curl --location --request GET 'https://api.covid19api.com/countries' ## GET country stats curl https://api.covid19api.com/total/country/poland # Screenshot ![Application window with covid stats charts](covid-app-window-all-countries.png) <file_sep>/covidstat/src/main/java/com/kamilachyla/model/CasesPerCountryModel.java package com.kamilachyla.model; import java.util.*; public class CasesPerCountryModel { private final Map<Country, List<Case>> countryCasesMap = new HashMap<>(); private final List<Country> countries = new ArrayList<>(); public List<Case> getCases(Country country) { return countryCasesMap.getOrDefault(country, Collections.emptyList()); } public void addCases(Country country, List<Case> cases) { countryCasesMap.put(country, cases); } public void setCountries(List<Country> countries) { this.countries.clear(); this.countries.addAll(countries); } public List<Country> getCountries() { return List.copyOf(countries); } } <file_sep>/covidstat/src/main/java/com/kamilachyla/service/HandmadeService.java package com.kamilachyla.service; import com.kamilachyla.model.Case; import com.kamilachyla.model.Country; import java.util.stream.Stream; import java.time.LocalDate; public final class HandmadeService implements CovidService { public Stream<Country> getCountries(){ return Stream.of( new Country("Poland", "poland", "PL"), new Country("Germany", "germany", "DE") ); } public Stream<Case> getCases(Country data) { if (data.name().equals("Poland")) { return Stream.of( new Case(LocalDate.parse("2021-04-07"), 1, 2, 3, 4), new Case(LocalDate.parse("2021-04-08"), 10, 20, 30, 40), new Case(LocalDate.parse("2021-04-09"), 20, 3, 35, 24) ); } else { return Stream.of( new Case(LocalDate.parse("2021-04-07"), 100, 200, 300, 400), new Case(LocalDate.parse("2021-04-08"), 130, 120, 230, 445), new Case(LocalDate.parse("2021-04-09"), 230, 259, 220, 500) ); } } } <file_sep>/covidstat/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.kamilachyla</groupId> <artifactId>covidstat</artifactId> <version>1.0.0</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>15</maven.compiler.source> <maven.compiler.target>15</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-controls</artifactId> <version>17-ea+6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <release>15</release> <compilerArgs><arg>--enable-preview</arg></compilerArgs> </configuration> </plugin> <plugin> <groupId>org.openjfx</groupId> <artifactId>javafx-maven-plugin</artifactId> <version>0.0.5</version> <configuration> <mainClass>covidstat/com.kamilachyla.App</mainClass> <commandlineArgs>--enable-preview</commandlineArgs> </configuration> </plugin> </plugins> </build> </project>
25db47595de4c5be3522e3c11e11222e1a9cd781
[ "Markdown", "Java", "Maven POM" ]
6
Java
kamchy/covidstat
1c9f001e94461a234f63f17cc98a981055142a31
48796668c5bba4dfef259e496ffb254076b56405
refs/heads/master
<file_sep>[pytest] log_file = log.txt<file_sep>import re import pytest def log(file_name: str, text: str): with open(file_name, 'a', encoding='utf-8') as file: try: file.write(text + '\n') finally: file.close() def check_to_valid_email(email: str) -> bool: return bool(re.search(r'^[\w\.\+\-]+\@[ \w]+\.[a-z]{2,3}$', email['email'])) @pytest.mark.parametrize("data", [ {'email': '<EMAIL>', "expected": True}, {'email': '<EMAIL>', 'expected': True}, {'email': '<EMAIL>', 'expected': True} ]) def test_valid_email(data: dict, file_path: str): temp = check_to_valid_email(data) if temp is True: log(file_path, f'Результат {temp}: почта {data["email"]} валидная') assert temp == data['expected'] @pytest.mark.parametrize("data", [ {'email': 'test@test.', 'expected': False}, {'email': 'w@', 'expected': False}, {'email': '@tt', 'expected': False} ]) def test_invalid_email(data: dict, file_path: str): temp = check_to_valid_email(data) if temp is False: log(file_path, f'Результат {temp}: почта {data["email"]} невалидная') assert temp == data['expected'] <file_sep>import pytest @pytest.fixture() def file_path(request): file_name = request.config.getini("log_file") return file_name def pytest_addoption(parser): parser.addini('log_file', help='file', default='log.txt')
ff40af0ab44875dee2a8538af44a8957fa587ef7
[ "Python", "INI" ]
3
INI
rinAkhm/param_test
2472f90bf0336049218d3da6f3efde2dd90a5581
75d6099d2611f1a21dac97d4577662d24fcf1e8a
refs/heads/master
<file_sep>#!/usr/bin/python import sys from datetime import datetime #-----------------------------------------------------------# # The reducer reads through all the records in the input. # # The input is of the format author_id\tadded_at_hour. # # # # It counts the number of lines in the input that have the # # same author_id and added_at_hour; remembers the hour for # # for which highest activity is found so far and outputs # # the highest activity hour for an author. # # # # It also considers the possibility of an author having the # # same highest activity in more than one hours by recording # # then in an array. # #-----------------------------------------------------------# lastId = None lastHour = None activityCount = 1 activityCountMax = 1 highestActivityHours = [] #This function helps with the recording of highest activity. #It optionally prints the results depending on the input flag. def calcMax(printResult): global lastId global lastHour global activityCount global activityCountMax if activityCount > activityCountMax: activityCountMax = activityCount highestActivityHours[:] = [] highestActivityHours.append(lastHour) elif activityCount == activityCountMax: highestActivityHours.append(lastHour) if printResult == 1: print lastId, "\t", ', '.join(highestActivityHours) return for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 2: continue #Something has gone wrong. Skip this line. thisId, thisHour = data_mapped if lastId and lastId == thisId and lastHour and lastHour == thisHour: #same author same hour activityCount += 1 if lastId and lastId == thisId and lastHour and lastHour != thisHour: #Same author different hour, calcMax(0) #record activity counts and reset the counter activityCount = 1 if lastId and lastId != thisId: #Different author, calcMax(1) #record activity counts and print the highest activity hours activityCount = 1 activityCountMax = 1 highestActivityHours[:] = [] lastId = thisId lastHour = thisHour if lastId != None: #calculate and print result for last author_id in the input calcMax(1) <file_sep>udacity_training ================ Repository for code written for the Hadoop training by Udacity <file_sep>#!/usr/bin/python import sys import csv import operator #-----------------------------------------------------------# # The mapper reads through all the records in the input, # # skips the first record (which happens to be the header) # # # # tagnames is the 3rd field in a record. # # The mapper separates all the tags in tagnames and # # outputs topN tags. # #-----------------------------------------------------------# n = 10 tagOccurence = {} reader = csv.reader(sys.stdin, delimiter='\t') headerSkipped = False for line in reader: if len(line) != 19: continue if not headerSkipped: headerSkipped = True continue for i in line[2].split(" "): if i != '': if i not in tagOccurence: tagOccurence[i] = 1 else: tagOccurence[i] = tagOccurence[i]+1 tagOccurence1 = [(v, k) for k, v in tagOccurence.items()] tagOccurence1 = sorted(tagOccurence1, reverse=True, key=lambda x: int(x[0]))[:n] for i in tagOccurence1: print "{0}\t{1}".format(i[1], i[0]) <file_sep>#!/usr/bin/python import sys import csv from datetime import datetime #-----------------------------------------------------------# # The mapper reads through all the records in the input, # # skips the first record (which happens to be the header) # # and outputs author_id and hour part of the added_at date. # # # # author_id is the 4th field in a record. # # added_at is the 9th field in a record. # #-----------------------------------------------------------# reader = csv.reader(sys.stdin, delimiter='\t') writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL) headerSkipped = False for line in reader: #skip the first (Header) line if not headerSkipped: headerSkipped = True continue author_id = line[3].strip('"') added_at_hour = datetime.strptime(line[8].strip('"').split('.')[0], '%Y-%m-%d %H:%M:%S').hour print "{0}\t{1}".format(author_id, added_at_hour) <file_sep>#!/usr/bin/python import sys import csv #-----------------------------------------------------------# # The mapper reads through all the records in the input, # # skips the first record (which happens to be the header) # # For nodes of type "question" it outputs # # node_id\tA\tbody_length # # # # For nodes of type "answer" it outputs # # abs_parent_id\tB\tbody_length # # # # The A or B written to the output help sort the record # # before they are consumed by the reducer. # # They make sure that question comes first followed by all # # the answers. # # # # node_id is the 1st field in a record. # # node_type is the 6th field in a record. # # body is the 5th field in a record. # # abs_parent_id is the 8th field in a record. # #-----------------------------------------------------------# reader = csv.reader(sys.stdin, delimiter='\t') headerSkipped = False for line in reader: if len(line) != 19: continue if not headerSkipped: headerSkipped = True continue node_id = line[0].strip('"') node_type = line[5].strip('"') body = line[4].strip('"') abs_parent_id = line[7].strip('"') if node_type == "question": print "{0}\t{1}\t{2}".format(node_id, "A", len(body)) if node_type == "answer": print "{0}\t{1}\t{2}".format(abs_parent_id, "B", len(body)) <file_sep>#!/usr/bin/python import sys import csv #-----------------------------------------------------------# # The mapper reads through all the records in the input, # # skips the first record (which happens to be the header) # # For nodes of type "question" it outputs # # node_id\tauthor_id # # # # For nodes of type "answer" or "comment" it outputs # # abs_parent_id\tauthor_id # # # # node_id is the 1st field in a record. # # node_type is the 6th field in a record. # # author_id is the 4th field in a record. # # abs_parent_id is the 8th field in a record. # #-----------------------------------------------------------# reader = csv.reader(sys.stdin, delimiter='\t') headerSkipped = False for line in reader: if len(line) != 19: continue if not headerSkipped: headerSkipped = True continue node_id = line[0].strip('"') node_type = line[5].strip('"') author_id = line[3].strip('"') abs_parent_id = line[7].strip('"') if node_type == "question": print "{0}\t{1}".format(node_id, author_id) else: print "{0}\t{1}".format(abs_parent_id, author_id) <file_sep>#!/usr/bin/python import sys import operator #-----------------------------------------------------------# # The reducer reads through all the records in the input. # # These are the individual topN lists generated by mappers. # # # # The reducer builds the global topN list by combining the # # individual lists. # #-----------------------------------------------------------# n = 10 tagOccurence = {} for line in sys.stdin: data_mapped = line.strip().split("\t") thisTag, Occ = data_mapped print thisTag, if thisTag not in tagOccurence: print "is not in dict", print "initializing to ", print int(Occ) tagOccurence[thisTag] = int(Occ) else: print "is in dict", print "is currently set to ", print int(tagOccurence[thisTag]), print "adding", print int(Occ), tagOccurence[thisTag] = int(tagOccurence[thisTag])+int(Occ) print "final value is", print int(tagOccurence[thisTag]) tagOccurence1 = [(v, k) for k, v in tagOccurence.items()] tagOccurence1 = sorted(tagOccurence1, reverse=True, key=lambda x: int(x[0]))[:n] for i in tagOccurence1: print "{0}\t{1}".format(i[1], i[0]) <file_sep>#!/usr/bin/python import sys #-----------------------------------------------------------# # The reducer reads through all the records in the input. # # The input is of the format node_id\tType\tbody_length # # # # If the record type is A, its a question; store its length # # If the record type is B, its an answer; store its length # # in an array so that the array could later be used for # # calculating average. # # # # The output is of the format # # node_id\tquestion_length\taverage_answer_length # #-----------------------------------------------------------# lastId = None lastQuestLength = 0 answerLengths = [] avgAnsLength = 0 #This function helps with avarage length calculations def calcAvg(): global lastId global lastQuestLength global answerLengths global avgAnsLength if len(answerLengths) == 0: avgAnsLength = 0 else: avgAnsLength = sum(answerLengths)/float(len(answerLengths)) print lastId, "\t", lastQuestLength, "\t", avgAnsLength answerLengths[:] = [] return for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 3: continue #Something has gone wrong. Skip this line. thisId, thisType, thisLength = data_mapped if lastId and lastId != thisId: calcAvg() lastId = thisId if thisType == 'A': lastQuestLength = thisLength else: answerLengths.append(float(thisLength)) if lastId != None: #calculate and print result for last post calcAvg() <file_sep>#!/usr/bin/python import sys #-----------------------------------------------------------# # The reducer reads through all the records in the input. # # The input is of the format node_id\tauthor_id # # # # The output is of the format # # node_id\t<comma separeted list of author_ids> # #-----------------------------------------------------------# lastId = None for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 2: continue #Something has gone wrong. Skip this line. thisId, thisAuthor = data_mapped if lastId == None: print thisId + "\t", print thisAuthor, elif lastId and lastId != thisId: print " " print thisId + "\t", print thisAuthor, else: print ", " + thisAuthor, lastId = thisId lastAuthor = thisAuthor print ", " + thisAuthor,
f1765a721ea9f3cc36e9b6ea68399a18a29ec358
[ "Markdown", "Python" ]
9
Python
kedruwsky/udacity_training
e633e72936ef83582e3f72c41f73c16d984ced44
dd02843c00964e4af0d8bfc4fd0bc89d3875c9a2
refs/heads/master
<file_sep>import java.util.Random; public class Quicksort { public static void main(String[] args) { Random random = new Random(); int n = 10; int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = random.nextInt(20); System.out.println(arr[i]); } quickSortDriver(arr); System.out.println("============================================================================="); for(int i = 0; i < n; i++){ System.out.println(arr[i]); } } public static void quickSortDriver(int[] arr) { quickSort(arr,arr.length - 1, 0); } private static void quickSort(int[] unsorted, int right, int left) { int i = left; int j = right; swapElements(unsorted, left, right); int pivot = unsorted[right]; j--; //Move the right pointer so the pivot is ignored while(j >= i) { while(i+1 < unsorted.length && unsorted[++i] < pivot); while(j-1 > -1 && unsorted[--j] > pivot); if( i <= j) swapElements(unsorted, i, j); } swapElements(unsorted, i, right); if(left != 0){ if(left != i - 1 && i - 1 > -1){ quickSort(unsorted, i -1, left); } } if(right != unsorted.length - 1){ if(right != i + 1 && i + 1 < unsorted.length){ quickSort(unsorted, right, i + 1); } } } private static void swapElements(int[] arr, int idx1, int idx2) { int temp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = temp; } }
36f3e115b602b72aee9ec67e1f79c368b6b07590
[ "Java" ]
1
Java
codes4coffee/javaQuicksort
cfff5000861dcfd39b7c86e0c4e2baef4a72ce73
af5f52c00b390a562d3686c1539cecafe33593a6
refs/heads/master
<repo_name>CastilloLuis/SnakeGame<file_sep>/README.md # SnakeGame Control with SocketIO for a snake game ## Getting Started Simple control with socket io for a snake game. ## Technologies * NODE JS. * EXPRESS JS. * SOCKET IO * CANVAS ## Authors * **<NAME>** - [GitHub](https://github.com/CastilloLuis) ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details <file_sep>/server/client/snake/scripts/ws.js const socket = io('http://192.168.1.5:5000'); socket.on('up', data => { console.log(data); if (backtracking('dy')) { snake.dy = -grid; snake.dx = 0; } }); socket.on('down', data => { console.log(data); if (backtracking('dy')) { snake.dy = grid; snake.dx = 0; } }); socket.on('left', data => { console.log(data); if (backtracking('dx')) { snake.dx = -grid; snake.dy = 0; } }); socket.on('right', data => { console.log(data); if (backtracking('dx')) { snake.dx = grid; snake.dy = 0; } }); const backtracking = axis => snake[axis] === 0 ? true : false;<file_sep>/phone-client/SnakeControl/src/pages/home/home.ts import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { Socket } from 'ng-socket-io'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { constructor(public navCtrl: NavController, private socket: Socket) { this.socket.on('hello', emit => console.log(emit)) } socketIO = direction => { switch(direction) { case 38: console.log('up') this.socket.emit('up', 'up event'); break; case 40: console.log('down') this.socket.emit('down', 'down event'); break; case 39: console.log('right') this.socket.emit('right', 'right event'); break; case 37: console.log('left') this.socket.emit('left', 'left event'); break; default: 'default value'; } } }
8f506562db97aac1469bf9feb4262d10fdd09148
[ "Markdown", "TypeScript", "JavaScript" ]
3
Markdown
CastilloLuis/SnakeGame
e829d34e72eaadef5090f43ffc60c8aa4ed10471
c844177e5104f3f9e6f1df445c4004a7994b0d79
refs/heads/master
<repo_name>kesava/PLAI<file_sep>/rescript/src/ch5_interp_subst.bs.js // Generated by ReScript, PLEASE EDIT WITH CARE 'use strict'; function getFunDef(f, _fds) { while(true) { var fds = _fds; if (fds) { var a = fds.hd; if (f === a._0) { return a; } _fds = fds.tl; continue ; } throw { RE_EXN_ID: "Not_found", Error: new Error() }; }; } function fdCarg(fd) { return fd._1; } function fdCbody(fd) { return fd._2; } function subst(wat, forr, inn) { switch (inn.TAG | 0) { case /* NumC */0 : return inn; case /* IdC */1 : if (inn._0 === forr) { return wat; } else { return inn; } case /* AppC */2 : return { TAG: /* AppC */2, _0: inn._0, _1: subst(wat, forr, inn._1) }; case /* PlusC */3 : return { TAG: /* PlusC */3, _0: subst(wat, forr, inn._0), _1: subst(wat, forr, inn._1) }; case /* MultC */4 : return { TAG: /* MultC */4, _0: subst(wat, forr, inn._0), _1: subst(wat, forr, inn._1) }; case /* IfCondC */5 : return { TAG: /* IfCondC */5, _0: subst(wat, forr, inn._0), _1: subst(wat, forr, inn._1), _2: subst(wat, forr, inn._2) }; } } function interp(_exp, fds) { while(true) { var exp = _exp; switch (exp.TAG | 0) { case /* NumC */0 : return exp._0; case /* IdC */1 : throw { RE_EXN_ID: "Not_found", Error: new Error() }; case /* AppC */2 : var fd = getFunDef(exp._0, fds); _exp = subst(exp._1, fdCarg(fd), fdCbody(fd)); continue ; case /* PlusC */3 : return interp(exp._0, fds) + interp(exp._1, fds) | 0; case /* MultC */4 : return Math.imul(interp(exp._0, fds), interp(exp._1, fds)); case /* IfCondC */5 : if (interp(exp._0, fds) === 0) { _exp = exp._2; continue ; } _exp = exp._1; continue ; } }; } function desugar(ars) { switch (ars.TAG | 0) { case /* NumS */0 : return { TAG: /* NumC */0, _0: ars._0 }; case /* PlusS */1 : return { TAG: /* PlusC */3, _0: desugar(ars._0), _1: desugar(ars._1) }; case /* MultS */2 : return { TAG: /* MultC */4, _0: desugar(ars._0), _1: desugar(ars._1) }; case /* MinusS */3 : return { TAG: /* PlusC */3, _0: desugar(ars._0), _1: { TAG: /* MultC */4, _0: { TAG: /* NumC */0, _0: -1 }, _1: desugar(ars._1) } }; case /* SquareS */4 : var l = ars._0; return { TAG: /* PlusC */3, _0: desugar(l), _1: desugar(l) }; case /* IfCondS */5 : return { TAG: /* IfCondC */5, _0: desugar(ars._0), _1: desugar(ars._1), _2: desugar(ars._2) }; } } var fd1 = /* FdC */{ _0: "double", _1: "x", _2: { TAG: /* PlusC */3, _0: { TAG: /* IdC */1, _0: "x" }, _1: { TAG: /* NumC */0, _0: 5 } } }; var fd2 = /* FdC */{ _0: "quad", _1: "x", _2: { TAG: /* AppC */2, _0: "double", _1: { TAG: /* AppC */2, _0: "double", _1: { TAG: /* IdC */1, _0: "x" } } } }; var fd3 = /* FdC */{ _0: "const5", _1: "_", _2: { TAG: /* NumC */0, _0: 5 } }; var an = interp({ TAG: /* PlusC */3, _0: { TAG: /* MultC */4, _0: { TAG: /* AppC */2, _0: "double", _1: { TAG: /* NumC */0, _0: 2 } }, _1: { TAG: /* NumC */0, _0: 4 } }, _1: { TAG: /* NumC */0, _0: 3 } }, { hd: fd1, tl: { hd: fd2, tl: { hd: fd3, tl: /* [] */0 } } }); console.log(an); var an1 = interp(desugar({ TAG: /* PlusS */1, _0: { TAG: /* SquareS */4, _0: { TAG: /* NumS */0, _0: 8 } }, _1: { TAG: /* NumS */0, _0: 3 } }), { hd: fd1, tl: { hd: fd2, tl: { hd: fd3, tl: /* [] */0 } } }); exports.getFunDef = getFunDef; exports.fdCarg = fdCarg; exports.fdCbody = fdCbody; exports.subst = subst; exports.interp = interp; exports.desugar = desugar; exports.fd1 = fd1; exports.fd2 = fd2; exports.fd3 = fd3; exports.an = an; exports.an1 = an1; /* an Not a pure module */ <file_sep>/rescript/src/ch07_interp_functions_as_values.bs.js // Generated by ReScript, PLEASE EDIT WITH CARE 'use strict'; var Belt_List = require("rescript/lib/js/belt_List.js"); function getNum(myType) { if (myType.TAG === /* NumV */0) { return myType._0; } throw { RE_EXN_ID: "Not_found", Error: new Error() }; } function isNum(x) { if (x.TAG === /* NumV */0) { return true; } else { return false; } } var Value = { getNum: getNum, isNum: isNum }; function fdCarg(fd) { if (fd.TAG !== /* NumV */0) { return fd._1; } throw { RE_EXN_ID: "Not_found", Error: new Error() }; } function fdCbody(fd) { if (fd.TAG !== /* NumV */0) { return fd._2; } throw { RE_EXN_ID: "Not_found", Error: new Error() }; } function lookup(n, _env) { while(true) { var env = _env; if (env) { var a = env.hd; if (a._0 === n) { return a._1; } _env = env.tl; continue ; } throw { RE_EXN_ID: "Not_found", Error: new Error() }; }; } function numPlus(l, r) { if (isNum(l) && isNum(r)) { return { TAG: /* NumV */0, _0: getNum(l) + getNum(r) | 0 }; } throw { RE_EXN_ID: "Not_found", Error: new Error() }; } function numMult(l, r) { if (isNum(l) && isNum(r)) { return { TAG: /* NumV */0, _0: Math.imul(getNum(l), getNum(r)) }; } throw { RE_EXN_ID: "Not_found", Error: new Error() }; } function interp(_exp, _env) { while(true) { var env = _env; var exp = _exp; switch (exp.TAG | 0) { case /* NumC */0 : return { TAG: /* NumV */0, _0: exp._0 }; case /* IdC */1 : return lookup(exp._0, env); case /* FdC */2 : return { TAG: /* FunV */1, _0: exp._0, _1: exp._1, _2: exp._2 }; case /* AppC */3 : var fd = interp(exp._0, env); _env = Belt_List.add(/* [] */0, /* Bind */{ _0: fdCarg(fd), _1: interp(exp._1, env) }); _exp = fdCbody(fd); continue ; case /* PlusC */4 : return numPlus(interp(exp._0, env), interp(exp._1, env)); case /* MultC */5 : return numMult(interp(exp._0, env), interp(exp._1, env)); } }; } function desugar(ars) { switch (ars.TAG | 0) { case /* NumS */0 : return { TAG: /* NumC */0, _0: ars._0 }; case /* PlusS */1 : return { TAG: /* PlusC */4, _0: desugar(ars._0), _1: desugar(ars._1) }; case /* MultS */2 : return { TAG: /* MultC */5, _0: desugar(ars._0), _1: desugar(ars._1) }; case /* MinusS */3 : return { TAG: /* PlusC */4, _0: desugar(ars._0), _1: { TAG: /* MultC */5, _0: { TAG: /* NumC */0, _0: -1 }, _1: desugar(ars._1) } }; case /* SquareS */4 : var l = ars._0; return { TAG: /* PlusC */4, _0: desugar(l), _1: desugar(l) }; } } var an = interp({ TAG: /* PlusC */4, _0: { TAG: /* MultC */5, _0: { TAG: /* AppC */3, _0: { TAG: /* FdC */2, _0: "double", _1: "x", _2: { TAG: /* PlusC */4, _0: { TAG: /* IdC */1, _0: "x" }, _1: { TAG: /* NumC */0, _0: 5 } } }, _1: { TAG: /* NumC */0, _0: 2 } }, _1: { TAG: /* NumC */0, _0: 4 } }, _1: { TAG: /* NumC */0, _0: 3 } }, /* [] */0); console.log(getNum(an)); var an1 = interp(desugar({ TAG: /* PlusS */1, _0: { TAG: /* SquareS */4, _0: { TAG: /* NumS */0, _0: 8 } }, _1: { TAG: /* NumS */0, _0: 3 } }), /* [] */0); var mtEnv = /* [] */0; var extendEnv = Belt_List.add; var fd1 = { TAG: /* FdC */2, _0: "double", _1: "x", _2: { TAG: /* PlusC */4, _0: { TAG: /* IdC */1, _0: "x" }, _1: { TAG: /* NumC */0, _0: 5 } } }; var fd2 = { TAG: /* FdC */2, _0: "quad", _1: "x", _2: { TAG: /* AppC */3, _0: { TAG: /* FdC */2, _0: "double", _1: "x", _2: { TAG: /* PlusC */4, _0: { TAG: /* IdC */1, _0: "x" }, _1: { TAG: /* NumC */0, _0: 5 } } }, _1: { TAG: /* NumC */0, _0: 5 } } }; var fd3 = { TAG: /* FdC */2, _0: "const5", _1: "_", _2: { TAG: /* NumC */0, _0: 5 } }; exports.Value = Value; exports.fdCarg = fdCarg; exports.fdCbody = fdCbody; exports.mtEnv = mtEnv; exports.extendEnv = extendEnv; exports.lookup = lookup; exports.numPlus = numPlus; exports.numMult = numMult; exports.interp = interp; exports.desugar = desugar; exports.fd1 = fd1; exports.fd2 = fd2; exports.fd3 = fd3; exports.an = an; exports.an1 = an1; /* an Not a pure module */ <file_sep>/README.md # PLAI This repo has exercises from the book `Programming Languages: Application and Interpretation` by <NAME>. I write the exercises in both Racket-PLAI and Rescript. <file_sep>/rescript/src/ch1_4_interp_basic.bs.js // Generated by ReScript, PLEASE EDIT WITH CARE 'use strict'; function interp(_exp) { while(true) { var exp = _exp; switch (exp.TAG | 0) { case /* NumC */0 : return exp._0; case /* PlusC */1 : return interp(exp._0) + interp(exp._1) | 0; case /* MultC */2 : return Math.imul(interp(exp._0), interp(exp._1)); case /* IfCondC */3 : if (interp(exp._0) === 0) { _exp = exp._2; continue ; } _exp = exp._1; continue ; } }; } function desugar(ars) { switch (ars.TAG | 0) { case /* NumS */0 : return { TAG: /* NumC */0, _0: ars._0 }; case /* PlusS */1 : return { TAG: /* PlusC */1, _0: desugar(ars._0), _1: desugar(ars._1) }; case /* MultS */2 : return { TAG: /* MultC */2, _0: desugar(ars._0), _1: desugar(ars._1) }; case /* MinusS */3 : return { TAG: /* PlusC */1, _0: desugar(ars._0), _1: { TAG: /* MultC */2, _0: { TAG: /* NumC */0, _0: -1 }, _1: desugar(ars._1) } }; case /* SquareS */4 : var l = ars._0; return { TAG: /* PlusC */1, _0: desugar(l), _1: desugar(l) }; case /* IfCondS */5 : return { TAG: /* IfCondC */3, _0: desugar(ars._0), _1: desugar(ars._1), _2: desugar(ars._2) }; } } var an = interp({ TAG: /* PlusC */1, _0: { TAG: /* MultC */2, _0: { TAG: /* NumC */0, _0: 2 }, _1: { TAG: /* NumC */0, _0: 4 } }, _1: { TAG: /* NumC */0, _0: 3 } }); var an1 = interp(desugar({ TAG: /* PlusS */1, _0: { TAG: /* SquareS */4, _0: { TAG: /* NumS */0, _0: 8 } }, _1: { TAG: /* NumS */0, _0: 3 } })); exports.interp = interp; exports.desugar = desugar; exports.an = an; exports.an1 = an1; /* an Not a pure module */ <file_sep>/rescript/src/ch06_interp_env.bs.js // Generated by ReScript, PLEASE EDIT WITH CARE 'use strict'; var Belt_List = require("rescript/lib/js/belt_List.js"); function getFunDef(f, _fds) { while(true) { var fds = _fds; if (fds) { var a = fds.hd; if (f === a._0) { return a; } _fds = fds.tl; continue ; } throw { RE_EXN_ID: "Not_found", Error: new Error() }; }; } function fdCarg(fd) { return fd._1; } function fdCbody(fd) { return fd._2; } function lookup(n, _env) { while(true) { var env = _env; if (env) { var a = env.hd; if (a._0 === n) { return a._1; } _env = env.tl; continue ; } throw { RE_EXN_ID: "Not_found", Error: new Error() }; }; } function interp(_exp, _env, fds) { while(true) { var env = _env; var exp = _exp; switch (exp.TAG | 0) { case /* NumC */0 : return exp._0; case /* IdC */1 : return lookup(exp._0, env); case /* AppC */2 : var fd = getFunDef(exp._0, fds); _env = Belt_List.add(env, /* Bind */{ _0: fdCarg(fd), _1: interp(exp._1, env, fds) }); _exp = fdCbody(fd); continue ; case /* PlusC */3 : return interp(exp._0, env, fds) + interp(exp._1, env, fds) | 0; case /* MultC */4 : return Math.imul(interp(exp._0, env, fds), interp(exp._1, env, fds)); case /* IfCondC */5 : if (interp(exp._0, env, fds) === 0) { _exp = exp._2; continue ; } _exp = exp._1; continue ; } }; } function desugar(ars) { switch (ars.TAG | 0) { case /* NumS */0 : return { TAG: /* NumC */0, _0: ars._0 }; case /* PlusS */1 : return { TAG: /* PlusC */3, _0: desugar(ars._0), _1: desugar(ars._1) }; case /* MultS */2 : return { TAG: /* MultC */4, _0: desugar(ars._0), _1: desugar(ars._1) }; case /* MinusS */3 : return { TAG: /* PlusC */3, _0: desugar(ars._0), _1: { TAG: /* MultC */4, _0: { TAG: /* NumC */0, _0: -1 }, _1: desugar(ars._1) } }; case /* SquareS */4 : var l = ars._0; return { TAG: /* PlusC */3, _0: desugar(l), _1: desugar(l) }; case /* IfCondS */5 : return { TAG: /* IfCondC */5, _0: desugar(ars._0), _1: desugar(ars._1), _2: desugar(ars._2) }; } } var fd1 = /* FdC */{ _0: "double", _1: "x", _2: { TAG: /* PlusC */3, _0: { TAG: /* IdC */1, _0: "x" }, _1: { TAG: /* NumC */0, _0: 5 } } }; var fd2 = /* FdC */{ _0: "quad", _1: "x", _2: { TAG: /* AppC */2, _0: "double", _1: { TAG: /* AppC */2, _0: "double", _1: { TAG: /* IdC */1, _0: "x" } } } }; var fd3 = /* FdC */{ _0: "const5", _1: "_", _2: { TAG: /* NumC */0, _0: 5 } }; var an = interp({ TAG: /* PlusC */3, _0: { TAG: /* MultC */4, _0: { TAG: /* AppC */2, _0: "double", _1: { TAG: /* NumC */0, _0: 2 } }, _1: { TAG: /* NumC */0, _0: 4 } }, _1: { TAG: /* NumC */0, _0: 3 } }, /* [] */0, { hd: fd1, tl: { hd: fd2, tl: { hd: fd3, tl: /* [] */0 } } }); console.log(an); var an1 = interp(desugar({ TAG: /* PlusS */1, _0: { TAG: /* SquareS */4, _0: { TAG: /* NumS */0, _0: 8 } }, _1: { TAG: /* NumS */0, _0: 3 } }), /* [] */0, { hd: fd1, tl: { hd: fd2, tl: { hd: fd3, tl: /* [] */0 } } }); var mtEnv = /* [] */0; var extendEnv = Belt_List.add; exports.getFunDef = getFunDef; exports.fdCarg = fdCarg; exports.fdCbody = fdCbody; exports.mtEnv = mtEnv; exports.extendEnv = extendEnv; exports.lookup = lookup; exports.interp = interp; exports.desugar = desugar; exports.fd1 = fd1; exports.fd2 = fd2; exports.fd3 = fd3; exports.an = an; exports.an1 = an1; /* an Not a pure module */
f699882e79138eb34e18bb2c79fe8bf8bd85c959
[ "JavaScript", "Markdown" ]
5
JavaScript
kesava/PLAI
5a2e73854dc44c671756c24135a7804342b6e8be
c317f54fc1ff76e9c1160de59553c75c634d8a0d
refs/heads/master
<repo_name>ericcontursi88/Java-Lista-3<file_sep>/3.2/src/Regular.java public class Regular extends Cliente { public Regular(String nome, double saldo) { super(nome, saldo); } //tarifa 1% //public void calcTarifaRegular() { // double tarifa = saldo * 0001; // System.out.println("A sua tarifa eh: " + tarifa); //} public void consultaTarifa() { System.out.println("A tarifa Regular é 1% do saldo"); } } <file_sep>/3.2/src/Cliente.java public class Cliente { //Cada cliente tem a necessidade de controle de conta corrente na conta possui nome, e saldo. public String nome; public double saldo; //Construtor public Cliente(String nome, double saldo) { this.nome = nome; this.saldo = saldo; } //public void ConsultaSaldo() { // System.out.println("Saldo"); //} public String getNome() { return nome; } public double getSaldo() { return saldo; } } <file_sep>/README.md # Java-Lista-3<file_sep>/3.3/src/Constelacao.java import java.util.ArrayList; public class Constelacao { //são atributos private String nome; private ArrayList<Estrela> estrelas; //------- public Constelacao(String nome) { this.nome = nome; this.estrelas= new ArrayList<Estrela>(); } public void adicionar(Estrela e) { estrelas.add(e); } //adicionando na lista public void infoEstrelas() { for (Estrela estrela : estrelas) { estrela.mostrar(); } //mostrei valor } //método public double tempConstelacao() { double auxTemperatura = 0.0; for (Estrela estrela : estrelas) { auxTemperatura = auxTemperatura + estrela.getTemperatura(); } return auxTemperatura; } }
75f181cbcda26338937fde4153df877199d40d20
[ "Markdown", "Java" ]
4
Java
ericcontursi88/Java-Lista-3
8eefb13e480b8a301068ffe9307a715c3e6a6b36
e3cec7c1663018c300462f6f7331982376b9a50c
refs/heads/master
<repo_name>foreverfighter/python-problem-solving<file_sep>/unsolved/no_tests/validate_binary_search_tree.py Determine whether a tree is a valid binary search tree. A binary search tree is a tree with two children, left and right, and satisfies the constraint that the key in the left child must be less than or equal to the root and the key in the right child must be greater than or equal to the root. <file_sep>/solved/count_inversions.py # We can determine how "out of order" an array A is by counting the number of # inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] # but i < j. That is, a smaller element appears after a larger element. # # Given an array, count the number of inversions it has. Do this faster than O(N^2) time. # # You may assume each element in the array is distinct. # # For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has # three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten # inversions: every distinct pair forms an inversion. # ---------------------------------------------------------------------------- # this should be faster than O(N^2), since the inner loop is shrinking each time def count_inversions(ls): total_inversions = 0 checked_elements = [] loops = len(ls) for i in range(loops): element = ls.pop() inversions = [item for item in ls if item > element] total_inversions += len(inversions) return total_inversions <file_sep>/solved/balanced_brackets.py # Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). # # For example, given the string "([])[]({})", you should return true. # # Given the string "([)]" or "((()", you should return false. # assumes that only bracket characters will be passed in def balanced_brackets(s): open_brackets = [] brackets = { '(': ')', '[': ']', '{': '}', } for char in s: if char in brackets: open_brackets.append(char) else: currently_open_bracket = open_brackets.pop() if brackets[currently_open_bracket] != char: return False if open_brackets: return False return True <file_sep>/unsolved/no_tests/return_deepest_node.py Given the root of a binary tree, return a deepest node. For example, in the following tree, return d. a / \ b c / d <file_sep>/unsolved/no_tests/LFU_cache.py Implement an LFU (Least Frequently Used) cache. It should be able to be initialized with a cache size n, and contain the following methods: set(key, value): sets key to value. If there are already n items in the cache and we are adding a new item, then it should also remove the least frequently used item. If there is a tie, then the least recently used key should be removed. get(key): gets the value at key. If no such key exists, return null. Each operation should run in O(1) time. <file_sep>/solved/product_of_the_others.py # Task: Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. # For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. import numpy as np def product_of_others(ls): new_ls = [] for i in ls: ls2 = ls.copy() ls2.remove(i) new_ls.append(np.prod(ls2)) return new_ls <file_sep>/unsolved/serialize_tree_to_string_test.py # Task: Given the root to a binary tree, implement serialize(root), which # serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. # # For example, given the following Node class # # class Node: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right # The following test should pass: # # node = Node('root', Node('left', Node('left.left')), Node('right')) # assert deserialize(serialize(node)).left.left.val == 'left.left' import pytest from serialize_tree_to_string import * @pytest.mark.parametrize("ls,expected", [([1, 2, 3, 4, 5], [120, 60, 40, 30, 24]), ([0, 2, 3, 4, 5], [120, 0, 0, 0, 0]), ([-1, 2, 3, 4, 5], [120, -60, -40, -30, -24]), ([2 for i in range(50)], [2**49 for i in range(50)])]) def test_serialize_tree_to_string(ls, expected): node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left' <file_sep>/solved/merge_and_sort_sorted_lists.py # Task : Return a new sorted merged list from K sorted lists, each with size N. # For example, if we had [[10, 15, 30], [12, 15, 20], [17, 20, 32]], the result should be [10, 12, 15, 15, 17, 20, 20, 30, 32]. import heapq def merge_and_sort_sorted_lists(lists): result = [] heap = [(lst[0], i, 0) for i, lst in enumerate(lists)] heapq.heapify(heap) while heap: smallest = heapq.heappop(heap) result.append(smallest[0]) next_index = smallest[2] + 1 if next_index < len(lists[smallest[1]]): next_tuple = (lists[smallest[1]][next_index], smallest[1], next_index) heapq.heappush(heap, next_tuple) return result <file_sep>/solved/cons_car_cdr.py # cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and # last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. # # Given this implementation of cons: # # Implement car and cdr. def cons(a, b): def pair(f): return f(a, b) return pair def car(closure): def first(a, b): return a return closure(first) def cdr(closure): def second(a, b): return b return closure(second) <file_sep>/unsolved/no_tests/graph_colorable.py # Given an undirected graph represented as an adjacency matrix and an integer k, # write a function to determine whether each vertex in the graph can be colored # such that no two adjacent vertices share the same color using at most k colors. <file_sep>/solved/any_two_add_up_to_k.py # Task: Determine if any two numbers from a list of numbers add up to k. # For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. def any_two_add_up(ls, k): if len(ls) < 2: print('The list must have at least two numbers.') targets = [] for i in ls: if i in targets: return True else: targets.append(k - i) return False <file_sep>/unsolved/no_tests/debounce_milliseconds.py Given a function f, and N return a debounced f of N milliseconds. That is, as long as the debounced f continues to be invoked, f itself will not be called for N milliseconds. <file_sep>/solved/game_of_life.py # Conway's Game of Life takes place on an infinite two-dimensional board of # square cells. Each cell is either dead or alive, and at each tick, the # following rules apply: # # Any live cell with less than two live neighbours dies. # Any live cell with two or three live neighbours remains living. # Any live cell with more than three live neighbours dies. # Any dead cell with exactly three live neighbours becomes a live cell. # A cell neighbours another cell if it is horizontally, vertically, or diagonally adjacent. # # Implement Conway's Game of Life. It should be able to be initialized with a # starting list of live cell coordinates and the number of steps it should run # for. Once initialized, it should print out the board state at each step. # Since it's an infinite board, print out only the relevant coordinates, i.e. # from the top-leftmost live cell to bottom-rightmost live cell. # # You can represent a live cell with an asterisk (*) and a dead cell with a dot (.). from __future__ import print_function def run_steps(board, steps): board = simplify_coordinates(board) if not steps: str_board = stringify(board) print(str_board) for i in range(steps): board = generate_next_board(board) str_board = stringify(board) print(str_board) def simplify_coordinates(board): if not board: return [] x_coords = [cell[0] for cell in board] y_coords = [cell[1] for cell in board] min_x, min_y = min(x_coords), min(y_coords) new_x_coords = [x - min_x for x in x_coords] new_y_coords = [y - min_y for y in y_coords] board = list(zip(new_x_coords, new_y_coords)) return board def get_width_height(board): x_coords = [cell[0] for cell in board] y_coords = [cell[1] for cell in board] width = max(x_coords) - min(x_coords) + 1 height = max(y_coords) - min(y_coords) + 1 return width, height def stringify(board): if not board: return '\n' width, height = get_width_height(board) s = '\n' for j in range(height): line = '' for i in range(width): if (i, j) in board: line += '*' else: line += '.' s = '\n' + line + s s = s[1:] return s def generate_next_board(board): width, height = get_width_height(board) candidates_for_life = set() for live_cell in board: x, y = live_cell for i in (-1, 0, 1): for j in (-1, 0, 1): candidates_for_life.add((x + i, y + j)) new_board = [] for cell in candidates_for_life: resolve_life(cell, board, new_board) return new_board def resolve_life(cell, board, new_board): n = count_live_neighbours(cell, board) if cell in board and n in (2, 3): new_board.append(cell) if cell not in board and n == 3: new_board.append(cell) def count_live_neighbours(cell, board): x, y = cell neighbours = [] for x_shift in (-1, 0, 1): for y_shift in (-1, 0, 1): neighbours.append((x + x_shift, y + y_shift)) neighbours.remove((x, y)) live_neighbours = [cell for cell in neighbours if cell in board] return len(live_neighbours) <file_sep>/solved/rand7_with_rand5_test.py # Using a function rand5() that returns an integer from 1 to 5 (inclusive) with # uniform probability, implement a function rand7() that returns an integer from # 1 to 7 (inclusive). # --------------------------------------------------------------------------------- from collections import Counter import pytest from rand7_with_rand5 import * # bad way to test, but bad way is better than no way. can do mocking instead for better testing def test_rand7(): ls = [rand7() for i in range(700)] is_reasonably_random = True for i, x in Counter(ls).items(): if x < 85: is_reasonably_random = False assert is_reasonably_random == True <file_sep>/solved/separate_into_batches.py # Task: Separate a list of elements, returning a 2d list with the inner lists having a specified length. def separate_into_batches(ls, batch_size): ls_2d = [] batch = 1 while batch < len(ls) // batch_size + 2: start = (batch - 1) * batch_size end = batch * batch_size ls_2d.append(ls[start:end]) batch += 1 return ls_2d <file_sep>/README.md # Python problem solving A collection of computing problems and my attempts at clean solutions in python, with tests. A lot of these may end up pretty naive when it comes to memory and time efficiency, but I'm trying to complete as many of them as I have time for. <file_sep>/unsolved/no_tests/detect_arbitrage_test.py # Suppose you are given a table of currency exchange rates, represented as a # 2D array. Determine whether there is a possible arbitrage: that is, whether # there is some sequence of trades you can make, starting with some amount A # of any currency, so that you can end up with some amount greater than A of # that currency. # # There are no transaction costs and you can trade fractional quantities. import pytest from detect_arbitrage import * @pytest.mark.parametrize('input,expected', [(1, 2), (3, 4)]) def test_determine_arbitrage_possibility(input, expected): assert determine_arbitrage_possibility(input) == expected <file_sep>/solved/longest_file_path.py # Suppose we represent our file system by a string in the following manner: # # The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: # # dir # subdir1 # subdir2 # file.ext # The directory dir contains an empty sub-directory subdir1 and a sub-directory # subdir2 containing a file file.ext. # # The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents: # # dir # subdir1 # file1.ext # subsubdir1 # subdir2 # subsubdir2 # file2.ext # The directory dir contains two sub-directories subdir1 and subdir2. subdir1 # contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 # contains a second-level sub-directory subsubdir2 containing a file file2.ext. # # We are interested in finding the longest (number of characters) absolute path # to a file within our file system. For example, in the second example above, the # longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is # 32 (not including the double quotes). # # Given a string representing the file system in the above format, return the # length of the longest absolute path to a file in the abstracted file system. # If there is no file in the system, return 0. # # Note: # # The name of a file contains at least a period and an extension. # # The name of a directory or sub-directory will not contain a period. def longest_file_path(filesystem): length = 0 dirs = {} lines = filesystem.split('\n') # we go through each line and calculate its total length. # we check if it's the new max (if it's a file) # or add it to the dictionary of directories, together with its # total length, so it doesn't need to be calculated again. # this way is efficient because the parent directory of the file/directory # is always in an earlier line. for i, s in enumerate(lines): level = s.count('\t') total_length = find_total_length(s, level, dirs) if '.' in s: length = max(length, total_length) else: dirs.update({i: (total_length, level)}) return length def find_total_length(s, level, dirs): own_length = len(s) - level if level == 0: return own_length else: parent_index = max( [i for i, (_, lev) in dirs.items() if lev == level - 1]) parent_length = dirs[parent_index][0] return own_length + parent_length + 1 <file_sep>/unsolved/cheapest_paint_houses.py # A builder is looking to build a row of N houses that can be of K different # colors. He has a goal of minimizing cost while ensuring that no two # neighboring houses are of the same color. # # Given an N by K matrix where the nth row and kth column represents the cost # to build the nth house with kth color, return the minimum cost which achieves # this goal. def minimum_cost(matrix): min_cost = 0 # houses = len(matrix) for house in matrix: min_cost += min(house) return min_cost <file_sep>/unsolved/crossword_searcher_test.py # Given a 2D matrix of characters and a target word, write a function that # returns whether the word can be found in the matrix by going left-to-right, or up-to-down. # # For example, given the following matrix: # # [['F', 'A', 'C', 'I'], # ['O', 'B', 'Q', 'P'], # ['A', 'N', 'O', 'B'], # ['M', 'A', 'S', 'S']] # and the target word 'FOAM', you should return true, since it's the leftmost # column. Similarly, given the target word 'MASS', you should return true, # since it's the last row. import pytest from crossword_searcher import * @pytest.mark.parametrize( 'matrix, target, expected', [([['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ['M', 'A', 'S', 'S']], 'FOAM', True), ([['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ['M', 'A', 'S', 'S']], 'MASS', True), ([['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ['M', 'A', 'S', 'S']], 'BOAT', False)]) def test_check_for_word(matrix, target, expected): assert check_for_word(matrix, target) == expected <file_sep>/unsolved/no_tests/_test.py import pytest from cheapest_paint_houses import * @pytest.mark.parametrize('input,expected', [(1, 2), (3, 4)]) def test_funcname(input, expected): assert funcname(input) == expected <file_sep>/solved/autocomplete_test.py # Implement an autocomplete system. That is, given a query string s and a set of # all possible query strings, return all strings in the set that have s as a prefix. # Hint: Try preprocessing the dictionary into a more efficient data structure to # speed up queries. import pytest from autocomplete import * @pytest.mark.parametrize("q,set,expected", [('de', ('dog', 'deer', 'deal'), ['deer', 'deal'])]) def test_autocomplete(q, set, expected): assert autocomplete(q, set) == expected <file_sep>/solved/game_of_life_test.py # Conway's Game of Life takes place on an infinite two-dimensional board of # square cells. Each cell is either dead or alive, and at each tick, the # following rules apply: # # Any live cell with less than two live neighbours dies. # Any live cell with two or three live neighbours remains living. # Any live cell with more than three live neighbours dies. # Any dead cell with exactly three live neighbours becomes a live cell. # A cell neighbours another cell if it is horizontally, vertically, or diagonally adjacent. # # Implement Conway's Game of Life. It should be able to be initialized with a # starting list of live cell coordinates and the number of steps it should run # for. Once initialized, it should print out the board state at each step. # Since it's an infinite board, print out only the relevant coordinates, i.e. # from the top-leftmost live cell to bottom-rightmost live cell. # # You can represent a live cell with an asterisk (*) and a dead cell with a dot (.). import pytest from game_of_life import * @pytest.mark.parametrize( 'board,steps,expected', [([(0, 0)], 0, '*\n\n'), ([(0, 0), (1, 0)], 0, '**\n\n'), ([(0, 0), (0, 1)], 0, '*\n*\n\n'), ([(0, 0), (0, 1), (1, 0), (1, 1)], 0, '**\n**\n\n'), ([(1, 0), (0, 1)], 0, '*.\n.*\n\n'), ([(0, 0)], 1, '\n\n'), ([(0, 0), (1, 0), (0, 1)], 1, '**\n**\n\n'), ([(0, 0), (1, 0), (0, 1)], 3, '**\n**\n\n**\n**\n\n**\n**\n\n'), ([(5, 5), (6, 5), (5, 6)], 3, '**\n**\n\n**\n**\n\n**\n**\n\n')]) # yapf: disable def test_run_steps(board, steps, expected, capsys): run_steps(board, steps) captured = capsys.readouterr() assert captured.out == expected <file_sep>/unsolved/no_tests/random_not_in_l.py Given an integer n and a list of integers l, write a function that randomly generates a number from 0 to n-1 that isn't in l (uniform). <file_sep>/solved/number_to_base36.py # Task: Take a positive integer and output a base-36 string. def to_b36(num): num_to_b36 = { num: chr(ord) for num, ord in zip( list(range(1, 37)), list(range(48, 58)) + list(range(97, 123))) } values = [] values.append(num % 36) while num // 36 > 0: num = num // 36 values.append(num % 36) s = '' for value in values: s += num_to_b36[value] return s <file_sep>/unsolved/binary_tree_locking.py # Implement locking in a binary tree. A binary tree node can be locked or unlocked only if all of its descendants or ancestors are not locked. # # Design a binary tree node class with the following methods: # # is_locked, which returns whether the node is locked # lock, which attempts to lock the node. If it cannot be locked, then it should return false. Otherwise, it should lock it and return true. # unlock, which unlocks the node. If it cannot be unlocked, then it should return false. Otherwise, it should unlock it and return true. # You may augment the node to add parent pointers or any other property you would like. You may assume the class is used in a single-threaded program, so there is no need for actual locks or mutexes. Each method should run in O(h), where h is the height of the tree. def autocomplete(q, set): letters = len(q) matches = [s for s in set if s[:letters] == q] return matches <file_sep>/unsolved/no_tests/min_paren_for_validity.py Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make the string valid (i.e. each open parenthesis is eventually closed). For example, given the string "()())()", you should return 1. Given the string ")(", you should return 2, since we must remove all of them. <file_sep>/unsolved/no_tests/palindromify.py # Given a string, find the palindrome that can be made by inserting the fewest # number of characters as possible anywhere in the word. If there is more than # one palindrome of minimum length that can be made, return the lexicographically # earliest one (the first one alphabetically). # # For example, given the string "race", you should return "ecarace", since we can # add three letters to it (which is the smallest amount to make a palindrome). There # are seven other palindromes that can be made from "race" by adding three letters, # but "ecarace" comes first alphabetically. # # As another example, given the string "google", you should return "elgoogle". <file_sep>/unsolved/no_tests/rows_to_remove_to_order_columns_lexicographically.py You are given an N by M 2D matrix of lowercase letters. Determine the minimum number of columns that can be removed to ensure that each row is ordered from top to bottom lexicographically. That is, the letter at each column is lexicographically later as you go down each row. It does not matter whether each row itself is ordered lexicographically. For example, given the following table: cba daf ghi This is not ordered because of the a in the center. We can remove the second column to make it ordered: ca df gi So your function should return 1, since we only needed to remove 1 column. As another example, given the following table: abcdef Your function should return 0, since the rows are already ordered (there's only one row). As another example, given the following table: zyx wvu tsr Your function should return 3, since we would need to remove all the columns to order it. <file_sep>/solved/any_two_add_up_to_k_test.py # Task: Determine if any two numbers from a list of numbers add up to k. # For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. import pytest from any_two_add_up_to_k import * @pytest.mark.parametrize( "ls,k,expected", [([10, 15, 3, 7], 17, True), ([10, 15, 3, 7], 18, True), ([10, 15, 3, 7], 50, False), ([-1, 3, 5, 7], 4, True), ([i for i in range(100)], 107, True), ([i for i in range(1000)], 1997, True)]) # yapf: disable def test_any_two_add_up(ls, k, expected): assert any_two_add_up(ls, k) == expected <file_sep>/unsolved/no_tests/queue_with_two_stacks.py # Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) # data structure with the following methods: enqueue, which inserts an element # into the queue, and dequeue, which removes it. <file_sep>/solved/balanced_brackets_test.py # Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). # # For example, given the string "([])[]({})", you should return true. # # Given the string "([)]" or "((()", you should return false. import pytest from balanced_brackets import * @pytest.mark.parametrize("s,expected", [("([])[]({})", True), ("([)]", False), ("((()", False)]) # yapf: disable def test_balanced_brackets(s, expected): assert balanced_brackets(s) == expected <file_sep>/solved/count_inversions_test.py # We can determine how "out of order" an array A is by counting the number of # inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] # but i < j. That is, a smaller element appears after a larger element. # # Given an array, count the number of inversions it has. Do this faster than O(N^2) time. # # You may assume each element in the array is distinct. # # For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has # three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten # inversions: every distinct pair forms an inversion. import pytest from count_inversions import * @pytest.mark.parametrize('input,expected', [([2, 4, 1, 3, 5], 3), ([5, 4, 3, 2, 1], 10)]) def test_count_inversions(input, expected): assert count_inversions(input) == expected <file_sep>/solved/cons_car_cdr_test.py # cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and # last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. # Given this implementation of cons: # def cons(a, b): # def pair(f): # return f(a, b) # return pair # Implement car and cdr. import pytest from cons_car_cdr import * @pytest.mark.parametrize("input,expected", [(cons(3, 4), 3)]) def test_car(input, expected): assert car(input) == expected @pytest.mark.parametrize("input,expected", [(cons(3, 4), 4)]) def test_cdr(input, expected): assert cdr(input) == expected <file_sep>/solved/merge_and_sort_sorted_lists_test.py # Task : Return a new sorted merged list from K sorted lists, each with size N. # For example, if we had [[10, 15, 30], [12, 15, 20], [17, 20, 32]], the result should be [10, 12, 15, 15, 17, 20, 20, 30, 32]. import pytest from merge_and_sort_sorted_lists import * @pytest.mark.parametrize("lists,expected", [ ([[10, 15, 30], [12, 15, 20], [17, 20, 32]], [10, 12, 15, 15, 17, 20, 20, 30, 32]), ([[1, 50, 51], [2, 42, 43], [3, 99, 200]], [1, 2, 3, 42, 43, 50, 51, 99, 200]), ]) # yapf: disable def test_merge_and_sort_sorted_lists(lists, expected): assert merge_and_sort_sorted_lists(lists) == expected <file_sep>/solved/product_of_the_others_test.py # Task: Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. # For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. import pytest from product_of_the_others import * @pytest.mark.parametrize("ls,expected", [([1, 2, 3, 4, 5], [120, 60, 40, 30, 24]), ([0, 2, 3, 4, 5], [120, 0, 0, 0, 0]), ([-1, 2, 3, 4, 5], [120, -60, -40, -30, -24]), ([2 for i in range(50)], [2**49 for i in range(50)])]) # yapf: disable def test_product_of_others(ls, expected): assert product_of_others(ls) == expected <file_sep>/solved/rand7_with_rand5.py # Using a function rand5() that returns an integer from 1 to 5 (inclusive) with # uniform probability, implement a function rand7() that returns an integer from # 1 to 7 (inclusive). # --------------------------------------------------------------------------------- # we just treat each number from 1 to 7 as a player rolling off with a 5 sided die! import random def rand7(): return roll_off(range(1, 8)) def roll_off(contenders): scores = [rand5() for i in contenders] tied_contenders = [ contenders[i] for i, x in enumerate(scores) if x == max(scores) ] if len(tied_contenders) == 1: return tied_contenders[0] else: return roll_off(tied_contenders) def rand5(): return random.randint(1, 5) <file_sep>/unsolved/no_tests/file_syncing.py # Implement a file syncing algorithm for two computers over a low-bandwidth # network. What if we know the files in the two computers are mostly the same? <file_sep>/unsolved/biggest_product_test.py # Given a list of integers, return the largest product that can be made by # multiplying any three integers. # # For example, if the list is [-10, -10, 5, 2], we should return 500, since # that's -10 * -10 * 5. # # You can assume the list has at least three integers. import pytest from biggest_product import * @pytest.mark.parametrize('ls,expected', [([-10, -10, 5, 2], 500), ([10, -10, 5, 2], 100), ([3, 4, 5], 60), ([-10, -15, -20, 2, 10], 3000)]) # yapf: disable def test_get_biggest_product(ls, expected): assert get_biggest_product(ls) == expected <file_sep>/unsolved/no_tests/hopping_through_an_integer_list.py Given an integer list where each number represents the number of hops you can make, determine whether you can reach to the last index starting at index 0. For example, [2, 0, 1, 0] returns true while [1, 1, 0, 1] returns false. <file_sep>/unsolved/cheapest_paint_houses_test.py # A builder is looking to build a row of N houses that can be of K different # colors. He has a goal of minimizing cost while ensuring that no two # neighboring houses are of the same color. # # Given an N by K matrix where the nth row and kth column represents the cost # to build the nth house with kth color, return the minimum cost which achieves # this goal. import pytest from cheapest_paint_houses import * @pytest.mark.parametrize('input,expected', [([[1, 2], [2, 1]], 2), ([[1, 5, 7], [1, 3, 2], [2, 2, 2], [1, 5, 6]], 6)]) def test_minimum_cost(input, expected): assert minimum_cost(input) == expected <file_sep>/solved/autocomplete.py # Implement an autocomplete system. That is, given a query string s and a set of # all possible query strings, return all strings in the set that have s as a prefix. # Hint: Try preprocessing the dictionary into a more efficient data structure to # speed up queries. def autocomplete(q, set): letters = len(q) matches = [s for s in set if s[:letters] == q] return matches <file_sep>/solved/separate_into_batches_test.py # Task: Separate a list of elements, returning a 2d list with the inner lists having a specified length. import pytest from separate_into_batches import * @pytest.mark.parametrize("ls,batch_size,expected", [ ([i for i in range(100)], 128, [[i for i in range(100)]]), ([i for i in range(500)], 128, [[i for i in range(500)][:128], [i for i in range(500)][128:256], [i for i in range(500)][256:384], [i for i in range(500)][384:]]), ]) # yapf: disable def test_separate_into_batches(ls, batch_size, expected): assert separate_into_batches(ls, batch_size) == expected <file_sep>/solved/number_to_base36_test.py # Task: Take a one-indexed number and output a one-indexed base-36 string. import pytest from number_to_base36 import * @pytest.mark.parametrize("num,expected", [(1,'0'), (10,'9'), (11,'a'), (1764102650123,'af350ehl')]) # yapf: disable def test_to_b36(num, expected): assert to_b36(num) == expected <file_sep>/unsolved/no_tests/trace_a_path.py You are in an infinite 2D grid where you can move in any of the 8 directions: (x,y) to (x+1, y), (x - 1, y), (x, y+1), (x, y-1), (x-1, y-1), (x+1,y+1), (x-1,y+1), (x+1,y-1) You are given a sequence of points and the order in which you need to cover the points. Give the minimum number of steps in which you can achieve it. You start from the first point. Example: Input: [(0, 0), (1, 1), (1, 2)] Output: 2 It takes 1 step to move from (0, 0) to (1, 1). It takes one more step to move from (1, 1) to (1, 2). <file_sep>/unsolved/no_tests/maximum_path_sum_between_nodes.py Given a binary tree of integers, find the maximum path sum between two nodes. The path must go through at least one node, and does not need to go through the root.
dc17584cea87813f08bc8f4d4ce5b02d06d89b38
[ "Markdown", "Python" ]
46
Python
foreverfighter/python-problem-solving
1796e9b39ad1b366ec0952190231e6ca14a85224
0314eb359eda35b33936cc011152cb80f6d2b5a1
refs/heads/main
<file_sep>package companyAll_MVC.documents; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; @Document(indexName = "announcements") @Data public class ElasticAnnouncement { @Id private String id; @Field(type = FieldType.Auto) private Integer aid; @Field(type = FieldType.Text) private String no; @Field(type = FieldType.Text) private String title; @Field(type = FieldType.Text) private String date; @Field(type = FieldType.Text) private String detail; @Field(type = FieldType.Text) private String status; } <file_sep>package companyAll_MVC.controllers; import companyAll_MVC.documents.ElasticNews; import companyAll_MVC.documents.ElasticNewsCategory; import companyAll_MVC.entities.News; import companyAll_MVC.entities.NewsCategory; import companyAll_MVC.repositories._elastic.ElasticNewsCategoryRepository; import companyAll_MVC.repositories._elastic.ElasticNewsRepository; import companyAll_MVC.repositories._jpa.NewsCategoryRepository; import companyAll_MVC.repositories._jpa.NewsRepository; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Util; import org.apache.commons.io.FileUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.*; @Controller @RequestMapping("/news") public class NewsAddController { int chosenId = 0; int sendCount = 0; int sendSuccessCount = 0; String errorMessage = ""; final NewsRepository newsRepository; final NewsCategoryRepository newsCategoryRepository; final ElasticNewsRepository elasticNewsRepository; final ElasticNewsCategoryRepository elasticNewsCategoryRepository; public NewsAddController(NewsRepository newsRepository, NewsCategoryRepository newsCategoryRepository, ElasticNewsRepository elasticNewsRepository, ElasticNewsCategoryRepository elasticNewsCategoryRepository) { this.newsRepository = newsRepository; this.newsCategoryRepository = newsCategoryRepository; this.elasticNewsRepository = elasticNewsRepository; this.elasticNewsCategoryRepository = elasticNewsCategoryRepository; } @GetMapping("") public String newsAdd() { return "newsAdd"; } // ===========================================Category Operations - START=========================================== // Add Category @PostMapping("/categoryAdd") @ResponseBody public Map<Check, Object> categoryAdd(@RequestBody @Valid NewsCategory newsCategory, BindingResult bindingResult) { Map<Check, Object> map = new LinkedHashMap<>(); if (!bindingResult.hasErrors()) { if (newsCategory.getId() != null) { Optional<NewsCategory> optionalNewsCategory = newsCategoryRepository.findById(newsCategory.getId()); if (optionalNewsCategory.isPresent()) { try { NewsCategory newsCategory1 = newsCategoryRepository.saveAndFlush(newsCategory); ElasticNewsCategory elasticNewsCategory1 = new ElasticNewsCategory(); elasticNewsCategory1.setId(Integer.toString(newsCategory1.getId())); elasticNewsCategory1.setCategoryId(newsCategory1.getId()); elasticNewsCategory1.setNo(newsCategory1.getNo()); elasticNewsCategory1.setName(newsCategory1.getName()); elasticNewsCategory1.setDetail(newsCategory1.getDetail()); elasticNewsCategory1.setDate(newsCategory1.getDate()); elasticNewsCategory1.setStatus(newsCategory1.getStatus()); elasticNewsCategoryRepository.save(elasticNewsCategory1); map.put(Check.status, true); map.put(Check.message, "Updated operations success!"); map.put(Check.result, newsCategory); } catch (Exception ex) { System.err.println("Elastic news category update" + ex); } } } else { try { NewsCategory newsCategory1 = newsCategoryRepository.saveAndFlush(newsCategory); map.put(Check.status, true); map.put(Check.message, "Adding of News Category Operations Successful!"); map.put(Check.result, newsCategory); ElasticNewsCategory elasticNewsCategory2 = new ElasticNewsCategory(); elasticNewsCategory2.setId(Integer.toString(newsCategory1.getId())); elasticNewsCategory2.setCategoryId(newsCategory1.getId()); elasticNewsCategory2.setNo(newsCategory1.getNo()); elasticNewsCategory2.setName(newsCategory1.getName()); elasticNewsCategory2.setDetail(newsCategory1.getDetail()); elasticNewsCategory2.setDate(newsCategory1.getDate()); elasticNewsCategory2.setStatus(newsCategory1.getStatus()); elasticNewsCategoryRepository.save(elasticNewsCategory2); } catch (Exception ex) { map.put(Check.status, false); if (ex.toString().contains("constraint")) { String error = "This news category name has alredy been registered!"; Util.logger(error, NewsCategory.class); map.put(Check.message, error); } } } } else { map.put(Check.status, false); map.put(Check.errors, Util.errors(bindingResult)); } return map; } //List of News Category with pagination @ResponseBody @GetMapping("/categoryList/{stShowNumber}/{stPageNo}") public Map<Check, Object> categoryList(@PathVariable String stShowNumber, @PathVariable String stPageNo) { Map<Check, Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo, showNumber); Page<ElasticNewsCategory> categoryPage = elasticNewsCategoryRepository.findByOrderByIdAsc(pageable); map.put(Check.status, true); map.put(Check.totalPage, categoryPage.getTotalPages()); map.put(Check.message, "Content listing on page " + (pageNo + 1) + " is successful"); map.put(Check.result, categoryPage.getContent()); } catch (Exception e) { map.put(Check.status, false); String error = "An error occurred during the operation!"; System.err.println(e); Util.logger(error, NewsCategory.class); map.put(Check.message, error); } return map; } // Delete Category @ResponseBody @DeleteMapping("/categoryDelete/{stId}") public Map<Check, Object> delete(@PathVariable String stId) { Map<Check, Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); Optional<NewsCategory> optionalNewsCategory = newsCategoryRepository.findById(id); if (optionalNewsCategory.isPresent()) { ElasticNewsCategory elasticNewsCategory = elasticNewsCategoryRepository.findById(id).get(); newsCategoryRepository.deleteById(id); elasticNewsCategoryRepository.deleteById(elasticNewsCategory.getId()); map.put(Check.status, true); map.put(Check.message, "Data has been deleted!"); map.put(Check.result, optionalNewsCategory.get()); } else { String error = "News Category not found"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, NewsCategory.class); } } catch (Exception e) { String error = "An error occurred during the delete operation"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, NewsCategory.class); System.err.println(e); } return map; } // ElasticSearch Category @ResponseBody @GetMapping("/searchNewsCategory/{data}/{stPageNo}/{stShowNumber}") public Map<Check, Object> searchNewsCategory(@PathVariable String data, @PathVariable String stPageNo, @PathVariable String stShowNumber) { Map<Check, Object> map = new LinkedHashMap<>(); try { System.out.println("burada :"); int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo, showNumber); System.out.println("burada pageable:" + pageable); System.out.println("burada data:" + data); Page<ElasticNewsCategory> searchPage = elasticNewsCategoryRepository.findBySearchData(data, pageable); System.out.println("burada searchPage:" + searchPage); List<ElasticNewsCategory> elasticNewsCategoryList = searchPage.getContent(); System.out.println("burada elasticNewsCategoryList:" + elasticNewsCategoryList); int totalData = elasticNewsCategoryList.size(); //for total data in table System.out.println("burada totalData:" + totalData); if (totalData > 0) { map.put(Check.status, true); map.put(Check.totalPage, searchPage.getTotalPages()); map.put(Check.message, "Search operation success!"); map.put(Check.result, elasticNewsCategoryList); } else { map.put(Check.status, false); map.put(Check.message, "Could not find a result for your search!"); } } catch (NumberFormatException e) { map.put(Check.status, false); String error = "An error occurred during the search operation!"; System.err.println(e); Util.logger(error, NewsCategory.class); map.put(Check.message, error); } return map; } // Category List @ResponseBody @GetMapping("/categoryList") public Map<Check, Object> categoryList() { Map<Check, Object> map = new LinkedHashMap<>(); map.put(Check.status, true); map.put(Check.message, "News category list operations success!"); map.put(Check.result, newsCategoryRepository.findAll()); return map; } // ===========================================Category Operations - END============================================= // ===========================================News Operations - START================================================= // News - Add and Update @PostMapping("/add") @ResponseBody public Map<Check, Object> newsAdd(@RequestBody @Valid News news, BindingResult bindingResult) { Map<Check, Object> map = new LinkedHashMap<>(); if (!bindingResult.hasErrors()) { if (news.getId() != null) { Optional<News> optionalNews = newsRepository.findById(news.getId()); if (optionalNews.isPresent()) { try { News news1 = newsRepository.saveAndFlush(news); System.out.println("news1: " + news1); ElasticNews elasticNews = new ElasticNews(); elasticNews.setId(Integer.toString(news1.getId())); elasticNews.setNo(Long.toString(news1.getNo())); elasticNews.setTitle(news1.getTitle()); elasticNews.setSummary(news1.getSummary()); elasticNews.setDescription(news1.getDescription()); elasticNews.setStatus(news1.getStatus()); elasticNews.setDate(news1.getDate()); elasticNews.setCategoryName(news1.getNewsCategory().getName()); elasticNews.setCategoryId(Integer.toString(news1.getNewsCategory().getId())); elasticNewsRepository.save(elasticNews); map.put(Check.status, true); map.put(Check.message, "Updated operations success!"); map.put(Check.result, news); } catch (Exception ex) { System.err.println("elastic news update : " + ex); } } } else { try { News news1 = newsRepository.saveAndFlush(news); map.put(Check.status, true); map.put(Check.message, "Adding of News Operations Successful!"); map.put(Check.result, news); NewsCategory newsCategory = newsCategoryRepository.findById(news.getNewsCategory().getId()).get(); ElasticNews elasticNews = new ElasticNews(); elasticNews.setId(Integer.toString(news1.getId())); elasticNews.setNo(Long.toString(news1.getNo())); elasticNews.setTitle(news1.getTitle()); elasticNews.setSummary(news1.getSummary()); elasticNews.setDescription(news1.getDescription()); elasticNews.setStatus(news1.getStatus()); elasticNews.setDate(news1.getDate()); elasticNews.setCategoryName(newsCategory.getName()); elasticNews.setCategoryId(Integer.toString(news1.getNewsCategory().getId())); elasticNewsRepository.save(elasticNews); } catch (Exception ex) { map.put(Check.status, false); if (ex.toString().contains("constraint")) { String error = "This news name has alredy been registered!"; Util.logger(error, News.class); map.put(Check.message, error); } } } } else { map.put(Check.status, false); map.put(Check.errors, Util.errors(bindingResult)); } return map; } //List of News with pagination @ResponseBody @GetMapping("/newslist/{stShowNumber}/{stPageNo}") public Map<Check, Object> listNews(@PathVariable String stShowNumber, @PathVariable String stPageNo) { Map<Check, Object> map = new LinkedHashMap<>(); //System.out.println(stShowNumber + " " + stPageNo); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo, showNumber); Page<ElasticNews> newsPage = elasticNewsRepository.findByOrderByIdAsc(pageable); map.put(Check.status, true); map.put(Check.totalPage, newsPage.getTotalPages()); map.put(Check.message, "News listing on page " + (pageNo + 1) + " is successful"); map.put(Check.result, newsPage.getContent()); } catch (Exception e) { map.put(Check.status, false); String error = "An error occurred during the operation!"; System.err.println(e); Util.logger(error, News.class); map.put(Check.message, error); } return map; } // Get id data from Choosen news @ResponseBody @GetMapping("/chosenId/{stId}") public int chosenId(@PathVariable String stId) { try { int id = Integer.parseInt(stId); Optional<News> optionalNews = newsRepository.findById(id); if (optionalNews.isPresent()) { chosenId = id; } } catch (Exception e) { System.err.println("Chosen Id Error: " + e); } System.out.println("Resim eklemek için seçilen ürünün ıd numarası: " + chosenId); return chosenId; } // Add News Images @PostMapping("/imageUpload") public String imageUpload(@RequestParam("imageName") MultipartFile[] files) { System.out.println(chosenId); Optional<News> optionalNews = newsRepository.findById(chosenId); List<String> imageNameList = new ArrayList<>(); File f = new File(Util.UPLOAD_DIR_NEWS + ("" + chosenId)); boolean isDeleted = f.delete(); if (optionalNews.isPresent()) { News news = optionalNews.get(); if (files != null && files.length != 0) { sendCount = files.length; String idFolder = "" + chosenId + "/"; File folderNews = new File(Util.UPLOAD_DIR_NEWS + idFolder); boolean status = folderNews.mkdir(); for (MultipartFile file : files) { Map<Check, Object> imgResult = Util.imageUpload(file, Util.UPLOAD_DIR_NEWS + idFolder); imageNameList.add(imgResult.get(Check.message).toString()); } news.setFileName(imageNameList); newsRepository.saveAndFlush(news); Optional<ElasticNews> elasticNewsOptional = elasticNewsRepository.findById(Integer.toString(news.getId())); if (elasticNewsOptional.isPresent()) { ElasticNews elasticNews = elasticNewsOptional.get(); elasticNews.setFileName(imageNameList); elasticNewsRepository.save(elasticNews); } else { errorMessage = "Elastic News is not found"; } } else { errorMessage = "Please choose an image"; System.err.println(errorMessage); } } else { errorMessage = "News is not found"; System.err.println(errorMessage); } return "redirect:/news"; } //Detail of news @ResponseBody @GetMapping("/detail/{stId}") public Map<Check, Object> detailNews(@PathVariable String stId) { Map<Check, Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); map.put(Check.status, true); map.put(Check.message, "News detail operation is successful!"); map.put(Check.result, newsRepository.findById(id).get()); } catch (Exception e) { map.put(Check.status, false); String error = "An error occurred during the operation!"; System.err.println(e); Util.logger(error, News.class); map.put(Check.message, error); } return map; } //Delete news @ResponseBody @DeleteMapping("/delete/{stId}") public Map<Check, Object> deleteNews(@PathVariable String stId) { Map<Check, Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); Optional<News> optionalNews = newsRepository.findById(id); if (optionalNews.isPresent()) { //Images Delete News news = optionalNews.get(); news.getFileName().forEach(item -> { File file = new File(Util.UPLOAD_DIR_NEWS + stId + "/" + item); file.delete(); }); File file = new File(Util.UPLOAD_DIR_NEWS + stId); if (file.exists()) { file.delete(); } //Images Delete ElasticNews elasticNews = elasticNewsRepository.findById(Integer.toString(id)).get(); newsRepository.deleteById(id); elasticNewsRepository.deleteById(elasticNews.getId()); map.put(Check.status, true); map.put(Check.message, "Data has been deleted!"); map.put(Check.result, optionalNews.get()); } else { String error = "NEws is not found"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, News.class); } } catch (Exception e) { String error = "An error occurred during the delete operation"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, News.class); System.err.println(e); } return map; } //Elasticsearch for News @ResponseBody @GetMapping("/search/{data}/{stPageNo}/{stShowNumber}") public Map<Check, Object> searchNews(@PathVariable String data, @PathVariable String stPageNo, @PathVariable String stShowNumber) { Map<Check, Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo, showNumber); Page<ElasticNews> searchPage = elasticNewsRepository.findBySearchData(data, pageable); List<ElasticNews> elasticNewsList = searchPage.getContent(); int totalData = elasticNewsList.size(); //for total data in table if (totalData > 0) { map.put(Check.status, true); map.put(Check.totalPage, searchPage.getTotalPages()); map.put(Check.message, "Search operation success!"); map.put(Check.result, elasticNewsList); } else { map.put(Check.status, false); map.put(Check.message, "Could not find a result for your search!"); } } catch (NumberFormatException e) { map.put(Check.status, false); String error = "An error occurred during the search operation!"; System.err.println(e); Util.logger(error, News.class); map.put(Check.message, error); } return map; } //Chosen image delete @ResponseBody @DeleteMapping("/chosenImages/delete/{images}") public Map<Check, Object> deleteChosenImage(@PathVariable List<String> images) { Map<Check, Object> map = new LinkedHashMap<>(); try { if (images.size() > 0) { for (int i = 0; i < images.size(); i++) { System.out.println("Silinmek istenen dosya: " + images.get(i)); newsRepository.deleteImageByFileName(images.get(i)); File file = new File(Util.UPLOAD_DIR_NEWS + chosenId + "/" + images.get(i)); file.delete(); } //Elasticsearch update images - Start News news = newsRepository.findById(chosenId).get(); System.out.println("Id ye ait resimler " + news.getFileName()); ElasticNews elasticNews = elasticNewsRepository.findById(Integer.toString(chosenId)).get(); elasticNews.setFileName(news.getFileName()); elasticNewsRepository.save(elasticNews); //Elasticsearch update images - End map.put(Check.status, true); map.put(Check.message, "The selected pictures have been deleted!"); } else { map.put(Check.status, false); map.put(Check.message, "Please select a picture!"); } } catch (Exception e) { String error = "An error occurred during the image delete operation"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, News.class); System.err.println(e); } return map; } // ===========================================News Operations - END================================================= @GetMapping("/newsDetail/get_image/id={id}name={name}") public void getImage(@PathVariable Integer id, @PathVariable String name, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg; image/jpg; image/png"); File file = new File(Util.UPLOAD_DIR_NEWS + id + "/" + name); if(file.exists()){ System.out.println(file.exists()); byte[] fileContent = FileUtils.readFileToByteArray(file); response.getOutputStream().write(fileContent); }else{ File defaultFile = new File(Util.UPLOAD_DIR_NEWS + "default_image.jpg"); byte[] defaultFileContent = FileUtils.readFileToByteArray(defaultFile); response.getOutputStream().write(defaultFileContent); } response.getOutputStream().close(); } } <file_sep>package companyAll_MVC.repositories._jpa; import companyAll_MVC.entities.Advertisement; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface AdvertisementRepository extends JpaRepository<Advertisement, Integer> { Optional<Advertisement> findByName(String name); } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.Max; import javax.validation.constraints.Min; @Data @Entity @ApiModel(value = "Likes Model", description = "Likes Model Variable Definitions") public class Likes extends AuditEntity<String>{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) @ApiModelProperty(value = "Likes Id",required = true) private Integer id; @Min(value = 0,message = "Rating value has to be minimum zero!") @Max(value = 5,message = "Rating value has to be maximum five!") @ApiModelProperty(value = "Likes Rating (Must be zero to five)",required = true) private Integer rating; @ManyToOne @JoinColumn(name = "indentId") private Indent indent; } <file_sep>//------------------------------ Company Form - Start ------------------------------// $("#companyInfo_form").submit( (event) => { event.preventDefault() const companyName = $("#settings-companyName").val() const companyAddress = $("#settings-companyAddress").val() const companySector = $("#settings-companySector").val() const companyPhone = $("#settings-companyPhone").val() const obj = { companyName:companyName, companyAddress:companyAddress, companySector:companySector, companyPhone:companyPhone } Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, changes saved!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './settings/updateCompany', type: 'POST', data: JSON.stringify(obj), dataType: 'json', contentType : 'application/json; charset=utf-8', success: function (data){ //console.log(data) if(data.status === true && data.result != null){ Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }else if(data.status == true && data.result == null){ Swal.fire({ title: "Warning!", text: "Returned Data is Empty!", icon: "warning", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }else{ if (!jQuery.isEmptyObject(data.errors)) { console.log(data.errors) Swal.fire({ title: 'Error!', text: data.errors[0].fieldMessage, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }else{ Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } } }, error: function (err){ Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } }); }) //------------------------------ Company Form - End --------------------------------// //------------------------------ Company Change Password Form - Start --------------------------------// $("#changePassword_form").submit( (event) => { event.preventDefault() const oldPassword = $("#account-old-password").val() const newPassword = $("#account-<PASSWORD>").val() const reNewPassword = $("#account-<PASSWORD>").val() const obj = { oldPassword:<PASSWORD>, newPassword:<PASSWORD>, reNewPassword:<PASSWORD> } Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, changes saved!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './settings/changePassword', type: 'POST', data: JSON.stringify(obj), dataType: 'json', contentType : 'application/json; charset=utf-8', success: function (data){ //console.log(data) if(data.status == true && data.result != null){ Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); resetPasswordForm() }else if(data.status == true && data.result == null){ Swal.fire({ title: "Warning!", text: "Returned Data is Empty!", icon: "warning", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); resetPasswordForm() }else{ if (!jQuery.isEmptyObject(data.errors)) { console.log(data.errors) Swal.fire({ title: 'Error!', text: data.errors[0].fieldMessage, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }else{ Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } } }, error: function (err){ Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } }); }) function resetPasswordForm(){ $("#changePassword_form").trigger('reset') } //------------------------------ Company Change Password Form - End ----------------------------------// //------------------------------ User Information Form - Start ----------------------------------// $("#userInfo_form").submit( (event) => { event.preventDefault() const name = $("#settings-name").val() const surname = $("#settings-surname").val() const email = $("#settings-Email").val() const birthdate = $("#settings-birtDate").val() const bio = $("#settings-bio").val() const obj = { name:name, surname:surname, email:email, bio:bio, birthday:birthdate } Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, changes saved!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './settings/userInfo', type: 'POST', data: JSON.stringify(obj), dataType: 'json', contentType : 'application/json; charset=utf-8', success: function (data){ console.log(data) if(data.status == true && data.result != null){ Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }else if(data.status == true && data.result == null){ Swal.fire({ title: "Warning!", text: "Returned Data is Empty!", icon: "warning", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }else{ if (!jQuery.isEmptyObject(data.errors)) { console.log(data.errors) Swal.fire({ title: 'Error!', text: data.errors[0].fieldMessage, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }else{ Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } } }, error: function (err){ Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } }); }) //------------------------------ User Information Form - End ------------------------------------// function getProfileImage() { $.ajax({ url: '/settings/get_profile_image', type: 'GET', dataType: 'Json', success: function (data) { setProfileImage(data.result); }, error: function (err) { console.log(err) } }) } function imageUpload(formData) { $.ajax({ url: '/settings/profile_image_upload', type: "POST", headers: {'IsAjax': 'true'}, dataType: "json", processData: false, contentType: false, data: formData, success: function (data) { if (data.status === true) { Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); $('#image_upload_form').trigger("reset"); getProfileImage(data.result); } else { Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } }, error: function () { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } }); } File.prototype.convertToBase64 = function(callback){ var FR= new FileReader(); FR.onload = function(e) { callback(e.target.result) }; FR.readAsDataURL(this); } function setProfileImage(bytes) { $("#profile_image").attr("src", "data:image/*;base64," + bytes); } $('#image_upload_form').submit((event) => { event.preventDefault(); let formData = new FormData(); let image = document.getElementById("profile_image_input"); if(image.files[0] !== undefined){ formData.append("image", image.files[0]); imageUpload(formData); $("#profile_image_warning").text(""); } }); $('#profile_image_input').change((event) => { event.preventDefault(); let image_input = document.getElementById("profile_image_input"); const image = image_input.files[0]; if(image !== undefined){ image.convertToBase64(function (base64){ $("#profile_image").attr("src", base64); $("#profile_image_warning").text("*"); }) } }); getProfileImage(); <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.*; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.List; @Data @Entity @ApiModel(value = "Customer Model", description = "Customer Model Variable Definitions") public class Customer extends AuditEntity<String> { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(value = "Customer Id",required = true) private Integer id; @Column(unique = true) @NotNull(message = "Invalid customer no! (null)") @NotEmpty(message = "Invalid customer no! (empty)") @Pattern(regexp="(^$|[0-9]{10})") @ApiModelProperty(value = "Customer ten digits no",required = true) private String no; @Size(max = 50, message = "Customer name's size can be 50 at max!") @NotNull(message = "Invalid customer name! (null)") @NotEmpty(message = "Invalid customer name! (empty)") @ApiModelProperty(value = "Customer name",required = true) private String name; @Size(max = 50, message = "Customer surname's size can be 50 at max!") @NotNull(message = "Invalid customer surname! (null)") @NotEmpty(message = "Invalid customer surname! (empty)") @ApiModelProperty(value = "Customer surname",required = true) private String surname; @Column(unique = true) @NotNull(message = "Invalid customer phone number(phone1)! (null)") @NotEmpty(message = "Invalid customer phone number(phone1)! (empty)") @Pattern(regexp="(^$|[0-9]{10})") @ApiModelProperty(value = "Customer phone1 (###-###-####)",required = true) private String phone1; @Pattern(regexp="(^$|[0-9]{10})") @ApiModelProperty(value = "Customer phone2 (###-###-####)",required = true) private String phone2; @Column(unique = true) @Size(max = 50) @NotNull(message = "Invalid customer mail! (null)") @NotEmpty(message = "Invalid customer mail! (empty)") @Pattern(regexp="(^(.+)@(.+)$)") @ApiModelProperty(value = "Customer email",required = true) private String mail; @Column(unique = true) @NotNull(message = "Invalid customer tax no! (null)") @NotEmpty(message = "Invalid customer tax no! (empty)") @ApiModelProperty(value = "Customer tax no",required = true) @Pattern(regexp="(^$|[0-9]{11})") private String taxno; @NotNull(message = "Invalid customer country! (null)") @NotEmpty(message = "Invalid customer country! (empty)") @ApiModelProperty(value = "Customer country",required = true) private String country; @NotNull(message = "Invalid customer city! (null)") @NotEmpty(message = "Invalid customer city! (empty)") @ApiModelProperty(value = "Customer city",required = true) private String city; @OneToMany private List<@Valid Address> addresses; @NotNull(message = "Invalid customer status! (null)") @NotEmpty(message = "Invalid customer status! (empty)") @ApiModelProperty(value = "Customer status (Active or Passive)",required = true) @Pattern(regexp = "Active|Passive", message = "Customer status must be either 'Active' or 'Passive'") private String status; } <file_sep>package companyAll_MVC.documents; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; @Document(indexName = "customers_min") @Data public class ElasticCustomerMin { @Id private String id; @Field(type = FieldType.Auto) private Integer cid; @Field(type = FieldType.Text) private String no; @Field(type = FieldType.Text) private String name; @Field(type = FieldType.Text) private String surname; @Field(type = FieldType.Text) private String status; } <file_sep>function fncAccountActivity (){ $.ajax({ url:"http://localhost:8080/api/userActivity", success: function (data){ //console.log(data) let role = data.result.role $("#nameAndSurname").text(data.result.name + ' ' + data.result.surname) //Rol ifadeleri düzenlendi. if(role === "ROLE_ADMIN"){ $("#role").text(role.replace("ROLE_ADMIN","Admin")) } //template 'de bulunan avatar resim kısmı $.ajax({ url: '/settings/get_profile_image', type: 'GET', dataType: 'Json', success: function (data) { $("#imageProfile").attr("src", "data:image/*;base64," + data.result); }, error: function (err) { console.log(err) } }) }, error: function (err){ console.log(err) } }) } fncAccountActivity () <file_sep>package companyAll_MVC.properties; import lombok.Data; import java.util.List; @Data public class Country { private String country; private List<String> states; } <file_sep> //--------------------------------------- Definition of Days and Months - Start ---------------------------------------// const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] //--------------------------------------- Definition of Days and Months - End -----------------------------------------// //--------------------------------------- News Chart - Start -----------------------------------------// var $earningsStrokeColor2 = '#28c76f66'; var $earningsStrokeColor3 = '#28c76f33'; var $earningsChart = document.querySelector('#earnings-chart'); var earningsChartOptions; var earningsChart; function getNewsInfo(){ var returnData $.ajax({ url: './dashboard/newsChart', type: 'get', dataType: "json", async: false, contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data) returnData = data }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the news information listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) return returnData } function createNewsChart(){ var newsInfoData = getNewsInfo() //console.log(newsInfoData) earningsChartOptions = { chart: { type: 'donut', height: 120, toolbar: { show: false } }, dataLabels: { enabled: false }, series: [newsInfoData.activeNews, newsInfoData.passiveNews, newsInfoData.totalNews], legend: { show: false }, comparedResult: [2, -3, 8], labels: ['Active News', 'Passive News', 'Total News'], stroke: { width: 0 }, colors: [$earningsStrokeColor2, $earningsStrokeColor3, window.colors.solid.success], grid: { padding: { right: -20, bottom: -8, left: -20 } }, plotOptions: { pie: { startAngle: -10, donut: { labels: { show: true, name: { offsetY: 15 }, value: { offsetY: -15, formatter: function (val) { return parseInt(val); } }, total: { show: true, offsetY: 15, label: 'Total News', formatter: function (w) { return newsInfoData.totalNews; } } } } } }, responsive: [ { breakpoint: 1325, options: { chart: { height: 100 } } }, { breakpoint: 1200, options: { chart: { height: 120 } } }, { breakpoint: 1045, options: { chart: { height: 100 } } }, { breakpoint: 992, options: { chart: { height: 120 } } } ] }; earningsChart = new ApexCharts($earningsChart, earningsChartOptions); earningsChart.render(); } createNewsChart() //--------------------------------------- News Chart - End -------------------------------------------// //--------------------------------------- General Statics - Start ---------------------------------------// function generalStatics(){ $.ajax({ url: './dashboard/generalStatics', type: 'get', dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data) html = `<div class="row"> <div class="col-xl-3 col-sm-6 col-12 mb-2 mb-xl-0"> <div class="media"> <div class="avatar bg-light-primary mr-2"> <div class="avatar-content"> <i data-feather="thumbs-up" class="avatar-icon"></i> </div> </div> <div class="media-body my-auto"> <h4 class="font-weight-bolder mb-0">${data.totalLikes}</h4> <p class="card-text font-small-3 mb-0">Likes</p> </div> </div> </div> <div class="col-xl-3 col-sm-6 col-12 mb-2 mb-xl-0"> <div class="media"> <div class="avatar bg-light-info mr-2"> <div class="avatar-content"> <i data-feather="user" class="avatar-icon"></i> </div> </div> <div class="media-body my-auto"> <h4 class="font-weight-bolder mb-0">${data.totalCustomers}</h4> <p class="card-text font-small-3 mb-0">Customers</p> </div> </div> </div> <div class="col-xl-3 col-sm-6 col-12 mb-2 mb-sm-0"> <div class="media"> <div class="avatar bg-light-danger mr-2"> <div class="avatar-content"> <i data-feather="box" class="avatar-icon"></i> </div> </div> <div class="media-body my-auto"> <h4 class="font-weight-bolder mb-0">${data.totalOrders}</h4> <p class="card-text font-small-3 mb-0">Orders</p> </div> </div> </div> <div class="col-xl-3 col-sm-6 col-12"> <div class="media"> <div class="avatar bg-light-success mr-2"> <div class="avatar-content"> <i data-feather="clipboard" class="avatar-icon"></i> </div> </div> <div class="media-body my-auto"> <h4 class="font-weight-bolder mb-0">${data.totalContents}</h4> <p class="card-text font-small-3 mb-0">Contents</p> </div> </div> </div> </div>` $("#generalStatics").html(html) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the general statics listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } generalStatics() //--------------------------------------- General Statics - End -----------------------------------------// //--------------------------------------- Last Added Six Product - Start -----------------------------------------// function lastAddSixProduct(){ $.ajax({ url: './dashboard/lastAddSixProduct', type: 'get', dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data) createTableLastAddSixProduct(data.lastAddedSixProduct) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the last added six product listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } function createTableLastAddSixProduct(data){ let html = `` for (let i = 0; i < data.length; i++){ const itm = data[i] let price = priceFormatter(itm.price) var returnData = categoryInfo(itm.productCategoryId[0]) html += `<tr> <td> <div class="d-flex align-items-center"> <div> <div class="font-weight-bolder">${itm.name}</div> </div> </div> </td> <td class="text-nowrap"> <div class="d-flex flex-column"> <span class="font-weight-bolder mb-25">${itm.description}</span> </div> </td> <td> <div class="d-flex align-items-center"> <span>${returnData.name}</span> </div> </td> <td>${price} TL</td> <td> <div class="d-flex align-items-center"> <span class="font-weight-bolder mr-1">${itm.date}</span> </div> </td> </tr>` } $("#lastAddSixProduct").html(html) } lastAddSixProduct() //--------------------------------------- Last Added Six Product - End -------------------------------------------// //--------------------------------------- Last Six Order - Start -------------------------------------------// function lastSixOrder(){ $.ajax({ url: './dashboard/lastSixOrder', type: 'get', dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data) createTableLastSixOrder(data.lastSixOrder) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the last six order listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } function createTableLastSixOrder(data){ let html = `` for (let i = 0; i < data.length; i++){ const itm = data[i] var product = productDetail(itm.pid,false) let price = priceFormatter(product.price) html += `<tr> <td> <div className="d-flex align-items-center"> <div> <div className="font-weight-bolder">${itm.no}</div> </div> </div> </td> <td> <div className="d-flex align-items-center"> <span>${itm.cname}</span> </div> </td> <td className="text-nowrap"> <div className="d-flex flex-column"> <span className="font-weight-bolder mb-25">${product.name} ${product.description}</span> </div> </td> <td> <a class="dropdown-item" href="javascript:productDetail(${itm.pid},true);"> <i class="far fa-file-alt"></i> </a> </td> <td> <div className="d-flex align-items-center"> <span className="font-weight-bolder mr-1">${price} TL</span> </div> </td> </tr>` } $("#lastOrderTable").html(html) } function productDetail(id,status){ var returnData $.ajax({ url: './dashboard/chosenProductDetail/' + id, type: 'get', dataType: "json", async: false, contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data) returnData = data.result if(status === true){ createProductDetailModal(data) } }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the last six order listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) return returnData } function createProductDetailModal(data) { let html = ``; const product = data.result; const imageArr = product.fileName; for (let i = 0; i < imageArr.length; i++) { const image = imageArr[i]; html += ` <div class="swiper-slide"> <img src="/productDetail/get_image/id=${product.productId}name=${image}" class="img-fluid" alt="banner" /> </div>`; } const buttonHtml = `<button onclick='window.location.href="/productDetail/${product.productId}"' class="btn btn-outline-primary">Details</button>`; $('#order_product_image_slider').html(html); $('#order_product_button_div').html(buttonHtml); $('#order_product_modal_title').text("Product No : " + product.no); $('#order_product_title').text(product.name + " " + product.description); $('#order_product_detail').text(product.details); $('#order_product_modal').modal('toggle'); } lastSixOrder() //--------------------------------------- Last Six Order - End ---------------------------------------------// //--------------------------------------- Category Information - Start ---------------------------------------------// function categoryInfo(id){ var returnData $.ajax({ url: './dashboard/productCategoryInfo/' + id, type: 'get', dataType: "json", async: false, contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data) returnData = data.result }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the last six order listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) return returnData } //--------------------------------------- Category Information - End -----------------------------------------------// //--------------------------------------- Donut Chart Series and Labels Info - Start -----------------------------------------------// var allCategories = allCategories() var glabalLabel = [] var globalSeries = [] let totalProduct = 0 //console.log(allCategories) function donutChartLabels(){ for (let i = 0; i < allCategories.length; i++) { glabalLabel[i] = allCategories[i].name globalSeries[i] = totalProductByCategoryId(allCategories[i].categoryId) totalProduct += globalSeries[i] } } donutChartLabels() //console.log(glabalLabel) //console.log(globalSeries) //console.log(totalProduct) //--------------------------------------- Donut Chart Series and Labels Info - End -------------------------------------------------// //--------------------------------------- Donut Chart for Product - Start ---------------------------------------------// function donutChart(){ var flatPicker = $('.flat-picker'), isRtl = $('html').attr('data-textdirection') === 'rtl', chartColors = { column: { series1: '#826af9', series2: '#d2b0ff', bg: '#f8d3ff' }, success: { shade_100: '#7eefc7', shade_200: '#06774f' }, donut: { series1: '#ffe700', series2: '#00d4bd', series3: '#826bf8', series4: '#2b9bf4', series5: '#FFA1A1' }, area: { series3: '#a4f8cd', series2: '#60f2ca', series1: '#2bdac7' } }; var donutChartEl = document.querySelector('#donut-chart'), donutChartConfig = { chart: { height: 350, type: 'donut' }, legend: { show: true, position: 'bottom' }, labels: glabalLabel, series: globalSeries, colors: [ chartColors.donut.series1, chartColors.donut.series5, chartColors.donut.series3, chartColors.donut.series2 ], dataLabels: { enabled: true, formatter: function (val, opt) { return parseInt(val) + '%'; } }, plotOptions: { pie: { donut: { labels: { show: true, name: { fontSize: '2rem', fontFamily: 'Montserrat' }, value: { fontSize: '1rem', fontFamily: 'Montserrat', formatter: function (val) { return parseInt(val) ; } }, total: { show: true, fontSize: '1.5rem', label: 'Total Product', formatter: function (w) { return totalProduct; } } } } } }, responsive: [ { breakpoint: 992, options: { chart: { height: 380 } } }, { breakpoint: 576, options: { chart: { height: 320 }, plotOptions: { pie: { donut: { labels: { show: true, name: { fontSize: '1.5rem' }, value: { fontSize: '1rem' }, total: { fontSize: '1.5rem' } } } } } } } ] }; if (typeof donutChartEl !== undefined && donutChartEl !== null) { var donutChart = new ApexCharts(donutChartEl, donutChartConfig); donutChart.render(); } } donutChart() //--------------------------------------- Donut Chart for Product - End -----------------------------------------------// //--------------------------------------- All Categories - Start -----------------------------------------------// function allCategories(){ var returnData $.ajax({ url: './dashboard/allProductCategories', type: 'get', dataType: "json", async: false, contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data.result) returnData = data.result }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the last six order listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) return returnData } //--------------------------------------- All Categories - End -------------------------------------------------// //--------------------------------------- Total Product by Category Id - Start -------------------------------------------------// function totalProductByCategoryId(id){ var returnData $.ajax({ url: './dashboard/totalProductByCategoryId/' + id, type: 'get', dataType: "json", async: false, contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data.result) returnData = data.result }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the last six order listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) return returnData } //--------------------------------------- Total Product by Category Id - End ---------------------------------------------------// //--------------------------------------- Daily Announcment - Start ---------------------------------------------------// function paginationAnnouncment(totalPage){ if(totalPage > 0){ $('#pagination_announcment').twbsPagination({ totalPages: totalPage, visiblePages: 5, prev: 'Prev', first: 'First', last: 'Last', startPage: 1, onPageClick: function (event, page) { dailyAnnouncment(page-1) //$('#firstLast1-content').text('You are on Page ' + page); $('.pagination').find('li').addClass('page-item'); $('.pagination').find('a').addClass('page-link'); } }); } } function dailyAnnouncment(pageNo){ var returnData $.ajax({ url: './dashboard/dailyAnnouncment/' + pageNo, type: 'get', dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data.result) //console.log(data) if(data.status === true){ if(data.result.length > 0){ paginationAnnouncment(data.totalPage) createDailyAnnouncmentCard(data.result) } } returnData = data.result }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the daily announcment listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) return returnData } dailyAnnouncment(0) function createDailyAnnouncmentCard(data){ const d = new Date() //console.log(data) let date = data[0].date.split(" ") let html = `` if(data.length > 0){ html = `<div class="meetup-header d-flex align-items-center"> <div class="meetup-day"> <h6 class="mb-0">${days[d.getDay()]}</h6> <h3 class="mb-0">${d.getDate()}</h3> </div> <div class="my-auto"> <h4 class="card-title mb-25">${data[0].title}</h4> <p class="card-text mb-0">${data[0].detail}</p> </div> </div> <div class="media"> <div class="avatar bg-light-primary rounded mr-1"> <div class="avatar-content"> <i class="far fa-calendar"></i> </div> </div> <div class="media-body"> <h6 class="mb-0">${date[0]}</h6> <small>${date[1]}</small> </div> </div>` $("#dailyAnnouncment").html(html) } } //--------------------------------------- Daily Announcment - End -----------------------------------------------------// //--------------------------------------- Other Functions - Start -----------------------------------------------------// function priceFormatter(price){ var formattedPrice = (price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,') return formattedPrice } function dateFormatter(){ } //--------------------------------------- Other Functions - Start -----------------------------------------------------//<file_sep>package companyAll_MVC.repositories._jpa; import companyAll_MVC.entities.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface UserRepository extends JpaRepository<User,Integer> { Optional<User> findByEmailIgnoreCase(String email); } <file_sep>package companyAll_MVC.properties; import lombok.Data; @Data public class ChangePassword { private String oldPassword; private String newPassword; private String reNewPassword; } <file_sep>// ================================================CATEGORY ACTIONS - START============================================= $('#pagination_news').twbsPagination('destroy'); getAllNewsByPage(1, $("#showNewsSize").val()); $('#pagination_category').twbsPagination('destroy'); getAllNewsCategoryByPage(1, $("#showCategorySize").val()); $('#pagination_news').change(function () { $('#pagination_news').twbsPagination('destroy'); getAllNewsByPage(1, $("#showNewsSize").val()); }); $('#pagination_category').change(function () { console.log("değişti") $('#pagination_category').twbsPagination('destroy'); getAllNewsCategoryByPage(1, $("#showCategorySize").val()); }); // <------------------------------------------------FUNCTIONS - START--------------------------------------------------> function noGenerator() { const date = new Date(); const time = date.getTime(); return time.toString().substring(4); } function fncDate() { const d = new Date(); const ye = new Intl.DateTimeFormat('tr', {year: 'numeric'}).format(d) const mo = new Intl.DateTimeFormat('tr', {month: '2-digit'}).format(d) const da = new Intl.DateTimeFormat('tr', {day: '2-digit'}).format(d) return `${da}-${mo}-${ye}`; } function resetFormCategory() { select_id = 0 $('#categoryName').val("") $('#categoryDetails').val("") $('#categoryStatus').val("") getAllNewsCategoryByPage(1, 10); } function resetFormNews() { select_id_news = 0 select_id_category = 0; $('#title').val("") $('#summary').val("") $('#description').val("") $('#status').val("1") $('#newsCategories').empty() getAllNewsByPage(1, 10); allNewsCategoryList() } // <------------------------------------------------FUNCTIONS - END----------------------------------------------------> // <------------------------------------------------NEWS CATEGORY ADD - START------------------------------------------> let select_id_category = 0; $('#newsCategoryAdd_modalForm').submit((event) => { event.preventDefault() const categoryName = $('#categoryName').val() const categoryDetails = $('#categoryDetails').val() const categoryStatus = $('#categoryStatus').val() const obj = { no: noGenerator(), name: categoryName, detail: categoryDetails, status: categoryStatus == 1 ? "Active" : "Passive", date: fncDate() } if (select_id_category != 0) { // update obj["id"] = select_id_category; } $.ajax({ url: './news/categoryAdd', type: 'POST', data: JSON.stringify(obj), dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (data.status == true && data.result != null) { Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); setTimeout(function () { $("#categoryAdd_modal").modal('hide'); }, 2000); resetFormCategory() resetFormNews() } else if (data.status == true && data.result == null) { Swal.fire({ title: "Warning!", text: "Returned Data is Empty!", icon: "warning", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); resetFormCategory() resetFormNews() } else { if (!jQuery.isEmptyObject(data.errors)) { console.log("burada") console.log(data.errors) Swal.fire({ title: 'Error!', text: data.errors[0].fieldMessage, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); resetFormNews() } else { console.log("burada"); Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); resetFormNews() } } console.log(data) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) resetFormNews() } }) }) // <------------------------------------------------NEWS CATEGORY ADD - END--------------------------------------------> // <------------------------------------------------NEWS CATEGORY DELETE - START---------------------------------------> function newsCategoryDelete(id) { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './news/categoryDelete/' + id, type: 'DELETE', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (id != null) { Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); resetFormCategory() resetFormNews() } else { Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); resetFormNews() } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) resetFormNews() } }) } }); } // <------------------------------------------------NEWS CATEGORY DELETE - END-----------------------------------------> // <------------------------------------------------NEWS CATEGORY UPDATE - START---------------------------------------> function newsCategoryUpdate(i) { $('#categoryAdd_modal').modal('toggle'); const itm = globalArr[i] select_id_category = itm.id $('#categoryName').val(itm.name) $('#categoryDetails').val(itm.detail) $('#categoryStatus').val(itm.status == "Active" ? 1 : 2) resetFormNews() //console.log(select_id) } // <------------------------------------------------NEWS CATEGORY UPDATE - END-----------------------------------------> // <------------------------------------------------NEWS CATEGORY LIST - START-----------------------------------------> let globalArr = [] function dynamicPagination(totalPage, size) { $('#pagination_category').twbsPagination({ totalPages: totalPage, visiblePages: 5, prev: 'Prev', first: 'First', last: 'Last', startPage: 1, onPageClick: function (event, page) { if ($('#searchCategory').val() === "") { getAllNewsCategoryByPage(page, size); } else { searchNewsCategory(page, size, $('#searchCategory').val()) } //$('#firstLast1-content').text('You are on Page ' + page); $('.pagination').find('li').addClass('page-item'); $('.pagination').find('a').addClass('page-link'); } }); } function getAllNewsCategoryByPage(page, showNumber) { $.ajax({ url: "./news/categoryList/" + showNumber + "/" + (page - 1), type: "get", dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { //console.log(data) createRowData(data) dynamicPagination(data.totalPage, showNumber) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the news category list operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } function createRowData(data) { console.log(data) let html = `` for (let i = 0; i < data.result.length; i++) { globalArr = data.result const itm = data.result[i] console.log(globalArr) html += `<tr> <td>${itm.no}</td> <td>${itm.name}</td> <td>${itm.detail}</td> <td>${itm.status}</td> <td> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown"> <i class="fas fa-ellipsis-v"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="javascript:newsCategoryUpdate(${i});"> <i class="mr-50 fas fa-pen"></i> <span>Edit</span> </a> <a class="dropdown-item" href="javascript:newsCategoryDelete(${itm.categoryId});"> <i class="mr-50 far fa-trash-alt"></i> <span>Delete</span> </a> </div> </div> </td> </tr>` } $("#categoryTable").html(html) } $('#showCategorySize').change(function () { if($('#searchCategory').val() === ""){ $('#pagination_category').twbsPagination('destroy'); getAllNewsCategoryByPage(1, parseInt($(this).val())); }else{ searchNewsCategory( page, $('#showCategorySize').val(),$('#searchCategory').val()); } }); getAllNewsCategoryByPage(1, 10); // <------------------------------------------------NEWS CATEGORY LIST - END-------------------------------------------> // <------------------------------------------------NEWS CATEGORY SEARCH - START---------------------------------------> function searchNewsCategory(page, showPageSize, searchData) { $.ajax({ url: './news/searchNewsCategory/' + searchData + "/" + (page - 1) + "/" + showPageSize, type: 'get', dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { //console.log("Data result " + JSON.stringify(data)) createRowData(data) dynamicPagination(data.totalPage, showPageSize) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } $('#searchCategory').keyup(function (event) { console.log("harf girildi") event.preventDefault(); const searchData = $(this).val() if (searchData !== "") { $("#categoryTable > tr").remove() searchNewsCategory(1, $("#showCategorySize").val(), searchData) } else { $('#pagination_category').twbsPagination('destroy'); getAllNewsCategoryByPage(1, $("#showCategorySize").val()); } }) // <------------------------------------------------NEWS CATEGORY SEARCH - END-----------------------------------------> // ================================================CATEGORY ACTIONS - END=============================================== // ================================================NEWS ACTIONS - START================================================= // <------------------------------------------------NEWS CATEGORY DATA - START----------------------------------------> function allNewsCategoryList() { $.ajax({ url: './news/categoryList', type: 'get', dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { category = data.result; //console.log("News Categories : ", categories) newsCategoryOption(category) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } allNewsCategoryList() function newsCategoryOption(data) { data.forEach(item => { $('#newsCategories').append('<option value="' + item.id + '">' + item.name + '</option>'); }) } // <------------------------------------------------NEWS CATEGORY DATA - END------------------------------------------> // <------------------------------------------------NEWS ADD - START---------------------------------------------------> let select_id_news = 0; $('#newsAdd_modalForm').submit((event) => { event.preventDefault() const title = $('#title').val() const summary = $('#summary').val() const description = $('#description').val() const status = $('#status').val() const newsCategory = $('#newsCategories').val() const obj = { no: noGenerator(), title: title, summary: summary, description: description, status: status == 1 ? "Active" : "Passive", newsCategory: { id: newsCategory }, date: fncDate() } if (select_id_news != 0) { // update obj["id"] = select_id_news; } console.log(obj) $.ajax({ url: './news/add', type: 'POST', data: JSON.stringify(obj), dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (data.status == true && data.result != null) { Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); setTimeout(function () { $("#newsAdd_modal").modal('hide'); }, 2000); resetFormNews() } else if (data.status == true && data.result == null) { Swal.fire({ title: "Warning!", text: "Returned Data is Empty!", icon: "warning", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); resetFormNews() } else { if (!jQuery.isEmptyObject(data.errors)) { console.log("burada") console.log(data.errors) Swal.fire({ title: 'Error!', text: data.errors[0].fieldMessage, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } else { console.log("burada"); Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } } console.log(data) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) }) // <------------------------------------------------NEWS ADD - END-----------------------------------------------------> // <------------------------------------------------NEWS LIST - START--------------------------------------------------> let globalNewsArr = [] function dynamicPaginationNews(totalPage, size) { $('#pagination_news').twbsPagination({ totalPages: totalPage, visiblePages: 5, prev: 'Prev', first: 'First', last: 'Last', startPage: 1, onPageClick: function (event, page) { if ($('#searchNewsData').val() === "") { getAllNewsByPage(page, size); } else { searchNews(page, size, $('#searchNewsData').val()) } $('.pagination').find('li').addClass('page-item'); $('.pagination').find('a').addClass('page-link'); } }); } function getAllNewsByPage(page, showNumber) { $.ajax({ url: "./news/newslist/" + showNumber + "/" + (page - 1), type: "get", dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { createRowDataNews(data) dynamicPaginationNews(data.totalPage, showNumber) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the news list operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } function createRowDataNews(data) { let html = ``; for (let i = 0; i < data.result.length; i++) { globalNewsArr = data.result const itm = data.result[i] console.log(globalNewsArr) html += `<tr> <td>${itm.no}</td> <td>${itm.title}</td> <td>${itm.categoryName}</td> <td>${itm.status}</td> <td>${itm.summary}</td> <td>${itm.date}</td> <td> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown"> <i class="fas fa-ellipsis-v"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="javascript:newsAddImages(${i});"> <i class="mr-50 far fa-images"></i> <span>Add Images</span> </a> <a class="dropdown-item" type="button" href="javascript:newsDetail(${i});" > <i class="mr-50 fas fa-info-circle"></i> <span>Detail</span> </a> <a class="dropdown-item" href="javascript:newsUpdate(${i});"> <i class="mr-50 fas fa-pen"></i> <span>Edit</span> </a> <a class="dropdown-item" href="javascript:newsDelete(${itm.id});"> <i class="mr-50 far fa-trash-alt"></i> <span>Delete</span> </a> </div> </div> </td> </tr>` } $("#newsTable").html(html) } $('#showNewsTableRow').change(function () { if($('#searchNewsData').val() === ""){ $('#pagination_news').twbsPagination('destroy'); getAllNewsByPage(1, parseInt($(this).val())); }else{ searchNews( page, $('#showNewsTableRow').val(),$('#searchNewsData').val()); } }); getAllNewsByPage(1, 10); // <------------------------------------------------NEWS LIST - END----------------------------------------------------> // <------------------------------------------------NEWS DELETE - START------------------------------------------------> function newsDelete(id) { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './news/delete/' + id, type: 'DELETE', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (id != null) { Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); resetFormNews() } else { Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } // <------------------------------------------------NEWS DELETE - END--------------------------------------------------> function newsAddImages(i) { $('#newsImage').modal('toggle'); const itm = globalNewsArr[i] $("#modalTitle").text(itm.title + " - " + itm.summary) $.ajax({ url: './news/chosenId/' + itm.id, type: 'get', dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { console.log(data) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the chosen id operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } // <------------------------------------------------NEWS DETAIL - START------------------------------------------------> var mySwiper3 = new Swiper('.swiper-progress', { pagination: { el: '.swiper-pagination', type: 'progressbar' }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' } }); // navigation var mySwiper1 = new Swiper('.swiper-navigations', { navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' } }); function newsDetail(i) { $('#newsDetail').modal('toggle') $('#imagesChose').empty() const itm = globalNewsArr[i] let html = `` var fileName $.ajax({ url: './news/chosenId/' + itm.id, type: 'get', dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { console.log(data) $.ajax({ url: "./news/detail/" + itm.id, type: "get", dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { console.log(data.result) for (let j = 0; j < data.result.fileName.length; j++) { fileName = data.result.fileName[j] html += `<div class="swiper-slide"> <!-- <img class="img-fluid" src="/uploadImages/_news/${itm.id}/${fileName}" alt="banner"/>--> <img src="/news/newsDetail/get_image/id=${itm.id}name=${fileName}" class="img-fluid" alt="banner" /> </div>` $('#imagesChose').append('<option value="' + fileName + '">Image - ' + j + '</option>'); } $("#imageSlide").html(html) $("#title").text(itm.no + " - " + itm.name + " " + itm.description) $("#titleDetail").text(itm.title) $("#dateDetail").text(itm.date) $("#statusDetail").text(itm.status) $("#descriptionDetails").text(data.result.description) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the news list operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the chosen id operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } // <------------------------------------------------NEWS DETAIL - END--------------------------------------------------> // <------------------------------------------------NEWS SEARCH - START------------------------------------------------> function searchNews(page, showPageSize, searchData) { $.ajax({ url: './news/search/' + searchData + "/" + (page - 1) + "/" + showPageSize, type: 'get', dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { createRowDataNews(data) dynamicPaginationNews(data.totalPage, showPageSize) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } $('#searchNewsData').keyup(function (event) { console.log("değişti") event.preventDefault(); const searchDataNews = $(this).val() if (searchDataNews !== "") { $("#newsTable > tr").remove() $('#pagination_news').twbsPagination('destroy'); searchNews(1, $("#showNewsTableRow").val(), searchDataNews) } else { $('#pagination_news').twbsPagination('destroy'); getAllNewsByPage(1, $("#showNewsTableRow").val()); } }) // <------------------------------------------------NEWS SEARCH - END--------------------------------------------------> // <------------------------------------------------NEWS UPDATE - START------------------------------------------------> function newsUpdate(i) { $('#newsAdd_modal').modal('toggle'); const itm = globalNewsArr[i] select_id_news = itm.id console.log("select_id : " + select_id_news) $.ajax({ url: "./news/detail/" + itm.id, type: "get", dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { console.log(data.result) // for (let i = 0; i < data.result.newsCategory.length; i++) { // $('#newsCategories').val(data.result.newsCategory[i].id).trigger('change') // } // allNewsCategoryList() $('#title').val(data.result.title) $('#summary').val(data.result.summary) $('#description').val(data.result.description) $("#status").val(data.result.status == "Active" ? 1 : 2) $('#newsCategories').val(data.result.newsCategory.id).trigger('change'); }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the news list operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } // <------------------------------------------------NEWS UPDATE - END--------------------------------------------------> // <------------------------------------------------NEWS IMAGE DELETE - START-------------------------------------------> function deleteImage() { const chosenImages = $("#imagesChose").val() console.log(chosenImages) Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './news/chosenImages/delete/' + chosenImages, type: 'DELETE', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (chosenImages.length > 0) { Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); $('#imagesChose').empty() setTimeout(function () { $("#newsDetail").modal('hide'); }, 2000); } else { Swal.fire({ icon: 'warning', title: "Warning", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } // <------------------------------------------------NEWS IMAGE DELETE - END--------------------------------------------> // ================================================NEWS ACTIONS - END=================================================== <file_sep>package companyAll_MVC.controllers; import com.fasterxml.jackson.databind.ObjectMapper; import companyAll_MVC.model.RedisCountry; import companyAll_MVC.properties.Country; import companyAll_MVC.properties.CountryHolder; import companyAll_MVC.repositories._redis.RedisCountryRepository; import companyAll_MVC.utils.Check; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException; import java.io.InputStream; import java.util.*; @Controller @RequestMapping("/redis") public class RedisCountryController { final RedisCountryRepository redisCountryRepository; public RedisCountryController(RedisCountryRepository redisCountryRepository) { this.redisCountryRepository = redisCountryRepository; } @GetMapping("") public String set() throws IOException { ObjectMapper mapper = new ObjectMapper(); List<RedisCountry> redisCountryList = new ArrayList<>(); InputStream is = CountryHolder.class.getResourceAsStream("/countries.json"); CountryHolder countryHolder = mapper.readValue(is, CountryHolder.class); for(Country country : countryHolder.getCountries()){ RedisCountry redisCountry = new RedisCountry(); redisCountry.setName(country.getCountry()); redisCountry.setCities(country.getStates()); redisCountryList.add(redisCountry); } redisCountryRepository.saveAll(redisCountryList); return "dashboard"; } @GetMapping("/get_countries") @ResponseBody public Map<Check, Object> getCountries() { Map<Check, Object> resultMap = new LinkedHashMap<>(); Iterable<RedisCountry> redisCountries = redisCountryRepository.findAll(); resultMap.put(Check.status, true); resultMap.put(Check.result, redisCountries); return resultMap; } @GetMapping("/get_cities/country_id={id}") @ResponseBody public Map<Check, Object> getCities(@PathVariable String id) { Map<Check, Object> resultMap = new LinkedHashMap<>(); Optional<RedisCountry> redisCountryOptional = redisCountryRepository.findById(id); if(redisCountryOptional.isPresent()){ resultMap.put(Check.status, true); resultMap.put(Check.result, redisCountryOptional.get().getCities()); }else{ resultMap.put(Check.status, false); resultMap.put(Check.message, "Country not found!"); } return resultMap; } } <file_sep>package companyAll_MVC.dto; import companyAll_MVC.entities.Gallery; import companyAll_MVC.entities.GalleryCategory; import companyAll_MVC.entities.News; import companyAll_MVC.entities.NewsCategory; import companyAll_MVC.repositories._elastic.ElasticNewsCategoryRepository; import companyAll_MVC.repositories._jpa.NewsCategoryRepository; import companyAll_MVC.repositories._jpa.NewsRepository; import companyAll_MVC.utils.Check; import org.springframework.stereotype.Service; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Service public class NewsDto { final ElasticNewsCategoryRepository elasticNewsCategoryRepository; final NewsCategoryRepository newsCategoryRepository; final NewsRepository newsRepository; public NewsDto(ElasticNewsCategoryRepository elasticNewsCategoryRepository, NewsCategoryRepository newsCategoryRepository, NewsRepository newsRepository) { this.elasticNewsCategoryRepository = elasticNewsCategoryRepository; this.newsCategoryRepository = newsCategoryRepository; this.newsRepository = newsRepository; } // news-category list public Map<Check, Object> list() { Map<Check, Object> hm = new LinkedHashMap<>(); hm.put(Check.status, true); List<NewsCategory> ls = newsCategoryRepository.findAll(); hm.put(Check.result, ls); return hm; } // newsListByCategoryId public Map<Check, Object> listByCategoryId(Integer id) { Map<Check, Object> hm = new LinkedHashMap<>(); hm.put(Check.status, true); List<News> ls = newsRepository.findByNewsCategory_IdEquals(id); hm.put(Check.result, ls); return hm; } } <file_sep>function save(passwordObj) { $.ajax({ url: '/newPassword/setPassword', type: 'POST', data: JSON.stringify(passwordObj), dataType: 'JSON', contentType: 'application/json; charset=utf-8', success: function (data) { if (data.status === true) { Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }).then(function (result) { if (result.value) { Swal.fire({ title: 'Redirecting...!', text: "You will be redirecting to the login page in 3 seconds.", icon: "success", buttonsStyling: false }) setTimeout(function () { window.location.href = '/login'; }, 3000); } }); } else { Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err); } }) } $('#new_password_form').submit((event) => { event.preventDefault(); const passwordObj = { oldPassword: "", newPassword: $('#<PASSWORD>').val(), reNewPassword: $('#<PASSWORD>').val() } console.log(passwordObj); save(passwordObj); }); <file_sep>package companyAll_MVC.repositories._jpa; import companyAll_MVC.entities.ReferenceHolder; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface ReferenceHolderRepository extends JpaRepository<ReferenceHolder, Integer> { Optional<ReferenceHolder> findByReference(String reference); boolean existsByUid(Integer uid); Optional<ReferenceHolder> findByUid(Integer uid); } <file_sep>package companyAll_MVC.controllers; import companyAll_MVC.entities.User; import companyAll_MVC.properties.ChangePassword; import companyAll_MVC.properties.Company; import companyAll_MVC.properties.UserInfo; import companyAll_MVC.repositories._jpa.UserRepository; import companyAll_MVC.services.UserService; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Util; import org.apache.commons.io.FileUtils; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.jws.soap.SOAPBinding; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.File; import java.io.IOException; import java.util.Base64; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; @Controller @RequestMapping("/settings") public class SettingsController { final UserRepository userRepository; final UserService userService; public SettingsController(UserRepository userRepository, UserService userService) { this.userRepository = userRepository; this.userService = userService; } @GetMapping("") public String settings(Model model){ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String email = auth.getName(); Optional<User> userOptional = userRepository.findByEmailIgnoreCase(email); if (userOptional.isPresent()){ User user = userOptional.get(); model.addAttribute("user",user); }else { String error = "User is not found!"; Util.logger(error,User.class); System.err.println(error); } return "settings"; } //Section - 1 (Company) @ResponseBody @PostMapping("/updateCompany") public Map<Check,Object> updateCompany(@RequestBody @Valid Company company, BindingResult bindingResult){ Map<Check,Object> map = new LinkedHashMap<>(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String email = auth.getName(); if(!bindingResult.hasErrors()){ try { Optional<User> userOptional = userRepository.findByEmailIgnoreCase(email); if (userOptional.isPresent()){ User us = userOptional.get(); us.setCompanyName(company.getCompanyName()); us.setCompanySector(company.getCompanySector()); us.setCompanyPhone(company.getCompanyPhone()); us.setCompanyAddress(company.getCompanyAddress()); User updatedUser = userRepository.saveAndFlush(us); map.put(Check.status,true); map.put(Check.message,"Company Information Update Successful!"); map.put(Check.result,updatedUser); }else{ String error = "User is not found!"; map.put(Check.status,false); map.put(Check.message,error); Util.logger(error,User.class); System.err.println(error); } } catch (Exception e) { String error = "An error occurred during the operation!"; map.put(Check.status,false); map.put(Check.message,error); Util.logger(error,User.class); System.err.println(e); } }else{ map.put(Check.status,false); map.put(Check.errors, Util.errors(bindingResult)); } return map; } //Section - 2 (Change Password) @ResponseBody @PostMapping("/changePassword") public Map<Check,Object> changePassword(@RequestBody ChangePassword changePassword){ Map<Check,Object> map = new LinkedHashMap<>(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String email = auth.getName(); Optional<User> userOptional = userRepository.findByEmailIgnoreCase(email); if (userOptional.isPresent()){ if ( changePassword.getOldPassword().equals("") || changePassword.getNewPassword().equals("") || changePassword.getReNewPassword().equals("")){ map.put(Check.status,false); map.put(Check.message,"Please fill in the specified!"); }else { if(changePassword.getNewPassword().equals(changePassword.getReNewPassword())){ User us = userOptional.get(); us.setPassword(userService.encoder().encode(changePassword.getNewPassword())); User user = userRepository.saveAndFlush(us); map.put(Check.status,true); map.put(Check.message,"Password changed successfully!"); map.put(Check.result,user); }else { map.put(Check.status,false); map.put(Check.message,"New password and its repetition don't match!"); } } }else{ String error = "User is not found!"; map.put(Check.status,false); map.put(Check.message,error); Util.logger(error,User.class); System.err.println(error); } return map; } //Section - 3 (User) @ResponseBody @PostMapping("/userInfo") public Map<Check,Object> userInfo(@RequestBody @Valid UserInfo userInfo, BindingResult bindingResult){ Map<Check,Object> map = new LinkedHashMap<>(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String email = auth.getName(); if(!bindingResult.hasErrors()){ try { Optional<User> userOptional = userRepository.findByEmailIgnoreCase(email); if (userOptional.isPresent()){ User us = userOptional.get(); us.setName(userInfo.getName()); us.setSurname(userInfo.getSurname()); us.setEmail(userInfo.getEmail()); us.setBirthday(userInfo.getBirthday()); us.setBio(userInfo.getBio()); User updatedUser = userRepository.saveAndFlush(us); map.put(Check.status,true); map.put(Check.message,"User Information Update Successful!"); map.put(Check.result,updatedUser); }else{ String error = "User is not found!"; map.put(Check.status,false); map.put(Check.message,error); Util.logger(error,User.class); System.err.println(error); } } catch (Exception e) { String error = "An error occurred during the operation!"; map.put(Check.status,false); map.put(Check.message,error); Util.logger(error,User.class); System.err.println(e); } }else{ map.put(Check.status,false); map.put(Check.errors, Util.errors(bindingResult)); } return map; } @PostMapping("/profile_image_upload") @ResponseBody public Map<Check, Object> uploadImage(@RequestParam("image") MultipartFile file) { Map<Check, Object> resultMap = new LinkedHashMap<>(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Optional<User> userOptional = userRepository.findByEmailIgnoreCase(auth.getName()); if(userOptional.isPresent()){ User user = userOptional.get(); File folderProfile = new File(Util.UPLOAD_DIR_PROFILE_IMAGES + user.getId()); if(folderProfile.exists()){ File fileOld = new File(Util.UPLOAD_DIR_PROFILE_IMAGES +user.getId() + "/" + user.getProfileImage()); if(fileOld.delete()){ resultMap = Util.imageUpload(file, Util.UPLOAD_DIR_PROFILE_IMAGES + user.getId() + "/"); }else{ resultMap.put(Check.status, false); resultMap.put(Check.message, "Old image couldn't be deleted!"); } }else{ boolean status = folderProfile.mkdir(); resultMap = Util.imageUpload(file, Util.UPLOAD_DIR_PROFILE_IMAGES + user.getId() + "/"); } if((Boolean) resultMap.get(Check.status)){ try{ user.setProfileImage(resultMap.get(Check.result).toString()); userRepository.saveAndFlush(user); resultMap.put(Check.status, true); resultMap.put(Check.message, "Profile Image successfully saved!"); }catch (Exception e){ e.printStackTrace(); } } } return resultMap; } @GetMapping("/get_profile_image") @ResponseBody public Map<Check, Object> getImage() throws IOException { Map<Check, Object> resultMap = new LinkedHashMap<>(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Optional<User> userOptional = userRepository.findByEmailIgnoreCase(auth.getName()); if(userOptional.isPresent()){ User user = userOptional.get(); String path = ""; String profile_image = user.getProfileImage(); if(!profile_image.equals("")){ path = Util.UPLOAD_DIR_PROFILE_IMAGES + user.getId() + "/" + profile_image; }else{ path = Util.UPLOAD_DIR_PROFILE_IMAGES + "default_profile_image.jpg"; } byte[] fileContent = FileUtils.readFileToByteArray(new File(path)); String encodedString = Base64.getEncoder().encodeToString(fileContent); if(encodedString != null){ resultMap.put(Check.status, true); resultMap.put(Check.result, encodedString); }else{ resultMap.put(Check.status, false); } } return resultMap; } } <file_sep>package companyAll_MVC.repositories._elastic; import companyAll_MVC.documents.ElasticLikes; import companyAll_MVC.documents.ElasticLikesProduct; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface ElasticLikeProductRepository extends ElasticsearchRepository<ElasticLikesProduct,String> { @Query("{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}}") Page<ElasticLikesProduct> findByOrderByIdAsc(Pageable pageable); @Query("{\"bool\":{\"must\":[],\"must_not\":[],\"should\":[{\"match\":{\"name\":\"?0\"}},{\"match\":{\"totalRating\":\"?0\"}},{\"prefix\":{\"name\":\"?0\"}},{\"prefix\":{\"totalRating\":\"?0\"}}]}}") Page<ElasticLikesProduct> findBySearchDataProductLike(String data, Pageable pageable); } <file_sep>function mostPopularProduct(){ $.ajax({ url:"./mostPopularProducts", type: "get", dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data){ if(data.result.length > 0){ createCard(data.result) } }, error: function (err){ Swal.fire({ title: "Error!", text: "An error occurred during the most popular five product listing operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } mostPopularProduct(); function createCard(data){ let html = `` for (let i = 0; i <data.length ; i++) { const itm = data[i] let price = priceFormatter(itm.price); html += `<div class="swiper-slide"> <a href="/productDetail/${itm.id}"> <div class="item-heading"> <h5 class="text-truncate mb-0">${itm.name} ${itm.description}</h5> <small class="text-body">by ${itm.name}</small> </div> <div class="img-container w-50 mx-auto py-75"> <img src="get_image/id=${itm.id}name=${itm.fileName[0]}" class="img-fluid" alt="image" /> </div> <div class="item-meta"> <div class="row"> <div class="read-only-ratings-${itm.id} mr-4" data-rateyo-read-only="true"></div> <div></div> <p class="card-text text-primary mb-0 ml-5">${price} TL</p> </div> </div> </a> </div> </div>` } $("#mostPopularFiveProduct").html(html); // Ratings To CustomerByProduct data.forEach(itm => { var isRtl = $('html').attr("data-textdirection") === 'rtl', readOnlyRatings = $(`.read-only-ratings-${itm.id}`) if (readOnlyRatings.length) { readOnlyRatings.rateYo({ rating: itm.totalLike, rtl: isRtl, starWidth: "15px" }); } }) } function priceFormatter(price){ var formattedPrice = (price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,') return formattedPrice }<file_sep>package companyAll_MVC.repositories._jpa; import companyAll_MVC.entities.Indent; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface IndentRepository extends JpaRepository<Indent,Integer> { List<Indent> findByCustomer_IdEquals(Integer id); List<Indent> findByProduct_IdEquals(Integer id); } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; @Data @Entity @ApiModel(value = "Announcment Model", description = "Announcment Model Variable Definitions") public class Announcement extends AuditEntity<String>{ @Id @ApiModelProperty(value = "Announcment Id",required = true) @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(unique = true) @NotNull(message = "Invalid announcement no! (null)") @NotEmpty(message = "Invalid announcement no! (empty)") @ApiModelProperty(value = "Announcment ten digits no",required = true) @Pattern(regexp="(^$|[0-9]{10})", message = "Invalid announcement no!") private String no; @Column(unique = true) @Size(max = 50, message = "Announcement title's size can be 50 at max!") @NotNull(message = "Invalid announcement title! (null)") @NotEmpty(message = "Invalid announcement title! (empty)") @ApiModelProperty(value = "Announcment title",required = true) private String title; @ApiModelProperty(value = "Announcment save date",required = true) private String date; @NotNull(message = "Invalid announcement status! (null)") @NotEmpty(message = "Invalid announcement status! (empty)") @ApiModelProperty(value = "Announcment status (Active or Passive)",required = true) @Pattern(regexp = "Active|Passive", message = "Announcement status must be either 'Active' or 'Passive'") private String status; @Size(max = 500, message = "Announcement detail's size can be 500 at max!") @NotNull(message = "Invalid announcement detail! (null)") @NotEmpty(message = "Invalid announcement detail! (empty)") @ApiModelProperty(value = "Announcment detail",required = true) private String detail; } <file_sep>package companyAll_MVC.repositories._redis; import companyAll_MVC.model.RedisCountry; import org.springframework.data.repository.CrudRepository; public interface RedisCountryRepository extends CrudRepository<RedisCountry, String> { } <file_sep>package companyAll_MVC.documents; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; @Document(indexName = "customers") @Data public class ElasticCustomer { @Id private String id; @Field(type = FieldType.Auto) private Integer cid; @Field(type = FieldType.Text) private String no; @Field(type = FieldType.Text) private String name; @Field(type = FieldType.Text) private String surname; @Field(type = FieldType.Text) private String phone1; @Field(type = FieldType.Text) private String mail; @Field(type = FieldType.Text) private String taxno; @Field(type = FieldType.Text) private String country; @Field(type = FieldType.Text) private String city; @Field(type = FieldType.Text) private String status; } <file_sep>package companyAll_MVC.documents; import lombok.Data; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import javax.persistence.Id; @Data @Document(indexName = "likes") public class ElasticLikes { @Id private String id; private Integer likesId; @Field(type = FieldType.Text) private String customerName; @Field(type = FieldType.Text) private String productName; @Field(type = FieldType.Text) private Integer productRating; @Field(type = FieldType.Text) private String productDetail; @Field(type = FieldType.Text) private String productNo; } <file_sep>package companyAll_MVC.restcontroller; import companyAll_MVC.dto.CustomerDto; import companyAll_MVC.entities.Address; import companyAll_MVC.entities.Customer; import companyAll_MVC.utils.Check; import io.swagger.annotations.Api; import io.swagger.annotations.Authorization; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Map; @RestController @RequestMapping("/api/customer") @Api(value = "CustomerRestController",authorizations = {@Authorization(value = "basicAuth")}) public class CustomerRestController { final CustomerDto customerDto; public CustomerRestController(CustomerDto customerDto) { this.customerDto = customerDto; } @GetMapping("/get/id={id}") @ResponseBody public Map<Check, Object> get(@PathVariable Integer id) { return customerDto.get(id); } @PostMapping("/add") @ResponseBody public Map<Check, Object> add(@RequestBody @Valid Customer customer, BindingResult bindingResult) { return customerDto.add(customer, bindingResult); } @PostMapping("/update") @ResponseBody public Map<Check, Object> update(@RequestBody @Valid Customer customer, BindingResult bindingResult) { return customerDto.update(customer, bindingResult); } @DeleteMapping("/delete/id={id}") @ResponseBody public Map<Check, Object> delete(@PathVariable Integer id) { return customerDto.delete(id); } @GetMapping("/addresses/cid={cid}") @ResponseBody public Map<Check, Object> addresses(@PathVariable Integer cid) { return customerDto.addresses(cid); } @PostMapping("/address/update") @ResponseBody public Map<Check, Object> updateAddress(@RequestBody @Valid Address address, BindingResult bindingResult) { return customerDto.updateAddress(address, bindingResult); } @DeleteMapping("/address/delete/cid={cid}aid={aid}") @ResponseBody public Map<Check, Object> deleteAddress(@PathVariable Integer cid, @PathVariable Integer aid) { return customerDto.deleteAddress(cid, aid); } } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @Data @Entity @ApiModel(value = "Country Model", description = "Country Model Variable Definitions") public class Country { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(value = "Country Id",required = true) private Integer id; @Column(unique = true) @NotNull(message = "Invalid country name! (null)") @NotEmpty(message = "Invalid country name! (empty)") @ApiModelProperty(value = "Country name",required = true) private String name; } <file_sep>package companyAll_MVC.controllers; import companyAll_MVC.documents.ElasticNews; import companyAll_MVC.entities.News; import companyAll_MVC.entities.NewsCategory; import companyAll_MVC.repositories._elastic.ElasticNewsRepository; import companyAll_MVC.repositories._jpa.NewsCategoryRepository; import companyAll_MVC.repositories._jpa.NewsRepository; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Util; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/newsList") public class NewsListController { final NewsCategoryRepository newsCategoryRepository; final NewsRepository newsRepository; final ElasticNewsRepository elasticNewsRepository; public NewsListController(NewsCategoryRepository newsCategoryRepository, NewsRepository newsRepository,ElasticNewsRepository elasticNewsRepository) { this.newsCategoryRepository = newsCategoryRepository; this.newsRepository = newsRepository; this.elasticNewsRepository = elasticNewsRepository; } @GetMapping("") public String newsList() { return "newsList"; } //------------------------------------ News Category List - Start ------------------------------------// @ResponseBody @GetMapping("/categories") public Map<Check, Object> categories() { Map<Check, Object> map = new LinkedHashMap<>(); try { map.put(Check.status, true); map.put(Check.message, "News category list operation succesful!"); map.put(Check.result, newsCategoryRepository.findAll()); } catch (Exception e) { String error = "An error occurred during the operation!"; Util.logger(error, NewsCategory.class); map.put(Check.status, false); map.put(Check.message, error); System.err.println(e); } return map; } //------------------------------------ News Category List - End --------------------------------------// //------------------------------------ News List by Category Id - Start ------------------------------------// @ResponseBody @GetMapping("/listByCategoryId/{stId}/{stShowNumber}/{stPageNo}") public Map<Check, Object> newsListByCategoryId(@PathVariable String stId, @PathVariable String stShowNumber, @PathVariable String stPageNo) { Map<Check, Object> map = new LinkedHashMap<>(); try { int categoryId = Integer.parseInt(stId); int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo, showNumber); Page<News> newsPage = newsRepository.findByNewsCategory_Id(categoryId, pageable); map.put(Check.status, true); map.put(Check.message, "News list operation succesful!"); map.put(Check.totalPage, newsPage.getTotalPages()); map.put(Check.result, newsPage.getContent()); } catch (Exception e) { String error = "An error occurred during the operation!"; Util.logger(error, News.class); map.put(Check.status, false); map.put(Check.message, error); System.err.println(e); } return map; } //------------------------------------ News List by Category Id List - End --------------------------------------// //------------------------------------ News List from category Id with Elasticsearch - Start ----------------------------------------// @ResponseBody @GetMapping("/listByCategoryIdElasticsearch/{stId}/{stShowNumber}/{stPageNo}") public Map<Check,Object> newsListByCategoryIdElasticsearch(@PathVariable String stId,@PathVariable String stShowNumber,@PathVariable String stPageNo){ Map<Check,Object> map = new LinkedHashMap<>(); try { int categoryId = Integer.parseInt(stId); int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo,showNumber); Page<ElasticNews> elasticNewsPage = elasticNewsRepository.findByNewsCategoryIdEquals(categoryId,pageable); System.out.println("elasticNewsPage: " + elasticNewsPage); map.put(Check.status,true); map.put(Check.message,"News list operation succesful!"); map.put(Check.totalPage,elasticNewsPage.getTotalPages()); map.put(Check.result,elasticNewsPage.getContent()); } catch (Exception e) { String error = "An error occurred during the operation!"; Util.logger(error, News.class); map.put(Check.status,false); map.put(Check.message,error); System.err.println(e); } return map; } //------------------------------------ News List from category Id with Elasticsearch - End ------------------------------------------// //------------------------------------ Elasticsearch for News - Start ------------------------------------// @ResponseBody @GetMapping("/search/{data}/{stPageNo}/{stShowNumber}") public Map<Check,Object> searchNews(@PathVariable String data,@PathVariable String stPageNo,@PathVariable String stShowNumber){ Map<Check,Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo,showNumber); Page<ElasticNews> searchPage = elasticNewsRepository.findBySearchData(data,pageable); List<ElasticNews> elasticNewsList = searchPage.getContent(); int totalData = elasticNewsList.size(); //for total data in table if(totalData > 0 ){ map.put(Check.status,true); map.put(Check.totalPage,searchPage.getTotalPages()); map.put(Check.message,"Search operation success!"); map.put(Check.result,elasticNewsList); }else{ map.put(Check.status,false); map.put(Check.message,"Could not find a result for your search!"); } } catch (NumberFormatException e) { map.put(Check.status,false); String error = "An error occurred during the search operation!"; System.err.println(e); Util.logger(error, News.class); map.put(Check.message,error); } return map; } //------------------------------------ Elasticsearch for News - End --------------------------------------// } <file_sep>package companyAll_MVC.dto; import companyAll_MVC.documents.ElasticLikes; import companyAll_MVC.documents.ElasticLikesProduct; import companyAll_MVC.documents.ElasticProduct; import companyAll_MVC.entities.*; import companyAll_MVC.repositories._elastic.ElasticLikeProductRepository; import companyAll_MVC.repositories._elastic.ElasticLikesRepository; import companyAll_MVC.repositories._elastic.ElasticProductRepository; import companyAll_MVC.repositories._jpa.IndentRepository; import companyAll_MVC.repositories._jpa.LikesProductRepository; import companyAll_MVC.repositories._jpa.LikesRepository; import companyAll_MVC.repositories._jpa.ProductRepository; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Util; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Service public class LikesDto { final LikesRepository likesRepository; final IndentRepository indentRepository; final LikesProductRepository likesProductRepository; final ProductRepository productRepository; final ElasticLikesRepository elasticLikesRepository; final ElasticProductRepository elasticProductRepository; final ElasticLikeProductRepository elasticLikeProductRepository; public LikesDto(LikesRepository likesRepository, IndentRepository indentRepository, LikesProductRepository likesProductRepository, ProductRepository productRepository, ElasticLikesRepository elasticLikesRepository, ElasticProductRepository elasticProductRepository, ElasticLikeProductRepository elasticLikeProductRepository) { this.likesRepository = likesRepository; this.indentRepository = indentRepository; this.likesProductRepository = likesProductRepository; this.productRepository = productRepository; this.elasticLikesRepository = elasticLikesRepository; this.elasticProductRepository = elasticProductRepository; this.elasticLikeProductRepository = elasticLikeProductRepository; } public Map<Check,Object> list(Integer id) { Map<Check,Object> hm = new LinkedHashMap<>(); hm.put(Check.status,true); List<Likes> ls = likesRepository.findByIndent_IdEquals(id); hm.put(Check.result,ls); return hm; } public Map<Check,Object> listCustomerById(Integer id) { Map<Check,Object> hm1 = new LinkedHashMap<>(); hm1.put(Check.status,true); // Indent indent = new Indent(); // Indent indent1 = indentRepository.findByCustomer_IdEquals(id); // List<Indent> ls1= indentRepository.findByCustomer_IdEquals(id); // List<Likes> ls = new ArrayList<>(); List<Likes> ls = likesRepository.findByIndent_Customer_IdEquals(id); hm1.put(Check.result,ls); return hm1; } // Like Add and Rating Point Actions public Map<Check, Object> add(Likes likes) { Map<Check, Object> hm = new LinkedHashMap<>(); try { Indent indent = indentRepository.findById(likes.getIndent().getId()).get(); Product product = productRepository.findById(indent.getProduct().getId()).get(); if (!indent.isOrderStatus()){ // saving data in sql and elasticsearch Likes likes1 = likesRepository.save(likes); ElasticLikes elasticLikes = new ElasticLikes(); elasticLikes.setId(Integer.toString(likes1.getId())); elasticLikes.setLikesId(likes1.getId()); elasticLikes.setCustomerName(indent.getCustomer().getName()); elasticLikes.setProductName(indent.getProduct().getName()); elasticLikes.setProductRating(likes1.getRating()); elasticLikes.setProductDetail(indent.getProduct().getDetails()); elasticLikes.setProductNo(indent.getProduct().getNo()); System.out.println("elasticLikes: " + elasticLikes); elasticLikesRepository.save(elasticLikes); hm.put(Check.status, true); hm.put(Check.message, "add likes successful"); hm.put(Check.result, likes1); LikesProduct likesProduct = new LikesProduct(); likesProduct.setProduct(indent.getProduct()); if (likesProduct.getTotalLike() == null) { likesProduct.setTotalLike(likes.getRating()); } else { likesProduct.setTotalLike(likesProduct.getTotalLike() + likes.getRating()); } likesProductRepository.save(likesProduct); List<LikesProduct> listAll = likesProductRepository.findByProduct_IdEquals(indent.getProduct().getId()); double total = 0; double avaregaRating = 0; double count = 0; for (LikesProduct item : listAll) { count++; total = total + item.getTotalLike(); avaregaRating = total / count; } System.out.println("total: " + total + "count: " + count + "avarageRating: " + avaregaRating); System.out.println("productObject: " + product); product.setTotalLike(avaregaRating); ElasticLikesProduct elasticLikesProduct= new ElasticLikesProduct(); elasticLikesProduct.setId(Integer.toString(product.getId())); elasticLikesProduct.setName(product.getName()); elasticLikesProduct.setTotalRating(Double.toString(product.getTotalLike())); elasticLikeProductRepository.save(elasticLikesProduct); productRepository.saveAndFlush(product); indent.setOrderStatus(true); indentRepository.saveAndFlush(indent); }else { hm.put(Check.status,false); hm.put(Check.message,"customer has already voted"); } //Elasticsearch total likes save - Start ElasticProduct elasticProduct = elasticProductRepository.findById(product.getId()).get(); elasticProduct.setTotalLike(product.getTotalLike()); elasticProductRepository.save(elasticProduct); //Elasticsearch total likes save - End } catch (Exception exception) { hm.put(Check.status, false); hm.put(Check.message, "Failed to add likes"); System.err.println(exception); } return hm; } //List of Likes With Customer Pagination public Map<Check, Object> listLikesWithPaginationCustomerId(String stShowNumber,String stPageNo){ Map<Check,Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); int showNumber = Integer.parseInt(stShowNumber); Pageable pageable = PageRequest.of(pageNo,showNumber); Page<ElasticLikes> likesPage = elasticLikesRepository.findByOrderByIdAsc(pageable); map.put(Check.status,true); map.put(Check.totalPage,likesPage.getTotalPages()); map.put(Check.message, "Likes listing on page " + (pageNo + 1) + " is successful"); map.put(Check.result,likesPage.getContent()); } catch (Exception e) { map.put(Check.status,false); String error = "An error occurred during the operation!"; System.err.println(e); Util.logger(error, Likes.class); map.put(Check.message,error); } return map; } } <file_sep>package companyAll_MVC.documents; import lombok.Data; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import javax.persistence.Id; @Data @Document(indexName = "newscategory") public class ElasticNewsCategory { @Id private String id; private Integer categoryId; @Field(type = FieldType.Text) private String no; @Field(type = FieldType.Text) private String name; @Field(type = FieldType.Text) private String detail; @Field(type = FieldType.Text) private String status; @Field(type = FieldType.Text) private String date; } <file_sep>package companyAll_MVC.utils; public enum Check { status, message, result, errors, totalPage // Total page number (for pagination process) } <file_sep>package companyAll_MVC.dto; import companyAll_MVC.entities.Gallery; import companyAll_MVC.entities.GalleryCategory; import companyAll_MVC.entities.Likes; import companyAll_MVC.repositories._jpa.GalleryCategoryRepository; import companyAll_MVC.repositories._jpa.GalleryRepository; import companyAll_MVC.utils.Check; import org.springframework.stereotype.Service; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Service public class GalleryDto { final GalleryRepository galleryRepository; final GalleryCategoryRepository galleryCategoryRepository; public GalleryDto(GalleryRepository galleryRepository, GalleryCategoryRepository galleryCategoryRepository) { this.galleryRepository = galleryRepository; this.galleryCategoryRepository = galleryCategoryRepository; } // gallery-category list public Map<Check, Object> list() { Map<Check, Object> hm = new LinkedHashMap<>(); hm.put(Check.status, true); List<GalleryCategory> ls = galleryCategoryRepository.findAll(); hm.put(Check.result, ls); return hm; } //galleryListByCategoryId public Map<Check, Object> listByCategoryId(Integer id) { Map<Check, Object> hm = new LinkedHashMap<>(); hm.put(Check.status, true); List<Gallery> ls = galleryRepository.findByGalleryCategory_IdEquals(id); hm.put(Check.result, ls); return hm; } } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.hibernate.validator.constraints.Length; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @Data @Entity @ApiModel(value = "Contents Model", description = "Contents Model Variable Definitions") public class Contents extends AuditEntity<String>{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) @ApiModelProperty(value = "Contents Id",required = true) private Integer id; @Column(unique = true) @ApiModelProperty(value = "Contents no",required = true) private String no; @Column(unique = true) @NotNull(message = "Contents title is not null!") @NotEmpty(message = "Contents title is not empty!") @ApiModelProperty(value = "Contents title",required = true) @Length(min = 2,max = 255,message = "Contents title length has min 2 and max 255 character!") private String title; @NotNull(message = "Contents description is not null!") @NotEmpty(message = "Contents description is not empty!") @ApiModelProperty(value = "Contents brief summary",required = true) @Length(min = 2,max = 255,message = "Contents description length has min 2 and max 255 character!") private String description; @NotNull(message = "Contents status is not null!") @NotEmpty(message = "Contents status is not empty!") @ApiModelProperty(value = "Contents status (Active or Passive)",required = true) private String status; @Column(columnDefinition = "text") @NotNull(message = "Contents details is not null!") @NotEmpty(message = "Contents details is not empty!") @ApiModelProperty(value = "Contents details",required = true) @Length(min = 2,message = "Contents details length has min 2 character!") private String details; @ApiModelProperty(value = "Contents save date",required = true) private String date; } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import org.hibernate.validator.constraints.Length; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import java.util.List; import java.util.Locale; @Data @Entity @ApiModel(value = "News Model", description = "News Model Variable Definitions") public class News extends AuditEntity<String> { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) @ApiModelProperty(value = "News Id",required = true) private Integer id; @Column(unique = true) @ApiModelProperty(value = "News no",required = true) private Long no; @Column(unique = true) @NotNull(message = "News title is not null!") @NotEmpty(message = "News title is not empty!") @ApiModelProperty(value = "News title",required = true) @Length(min = 2, max = 255, message = "News title length has min 2 and max 255 character!") private String title; @NotNull(message = "News summary is not null!") @NotEmpty(message = "News summary is not empty!") @ApiModelProperty(value = "News summary",required = true) @Length(min = 2, max = 255, message = "News summary length has min 2 and max 255 character!") private String summary; @Column(columnDefinition = "text") @NotNull(message = "News description is not null!") @NotEmpty(message = "News description is not empty!") @ApiModelProperty(value = "News details",required = true) @Length(min = 2, message = "News description length has min 2 character!") private String description; @ApiModelProperty(value = "News status (Active or Passive)",required = true) private String status; @ApiModelProperty(value = "News save date",required = true) private String date; @ElementCollection(fetch = FetchType.EAGER) private List<String> fileName; @ManyToOne(cascade = CascadeType.DETACH) @JoinColumn(name="categoryId") private NewsCategory newsCategory; } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.hibernate.validator.constraints.Length; import javax.persistence.*; import javax.validation.constraints.NotEmpty; @Data @Entity @ApiModel(value = "Survey Option Model", description = "Survey Option Model Variable Definitions") public class SurveyOption { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) @ApiModelProperty(value = "Survey Option Id",required = true) private Integer id; @Column(unique = true) @ApiModelProperty(value = "Survey Option No",required = true) private Long no; @NotEmpty(message = "Please Enter Title!") @NotEmpty(message = "Please Enter Title!") @ApiModelProperty(value = "Survey Option title",required = true) @Length(min = 3, max = 50, message = "Title field must be between 2 characters and 50 characters!") private String title; @ApiModelProperty(value = "Survey Option vote",required = true) private Integer vote=0; @ApiModelProperty(value = "Survey Option save date",required = true) private String date; @ManyToOne(cascade = CascadeType.DETACH) @JoinColumn(name="surveyId") private Survey survey; } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.*; import java.time.LocalDateTime; @Data @Entity @ApiModel(value = "User Activity Model", description = "User Activity Model Variable Definitions") public class UserActivity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) private Integer id; private String name; private String surname; private String email; private String sessionId; private String ip; private String role; private String url; private String image; private LocalDateTime date; } <file_sep> let select_id = 0; var success = $('#type-success'); var confirmText = $('#confirm-text'); //====================================== Category Section - Start ======================================// //-------------------------------------- Product Category Add - Start --------------------------------------// $('#productCategoryAdd_modalForm').submit( ( event ) => { event.preventDefault() const categoryName = $('#categoryName').val() const categoryDetail = $('#categoryDetails').val() const categoryStatus = $('#categoryStatus').val() const obj = { name: categoryName, status: categoryStatus, details: categoryDetail, no: codeGenerator() } //console.log("obj -> " + JSON.stringify(obj)) if (select_id !== 0) { // update obj["id"] = select_id; } $.ajax({ url: './product/categoryAdd', type: 'POST', data: JSON.stringify(obj), dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (data.status === true && data.result != null) { Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); setTimeout(function(){ $("#categoryAdd_modal").modal('hide'); }, 2000); resetFormCategory() } else if (data.status === true && data.result == null) { Swal.fire({ title: "Warning!", text: "Returned Data is Empty!", icon: "warning", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); resetFormCategory() } else { if (!jQuery.isEmptyObject(data.errors)) { console.log(data.errors) Swal.fire({ title: 'Error!', text: data.errors[0].fieldMessage, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } else { Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } } console.log(data) //formReset() }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) }) //-------------------------------------- Product Category Add - End ----------------------------------------// //-------------------------------------- Product Category List - Start ----------------------------------------// let globalArr = [] function dynamicPagination(totalPage, size) { $('#pagination_category').twbsPagination({ totalPages: totalPage, visiblePages: 5, prev: 'Prev', first: 'First', last: 'Last', startPage: 1, onPageClick: function (event, page) { if($('#searchCategory').val() === ""){ getAllProductCategoryByPage(page, size); }else{ searchProductCategory(page,size,$('#searchCategory').val()) } //$('#firstLast1-content').text('You are on Page ' + page); $('.pagination').find('li').addClass('page-item'); $('.pagination').find('a').addClass('page-link'); } }); } function getAllProductCategoryByPage(page,showNumber){ $.ajax({ url:"./product/categoryList/" + showNumber + "/" + (page-1), type: "get", dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data){ //console.log(data) createRowData(data) dynamicPagination(data.totalPage,showNumber) }, error: function (err){ Swal.fire({ title: "Error!", text: "An error occurred during the product category list operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } function createRowData(data){ let html = ``; let statusHtml = ``; let statusDropdownHtml = ``; let statusInt; //console.log(data) for (let i = 0; i < data.result.length; i++) { globalArr = data.result const itm = data.result[i] let status = itm.status; if(status === "Active"){ statusInt = 1; statusHtml = `<i class="fas fa-check-circle"></i>`; statusDropdownHtml = `<i class="mr-50 fas fa-ban"></i> <span>Passive</span>`; } if(status === "Passive"){ statusInt = 0; statusHtml = `<i class="fas fa-ban"></i>`; statusDropdownHtml = `<i class="fas fa-check-circle"></i> <span>Active</span>`; } html += `<tr> <td>${itm.no}</td> <td>${itm.name}</td> <td>${itm.details}</td> <td>${itm.date}</td> <td>${itm.status}</td> <td> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown"> <i class="fas fa-ellipsis-v"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="javascript:productCategoryUpdate(${i});"> <i class="mr-50 fas fa-pen"></i> <span>Edit</span> </a> <a class="dropdown-item" href="javascript:changeProductCategoryStatus(${itm.categoryId}, ${statusInt});"> `+statusDropdownHtml+` </a> <a class="dropdown-item" href="javascript:productCategoryDelete(${itm.categoryId});"> <i class="mr-50 far fa-trash-alt"></i> <span>Delete</span> </a> </div> </div> </td> </tr>` } $("#categoryTable").html(html) } $('#showCategoryTableRow').change(function(){ $('#pagination_category').twbsPagination('destroy'); getAllProductCategoryByPage(1, parseInt($(this).val())); //console.log("Show number Change " + parseInt($(this).val())); }); getAllProductCategoryByPage(1, 10); //-------------------------------------- Product Category List - End ------------------------------------------// //-------------------------------------- Product Category Delete - Start --------------------------------------------// function productCategoryDelete(id){ Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './product/categoryDelete/' + id, type: 'DELETE', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if( id != null){ Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); resetFormCategory() }else{ Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } //-------------------------------------- Product Category Delete - End ----------------------------------------------// //-------------------------------------- Product Category Update - Start ----------------------------------------------// function productCategoryUpdate(i){ $('#categoryAdd_modal').modal('toggle'); const itm = globalArr[i] select_id = itm.categoryId $('#categoryName').val(itm.name) $('#categoryDetails').val(itm.details) $('#categoryStatus').append(itm.status) //console.log(select_id) } //-------------------------------------- Product Category Update - End ------------------------------------------------// //-------------------------------------- Product Category Search - Start ------------------------------------------------// function searchProductCategory(page,showPageSize,searchData){ $.ajax({ url: './product/searchProductCategory/' + searchData + "/" + (page-1) + "/" + showPageSize, type: 'get', dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data) { //console.log("Data result " + JSON.stringify(data)) createRowData(data) dynamicPagination(data.totalPage,showPageSize) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } $('#searchCategory').keyup( function (event) { event.preventDefault(); const searchData = $(this).val() //console.log("Key " + searchData) if(searchData !== ""){ $("#categoryTable > tr" ).remove() //$('#pagination_category').twbsPagination('destroy'); searchProductCategory(1,$("#showCategoryTableRow").val(),searchData) }else{ $('#pagination_category').twbsPagination('destroy'); getAllProductCategoryByPage(1, $("#showCategoryTableRow").val()); } }) //-------------------------------------- Product Category Search - End --------------------------------------------------// //-------------------------------------- Product Category Status - Start ----------------------------------------------// function changeProductCategoryStatus(id, statusInt) { let url; let text; let confirmButtonText; let successTitle; if(statusInt === 1){ //Passive url = '/product/changeCategoryStatus/' + id + "/passive"; text = "This product category will be passive and won't be able to do any operations!"; confirmButtonText = "Ok"; successTitle = "Passive!" }else if(statusInt === 0){ //Active url = '/product/changeCategoryStatus/' + id + "/active"; text = "This product category will be active and will be able to do any operations!"; confirmButtonText = "Ok"; successTitle = "Active!" }else{ return; } Swal.fire({ title: 'Are you sure?', text: text, icon: 'warning', showCancelButton: true, confirmButtonText: confirmButtonText, customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { console.log(url) if (result.value) { $.ajax({ url: url, type: 'GET', dataType: 'json', success: function (data) { if( data.status === true){ Swal.fire({ icon: 'success', title: successTitle, text: data.message, customClass: { confirmButton: 'btn btn-success' } }); resetFormCategory() }else{ Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } //-------------------------------------- Product Category Status - End ------------------------------------------------// function resetFormCategory(){ select_id = 0 $('#categoryName').val("") $('#categoryDetails').val("") $('#categoryStatus').val("") getAllProductCategoryByPage(1, $('#showCategoryTableRow').val()); } function allProductCategoryList(){ $.ajax({ url: './product/categoryList', type: 'get', dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data) { category = data.result; //console.log("Product Categories : ", category) productCategoryOption(category) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } allProductCategoryList() function productCategoryOption(data) { data.forEach(item => { $('#productCategories').append('<option value="' + item.id + '">' + item.name + '</option>'); }) } //====================================== Category Section - End ========================================// //====================================== Product Section - Start ========================================// //-------------------------------------- Product Add - Start --------------------------------------// $("#productAdd_modalForm").submit( (event) => { event.preventDefault() const categories = $('#productCategories').val() const productName = $('#productName').val() const productDescription = $('#productDescription').val() const productPrice = $('#productPrice').val() const productDetails = $('#productDetails').val() const campaStatus = $('#campaignStatus').val() const campaName = $('#campaignName').val() const campaDetails = $('#campaignDetails').val() let categoryList = [] for(let i= 0 ; i<categories.length; i++){ const categoryObj = { id: categories[i] } categoryList.push(categoryObj) } const obj = { productCategories: categoryList, name: productName, description: productDescription, price: productPrice, details: productDetails, status: "Available", no: codeGenerator(), campaignName: campaName, campaignDetails: campaDetails, campaignStatus: campaStatus } console.log(obj) if ( select_id != 0 ) { // update obj["id"] = select_id; } $.ajax({ url: './product/add', type: 'POST', data: JSON.stringify(obj), dataType: 'json', contentType : 'application/json; charset=utf-8', success: function (data) { if(data.status == true && data.result != null){ Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); setTimeout(function(){ $("#productAdd_modal").modal('hide'); }, 2000); resetFormProduct() }else if(data.status == true && data.result == null){ Swal.fire({ title: "Warning!", text: "Returned Data is Empty!", icon: "warning", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); resetFormProduct() }else{ if (!jQuery.isEmptyObject(data.errors)) { console.log(data.errors) Swal.fire({ title: 'Error!', text: data.errors[0].fieldMessage, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }else{ Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } } console.log(data) resetFormProduct() }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) }) //-------------------------------------- Product Add - End ----------------------------------------// //-------------------------------------- Product List - Start ----------------------------------------// let globalProductArr = [] function dynamicPaginationProduct(totalPage, size) { $('#pagination_product').twbsPagination({ totalPages: totalPage, visiblePages: 5, prev: 'Prev', first: 'First', last: 'Last', startPage: 1, onPageClick: function (event, page) { if($('#searchProduct').val() === ""){ getAllProductsByPage(page, size); }else{ searchProduct(page,$('#showProductTableRow').val(),$('#searchProduct').val()) } //$('#firstLast1-content').text('You are on Page ' + page); $('.pagination').find('li').addClass('page-item'); $('.pagination').find('a').addClass('page-link'); } }); } function getAllProductsByPage(page,showNumber){ $.ajax({ url:"./product/list/" + showNumber + "/" + (page-1), type: "get", dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data){ createRowDataProduct(data) dynamicPaginationProduct(data.totalPage,showNumber) }, error: function (err){ Swal.fire({ title: "Error!", text: "An error occurred during the product list operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } function createRowDataProduct(data){ let html = ``; let statusHtml = ``; let statusDropdownHtml = ``; let statusInt; for (let i = 0; i < data.result.length; i++) { globalProductArr = data.result const itm = data.result[i] let status = itm.status; let price = priceFormatter(itm.price) let productCategory = productCategoryDetail(itm.productCategoryId[0]) if(status === "Available"){ statusInt = 1; statusHtml = `<i class="fas fa-check-circle"></i>`; statusDropdownHtml = `<i class="mr-50 fas fa-ban"></i> <span>Ban</span>`; } if(status === "Unavailable"){ statusInt = 0; statusHtml = `<i class="fas fa-ban"></i>`; statusDropdownHtml = `<i class="fas fa-check-circle"></i> <span>Unban</span>`; } html += `<tr> <td>${itm.no}</td> <td>${itm.name}</td> <td>${itm.description}</td> <td>${productCategory.name}</td> <td>${price}</td> <td>${itm.date}</td> <td>${itm.status}</td> <td> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown"> <i class="fas fa-ellipsis-v"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="javascript:productAddImages(${i});"> <i class="mr-50 far fa-images"></i> <span>Add Images</span> </a> <a class="dropdown-item" type="button" href="javascript:productDetail(${i});" > <i class="mr-50 fas fa-info-circle"></i> <span>Detail</span> </a> <a class="dropdown-item" href="javascript:productUpdate(${i});"> <i class="mr-50 fas fa-pen"></i> <span>Edit</span> </a> <a class="dropdown-item" href="javascript:changeProductStatus(${itm.productId}, ${statusInt});"> `+statusDropdownHtml+` </a> <a class="dropdown-item" href="javascript:productDelete(${itm.productId});"> <i class="mr-50 far fa-trash-alt"></i> <span>Delete</span> </a> </div> </div> </td> </tr>` } $("#productTable").html(html) } function productCategoryDetail(id){ var returnData $.ajax({ url: './product/categoryDetail/' + id, type: 'get', dataType: "json", async: false, contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data) returnData = data.result }, error: function (err) { console.log(err) } }) return returnData } $('#showProductTableRow').change(function(){ if($('#searchProduct').val() === ""){ $('#pagination_product').twbsPagination('destroy'); getAllProductsByPage(1, parseInt($(this).val())); }else{ //$('#pagination_product').twbsPagination('destroy'); searchProduct(page,parseInt($(this).val()),$('#searchProduct').val()) } //console.log("Show number Change " + parseInt($(this).val())); }); getAllProductsByPage(1, 10); //-------------------------------------- Product List - End ------------------------------------------// //-------------------------------------- Product Delete - Start ------------------------------------------// function productDelete(id){ Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './product/delete/' + id, type: 'DELETE', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if( id != null){ Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); resetFormProduct() }else{ Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } //-------------------------------------- Product Delete - End --------------------------------------------// //-------------------------------------- Product Update - End --------------------------------------------// function productUpdate(i){ $('#productAdd_modal').modal('toggle'); const itm = globalProductArr[i] select_id = itm.productId $.ajax({ url:"./product/detail/" + itm.productId, type: "get", dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data){ console.log(data.result) for(let i = 0; i < data.result.productCategories.length; i++){ $('#productCategories').val(data.result.productCategories[i].id).trigger('change') } $('#productName').val(data.result.name) $('#productDescription').val(data.result.description) $('#productPrice').val(data.result.price) $('#productDetails').val(data.result.details) if(data.result.campaignStatus === "Yes"){ $('#campaignStatus').val(data.result.campaignStatus).trigger('change') $('#campaignName').val(data.result.campaignName) $('#campaignDetails').val(data.result.campaignDetails) }else{ $('#campaignStatus').val(data.result.campaignStatus).trigger('change') } }, error: function (err){ Swal.fire({ title: "Error!", text: "An error occurred during the product list operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } function productAddImages(i){ $('#productImage').modal('toggle'); const itm = globalProductArr[i] $("#modalTitle").text(itm.name + " " + itm.description + " - " + itm.productId) $.ajax({ url: './product/chosenId/' + itm.productId, type: 'get', dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data) { console.log(data) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the chosen id operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } //-------------------------------------- Product Update - End --------------------------------------------// //-------------------------------------- Product Details - Start --------------------------------------------// // progress var mySwiper3 = new Swiper('.swiper-progress', { pagination: { el: '.swiper-pagination', type: 'progressbar' }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' } }); // navigation var mySwiper1 = new Swiper('.swiper-navigations', { navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' } }); function productDetail(i){ $('#productDetail').modal('toggle') $('#imagesChose').empty() const itm = globalProductArr[i] let html = `` let campaign1 let campaign2 let campaign3 var fileName $.ajax({ url: './product/chosenId/' + itm.productId, type: 'get', dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data) { //console.log(data) $.ajax({ url:"./product/detail/" + itm.productId, type: "get", dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data){ console.log(data) for (let j = 0; j < data.result.fileName.length; j++) { fileName = data.result.fileName[j] html += `<div class="swiper-slide"> <img src="/productDetail/get_image/id=${itm.productId}name=${fileName}" class="img-fluid" alt="banner" /> </div>` $('#imagesChose').append('<option value="' + fileName + '">Image - ' + j + '</option>'); //Ürüne ait image'leri silme aksiyonu select2 bölümüne eklenmesi }$("#imageSlide").html(html) $("#title").text(itm.no + " - " + itm.name + " " + itm.description) $("#priceDetail").text(priceFormatter(itm.price)+" TL") $("#dateDetail").text(itm.date) $("#statusDetail").text(itm.status) $("#details").text(data.result.details) if(data.result.campaignStatus === "Yes"){ $('#campaignStatusDetail').text(data.result.campaignStatus) $('#campaignNameDetail').text(data.result.campaignName) $('#campaignDetailsInfo').text(data.result.campaignDetails) }else{ $("#campaign-1").remove(); $("#campaign-2").remove(); $("#campaign-3").remove(); } }, error: function (err){ Swal.fire({ title: "Error!", text: "An error occurred during the product list operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the chosen id operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } //-------------------------------------- Product Details - End ----------------------------------------------// //-------------------------------------- Product Image Delete - Start ----------------------------------------------// function deleteImage(){ const chosenImages = $("#imagesChose").val() Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: '/product/chosenImages/delete/images=' + chosenImages, type: 'DELETE', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if( chosenImages.length > 0){ Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); $('#imagesChose').empty() setTimeout(function(){ $("#productDetail").modal('hide'); }, 2000); }else{ Swal.fire({ icon: 'warning', title: "Warning", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } //-------------------------------------- Product Image Delete - End ------------------------------------------------// //-------------------------------------- Product Search - Start --------------------------------------------// function searchProduct(page,showPageSize,searchData){ $.ajax({ url: './product/search/' + searchData + "/" + (page-1) + "/" + showPageSize, type: 'get', dataType: "json", contentType : 'application/json; charset=utf-8', success: function (data) { createRowDataProduct(data) dynamicPaginationProduct(data.totalPage,showPageSize) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } $('#searchProduct').keyup( function (event) { event.preventDefault(); const searchData = $(this).val() if(searchData !== ""){ $("#productTable > tr" ).remove() $('#pagination_product').twbsPagination('destroy'); searchProduct(1,$("#showProductTableRow").val(),searchData) }else{ $('#pagination_product').twbsPagination('destroy'); getAllProductsByPage(1, $("#showProductTableRow").val()); } }) //-------------------------------------- Product Search - End ----------------------------------------------// //-------------------------------------- Product Status - Start ----------------------------------------------// function changeProductStatus(id, statusInt) { let url; let text; let confirmButtonText; let successTitle; if(statusInt === 1){ //Unavailable url = '/product/changeStatus/' + id + "/passive"; text = "This product will be banned and won't be able to do any operations!"; confirmButtonText = "Ban"; successTitle = "Banned!" }else if(statusInt === 0){ //Available url = '/product/changeStatus/' + id + "/active"; text = "This product will be unbanned and will be able to do any operations!"; confirmButtonText = "Unban"; successTitle = "Unbanned!" }else{ return; } Swal.fire({ title: 'Are you sure?', text: text, icon: 'warning', showCancelButton: true, confirmButtonText: confirmButtonText, customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { console.log(url) if (result.value) { $.ajax({ url: url, type: 'GET', dataType: 'json', success: function (data) { if( data.status === true){ Swal.fire({ icon: 'success', title: successTitle, text: data.message, customClass: { confirmButton: 'btn btn-success' } }); getAllProductsByPage(1, $('#showProductTableRow').val()); }else{ Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } //-------------------------------------- Product Status - End ------------------------------------------------// //====================================== Product Section - End ==========================================// $('#campaignStatus').change(function () { //console.log($(this).val()) if ($(this).val() !== "Yes"){ $('#campaignName').attr("disabled", true); $('#campaignDetails').attr("disabled", true); }else{ $('#campaignName').attr("disabled", false); $('#campaignDetails').attr("disabled", false); } }); function resetFormProduct(){ select_id = 0 $('#productCategories').empty() $('#productName').val("") $('#productDescription').val("") $('#productPrice').val("") $('#productDetails').val("") $('#campaignName').val("") $('#campaignDetails').val("") getAllProductsByPage(1, 10); allProductCategoryList() } function priceFormatter(price){ var formattedPrice = (price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,') return formattedPrice } function codeGenerator() { const date = new Date(); const time = date.getTime(); return time.toString().substring(3); } <file_sep>function getAllAnnouncementsByPage(page, size) { $.ajax({ url: '/announcements/all' + '/status=' + selectedAnnouncementStatus + '/page=' + page + 'size=' + size, type: 'GET', dataType: 'Json', success: function (data) { console.log(data.result) createAnnouncementTable(data.result); dynamicPagination(data.totalPage, size); }, error: function (err) { console.log(err) } }) } function searchAnnouncementByKey(key, page, size) { $.ajax({ url: '/announcements/search' + '/key=' + key + '/status=' + selectedAnnouncementStatus + '/page=' + page + 'size=' + size, type: 'GET', dataType: 'Json', success: function (data) { createAnnouncementTable(data.result); dynamicPagination(data.totalPage, size); }, error: function (err) { console.log(err) } }) } function saveAnnouncement(announcementObj) { let url; if(announcementObj["id"] === undefined){ url = '/announcements/add'; }else{ url = '/announcements/update'; } $.ajax({ url: url, type: 'POST', data: JSON.stringify(announcementObj), dataType: 'JSON', contentType: 'application/json; charset=utf-8', success: function (data) { if (data.status === true) { Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); getAllAnnouncementsByPage(0, $('#announcement_pagesize').val()); $('#announcement_add_form').trigger("reset"); editor.setText(''); setTimeout(function () { $("#announcement_form_modal").modal('hide'); }, 0); selectedAnnouncement = {}; } else { if (!jQuery.isEmptyObject(data.errors)) { Swal.fire({ title: 'Error!', text: data.errors[0].fieldMessage, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } else { Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } } }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err); } }) } function deleteAnnouncement(aid) { Swal.fire({ title: 'Are you sure?', text: "This announcement will be permanently deleted!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Delete', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: '/announcements/delete/id=' + aid, type: 'DELETE', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if( data.status === true){ Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); $('#announcement_pagination').twbsPagination('destroy'); getAllAnnouncementsByPage(0, $('#announcement_pagesize').val()); }else{ Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } function getAnnouncement(aid, index) { $.ajax({ url: '/announcements/get' + '/id=' + aid, type: 'GET', dataType: 'Json', success: function (data) { if(data.status === true){ selectedAnnouncement = data.result; if(index === 0){ //detail createAnnouncementDetailsModal(); } if(index === 1){ //update createAnnouncementEditModal(); } }else{ console.log(data.message); } }, error: function (err) { console.log(err) } }) return {}; } function codeGenerator() { const date = new Date(); const time = date.getTime(); return time.toString().substring(3); } function dynamicPagination(totalPage, size) { $('#announcement_pagination').twbsPagination({ totalPages: totalPage, visiblePages: 5, prev: 'Prev', first: 'First', last: 'Last', startPage: 1, onPageClick: function (event, page) { if($('#announcement_search').val() === ""){ getAllAnnouncementsByPage(page-1, size); }else{ searchAnnouncementByKey($('#announcement_search').val(), page-1, $('#announcement_pagesize').val()); } //$('#firstLast1-content').text('You are on Page ' + page); $('.pagination').find('li').addClass('page-item'); $('.pagination').find('a').addClass('page-link'); } }); } function createAnnouncementTable(announcements) { let html = ``; for(let i = 0; i < announcements.length; i++){ const announcement = announcements[i]; html += ` <tr> <td>` + announcement.no + `</td> <td>` + announcement.title + `</td> <td>` + announcement.date + `</td> <td>` + announcement.status + `</td> <td> <a href="javascript:getAnnouncement(`+announcement.aid+`, `+0+`);"> <i class="far fa-file-alt" style="font-size: 20px;"></i> </a> </td> <td> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown"> <i class="fas fa-ellipsis-v"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="javascript:getAnnouncement(`+announcement.aid+`, `+1+`);"> <i class="mr-50 fas fa-pen"></i> <span>Edit</span> </a> <a class="dropdown-item" href="javascript:deleteAnnouncement(`+announcement.aid+`);"> <i class="mr-50 far fa-trash-alt"></i> <span>Delete</span> </a> </div> </div> </td> </tr>`; } $('#tBodyAnnouncements').html(html); } function createAnnouncementDetailsModal() { $("#detail_detail").text(selectedAnnouncement.detail); $("#announcement_detail_modal_title").text( "Announcement No : " + selectedAnnouncement.no); $('#announcement_detail_modal').modal('toggle'); } function createAnnouncementEditModal() { $("#title").val(selectedAnnouncement.title); editor.setText(selectedAnnouncement.detail); $("#announcement_form_modal_title").text("Edit Announcement - No : " + selectedAnnouncement.no); $('#announcement_form_modal').modal('toggle'); } $('#announcement_add_form').submit((event) => { event.preventDefault(); const title = $("#title").val(); const announcementObj = { title: title, detail: editorText, status: "Active" } if(jQuery.isEmptyObject(selectedAnnouncement)){ announcementObj["no"] = codeGenerator(); }else{ announcementObj["id"] = selectedAnnouncement.id; announcementObj["no"] = selectedAnnouncement.no; announcementObj["date"] = selectedAnnouncement.date; } saveAnnouncement(announcementObj); }); $('#announcement_pagesize').change(function () { if($('#announcement_search').val() === ""){ $('#announcement_pagination').twbsPagination('destroy'); getAllAnnouncementsByPage(0, parseInt($(this).val())); }else{ searchAnnouncementByKey($('#announcement_search').val(), page-1, $('#announcement_pagesize').val()); } }); $('#announcement_status').change(function(){ selectedAnnouncementStatus = $(this).val(); $("#tBodyAnnouncements > tr").remove(); getAllAnnouncementsByPage(0, $('#announcement_pagesize').val()); }); $('#announcement_search').keyup( function (event) { event.preventDefault(); const key = $(this).val(); if(key !== ""){ $("#tBodyAnnouncements > tr").remove(); $('#announcement_pagination').twbsPagination('destroy'); searchAnnouncementByKey(key, 0, $('#announcement_pagesize').val()); }else{ $('#announcement_pagination').twbsPagination('destroy'); getAllAnnouncementsByPage(0, $('#announcement_pagesize').val()); } }); $( "#announcement_form_modal_button" ).click(function() { $('#announcement_add_form').trigger("reset"); $("#announcement_form_modal_title").text("New Announcement"); $('#announcement_form_modal').modal('toggle'); }); let options = { placeholder: 'Enter the announcement details...', theme: 'snow' }; const editor = new Quill('#detail', options); editor.on('text-change', function() { editorText = editor.getText(); }); let selectedAnnouncement = {}; let selectedAnnouncementStatus = "Active"; let editorText = ""; $('#announcement_pagination').twbsPagination('destroy'); getAllAnnouncementsByPage(0, 10); <file_sep>package companyAll_MVC.properties; import lombok.Data; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @Data public class Company { @NotNull(message = "Please Enter Your Company Name!") @NotEmpty(message = "Please Enter Your Company Name!") @Length(min = 2,max = 100, message = "Company Name field must be between 2 characters and 100 characters!") private String companyName; @NotNull(message = "Please Enter Your Company Address!") @NotEmpty(message = "Please Enter Your Company Address!") @Length(min = 10,max = 200, message = "Company Address field must be between 10 characters and 200 characters!") private String companyAddress; private String companySector; @NotNull(message = "Please Enter Your Company Phone!") @NotEmpty(message = "Please Enter Your Company Phone!") @Length(min = 1,max = 13, message = "Company Phone must be in the format +90(xxx)-xxx-xx-xx!") private String companyPhone; } <file_sep>package companyAll_MVC.repositories._elastic; import companyAll_MVC.documents.ElasticContents; import companyAll_MVC.documents.ElasticProduct; import companyAll_MVC.documents.ElasticProductCategory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; import java.util.Optional; public interface ElasticProductRepository extends ElasticsearchRepository<ElasticProduct,String> { @Query("{\"bool\":{\"must\":[{\"term\":{\"productId\":\"?0\"}}],\"must_not\":[],\"should\":[]}}") Optional<ElasticProduct> findById(Integer productId); @Query("{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}}") Page<ElasticProduct> findByOrderByIdAsc(Pageable pageable); @Query("{\"bool\":{\"must\":[],\"must_not\":[],\"should\":[{\"prefix\":{\"name\":\"?0\"}},{\"prefix\":{\"status\":\"?0\"}},{\"prefix\":{\"no\":\"?0\"}},{\"prefix\":{\"date\":\"?0\"}},{\"prefix\":{\"description\":\"?0\"}}]}}}") Page<ElasticProduct> findBySearchData(String data, Pageable pageable); @Query("{\"bool\":{\"must\":[],\"must_not\":[],\"should\":[{\"match\":{\"name\":\"?0\"}},{\"match\":{\"status\":\"?0\"}},{\"match\":{\"no\":\"?0\"}},{\"match\":{\"date\":\"?0\"}},{\"match\":{\"description\":\"?0\"}}]}}}") Page<ElasticProduct> findBySearchDataMatch(String data, Pageable pageable); Page<ElasticProduct> findByProductCategoryIdEquals(Integer categoryId,Pageable pageable); @Query("{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}}") List<ElasticProduct> findAllProducts(); @Query("{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}},\"from\":0,\"size\":10,\"sort\":{ \"productId\": { \"order\": \"desc\" } },\"aggs\":{}") List<ElasticProduct> findElasticProductsBySizeBetween(); Page<ElasticProduct> findByOrderByProductIdDesc(Pageable pageable); List<ElasticProduct> findByProductCategoryIdEquals(Integer categoryId); } <file_sep>package companyAll_MVC.restcontroller; import companyAll_MVC.dto.DashboardDto; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Statics; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.Authorization; import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping("/api/dashboard") @Api(value = "DashboardRestController",authorizations = {@Authorization(value = "basicAuth")}) public class DashboardRestController { final DashboardDto dashboardDto; public DashboardRestController(DashboardDto dashboardDto) { this.dashboardDto = dashboardDto; } //News Chart @ResponseBody @GetMapping("/newsChart") @ApiOperation(value = "News statics shows.") public Map<Statics,Object> newsChart(){ return dashboardDto.newsChart(); } //General Statics Information @ResponseBody @GetMapping("/generalStatics") @ApiOperation(value = "General statics shows for firm.") public Map<Statics,Object> generalStatics(){ return dashboardDto.generalStatics(); } //Last Added 6 Product @ResponseBody @GetMapping("/lastAddSixProduct") @ApiOperation(value = "Last added six product shows for the firm.") public Map<Statics,Object> lastAddSixProduct(){ return dashboardDto.lastAddSixProduct(); } //Last Six Order @ResponseBody @GetMapping("/lastSixOrder") @ApiOperation(value = "Last added six order shows for the firm.") public Map<Statics,Object> lastSixOrder(){ return dashboardDto.lastSixOrder(); } //Total product by Category Id @ResponseBody @GetMapping("/totalProductByCategoryId/{stId}") @ApiOperation(value = "Total product is listed by category id.") public Map<Check,Object> totalProductByCategoryId(@PathVariable String stId){ return dashboardDto.totalProductByCategoryId(stId); } //Daily Announcment @ResponseBody @GetMapping("/dailyAnnouncment/{stPageNo}") @ApiOperation(value = "Daily announcment is listed by page no.") public Map<Check,Object> dailyAnnouncment(@PathVariable String stPageNo){ return dashboardDto.dailyAnnouncment(stPageNo); } } <file_sep>package companyAll_MVC.documents; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.math.BigDecimal; import java.util.List; @Data @Document(indexName = "product") public class ElasticProduct { @Id private String id; private Integer productId; @Field(type = FieldType.Text) private String no; @Field(type = FieldType.Text) private String name; @Field(type = FieldType.Text) private String description; private BigDecimal price; @Field(type = FieldType.Text) private String details; @Field(type = FieldType.Text) private String date; @Field(type = FieldType.Text) private String status; private List<String> fileName; private Double totalLike; @Field(type = FieldType.Text) private String campaignStatus; //yes or no @Field(type = FieldType.Text) private String campaignName; @Field(type = FieldType.Text) private String campaignDetails; private List<Integer> productCategoryId; } <file_sep>package companyAll_MVC.restcontroller; import companyAll_MVC.dto.SurveyDto; import companyAll_MVC.entities.Likes; import companyAll_MVC.entities.Survey; import companyAll_MVC.entities.SurveyOption; import companyAll_MVC.repositories._elastic.ElasticSurveyRepository; import companyAll_MVC.utils.Check; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping("/api/surveys") //@Api(value = "SurveysRestController",authorizations = {@Authorization(value = "basicAuth")}) public class SurveyRestController { final ElasticSurveyRepository elasticSurveyRepository; final SurveyDto surveyDto; public SurveyRestController(ElasticSurveyRepository elasticSurveyRepository, SurveyDto surveyDto) { this.elasticSurveyRepository = elasticSurveyRepository; this.surveyDto = surveyDto; } // Survey List With Pagination @GetMapping("/list/{stShowNumber}/{stPageNo}") @ApiOperation(value = "Products is listed by page no and number of show.") public Map<Check, Object> listSurveyWithPagination(@PathVariable String stShowNumber, @PathVariable String stPageNo) { return surveyDto.listSurveyWithPagination(stShowNumber, stPageNo); } // Survey List PaginationByElasticSearch @GetMapping("/search/{data}/{stPageNo}/{stShowNumber}") @ApiOperation(value = "Products is searched by page no and number of show.") public Map<Check,Object> searchVote(@PathVariable String data,@PathVariable String stPageNo,@PathVariable String stShowNumber) { return surveyDto.searchVote(data, stPageNo, stShowNumber); } // vote - add @GetMapping("/addVote/{surveyId}/{surveyOptionId}") @ResponseBody public Map<Check, Object> addVote(@PathVariable Integer surveyId, @PathVariable Integer surveyOptionId) { return surveyDto.addVote(surveyId,surveyOptionId); } } <file_sep>package companyAll_MVC.repositories._elastic; import companyAll_MVC.documents.ElasticCustomerMin; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; import java.util.Optional; public interface ElasticCustomerMinRepository extends ElasticsearchRepository<ElasticCustomerMin, String> { @Query("{\"bool\":{\"should\":[{\"match\":{\"status\":\"?0\"}}],\"must_not\":[]}}") List<ElasticCustomerMin> findAllByStatus(String status); @Query("{\"bool\":{\"should\":[{\"match\":{\"status\":\"?0\"}}],\"must_not\":[]}}") Page<ElasticCustomerMin> findAllByStatus(String status, Pageable pageable); @Query("{\"bool\":{\"must\":[{\"term\":{\"cid\":\"?0\"}}],\"must_not\":[],\"should\":[]}}") Optional<ElasticCustomerMin> findByCid(Integer cid); } <file_sep>package companyAll_MVC.documents; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; @Document(indexName = "addresses") @Data public class ElasticAddress { @Id private String id; @Field(type = FieldType.Auto) private Integer aid; @Field(type = FieldType.Text) private String type; @Field(type = FieldType.Text) private String detail; } <file_sep>package companyAll_MVC.controllers; import companyAll_MVC.entities.Product; import companyAll_MVC.repositories._elastic.ElasticProductCategoryRepository; import companyAll_MVC.repositories._elastic.ElasticProductRepository; import companyAll_MVC.repositories._jpa.ProductCategoryRepository; import companyAll_MVC.repositories._jpa.ProductRepository; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Util; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.Base64; import java.util.LinkedHashMap; import java.util.Map; @Controller @RequestMapping("/productDetail") public class ProductDetailsController { final ProductRepository productRepository; final ProductCategoryRepository productCategoryRepository; final ElasticProductCategoryRepository elasticProductCategoryRepository; final ElasticProductRepository elasticProductRepository; public ProductDetailsController(ProductRepository productRepository, ProductCategoryRepository productCategoryRepository, ElasticProductCategoryRepository elasticProductCategoryRepository, ElasticProductRepository elasticProductRepository) { this.productRepository = productRepository; this.productCategoryRepository = productCategoryRepository; this.elasticProductCategoryRepository = elasticProductCategoryRepository; this.elasticProductRepository = elasticProductRepository; } @GetMapping("/{stId}") public String productDetails(@PathVariable String stId, Model model){ try { int id = Integer.parseInt(stId); Product product = productRepository.findById(id).get(); DecimalFormat df = new DecimalFormat("###,###.##"); // or pattern "###,###.##$" model.addAttribute("detail",product); model.addAttribute("priceFormat",df.format(product.getPrice())); //System.out.println(product); } catch (Exception e) { System.err.println(e); return "redirect:/productList"; } return "productDetails"; } @ResponseBody @GetMapping("/mostPopularProducts") public Map<Check,Object> mostPopular(){ Map<Check,Object> map = new LinkedHashMap<>(); map.put(Check.status,true); map.put(Check.message,"Most popular 5 products listing operations success!"); map.put(Check.result,productRepository.mostPopularFiveProducts()); return map; } @GetMapping("/get_image/id={id}name={name}") public void getImage(@PathVariable Integer id, @PathVariable String name, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg; image/jpg; image/png"); File file = new File(Util.UPLOAD_DIR_PRODUCTS + id + "/" + name); if(file.exists()){ byte[] fileContent = FileUtils.readFileToByteArray(file); response.getOutputStream().write(fileContent); }else{ File defaultFile = new File(Util.UPLOAD_DIR_PRODUCTS + "default_image.jpg"); byte[] defaultFileContent = FileUtils.readFileToByteArray(defaultFile); response.getOutputStream().write(defaultFileContent); } response.getOutputStream().close(); } } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.*; @Data @Entity @ApiModel(value = "Advertisement Model", description = "Advertisement Model Variable Definitions") public class Advertisement extends AuditEntity<String>{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(value = "Advertisement Id",required = true) private Integer id; @Column(unique = true) @NotNull(message = "Invalid advertisement no! (null)") @NotEmpty(message = "Invalid advertisement no! (empty)") @ApiModelProperty(value = "Advertisement ten digits no",required = true) @Pattern(regexp="(^$|[0-9]{10})", message = "Invalid advertisement no!") private String no; @Column(unique = true) @Size(max = 50, message = "Advertisement name's size can be 50 at max!") @NotNull(message = "Invalid advertisement name! (null)") @NotEmpty(message = "Invalid advertisement name! (empty)") @ApiModelProperty(value = "Advertisement name",required = true) private String name; @Positive(message = "Advertisement view should be positive number!") @ApiModelProperty(value = "Advertisement number of view",required = true) private int view; @NotNull(message = "Invalid advertisement start date! (null)") @NotEmpty(message = "Invalid advertisement start date! (empty)") @ApiModelProperty(value = "Advertisement date of start",required = true) private String startDate; @NotNull(message = "Invalid advertisement finish date! (null)") @NotEmpty(message = "Invalid advertisement finish date! (empty)") @ApiModelProperty(value = "Advertisement date of finish",required = true) private String finishDate; @Positive(message = "Advertisement width should be positive number!") @ApiModelProperty(value = "Advertisement image width",required = true) private int width; @Positive(message = "Advertisement height should be positive number!") @ApiModelProperty(value = "Advertisement image height",required = true) private int height; @ApiModelProperty(value = "Advertisement image file name",required = true) private String image; @NotNull(message = "Invalid advertisement link! (null)") @NotEmpty(message = "Invalid advertisement link! (empty)") @ApiModelProperty(value = "Advertisement web link",required = true) private String link; @Min(value = 0L, message = "Click count should be min 0!") @ApiModelProperty(value = "Advertisement number of click",required = true) private Long click; @NotNull(message = "Invalid advertisement status! (null)") @NotEmpty(message = "Invalid advertisement status! (empty)") @ApiModelProperty(value = "Advertisement status (Active or Passive)",required = true) @Pattern(regexp = "Active|Passive", message = "Advertisement status must be either 'Active' or 'Passive'") private String status; } <file_sep>package companyAll_MVC.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.hibernate.validator.constraints.Length; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.List; @Data @Entity @ApiModel(value = "User Model", description = "User Model Variable Definitions") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) @ApiModelProperty(value = "User Id",required = true) private Integer id; @Column(unique = true) @ApiModelProperty(value = "User no",required = true) private Long no; @NotNull(message = "Please Enter Your Name!") @NotEmpty(message = "Please Enter Your Name!") @ApiModelProperty(value = "User name",required = true) @Length(min = 2,max = 50, message = "Name field must be between 2 characters and 50 characters!") private String name; @NotNull(message = "Please Enter Your Surname!") @NotEmpty(message = "Please Enter Your Surname!") @ApiModelProperty(value = "User surname",required = true) @Length(min = 2,max = 50, message = "Surname field must be between 2 characters and 50 characters!") private String surname; @Column(unique = true) @NotNull(message = "Please Enter Your Email!") @NotEmpty(message = "Please Enter Your Email!") @ApiModelProperty(value = "User email",required = true) @Length(min = 11,max = 50, message = "Surname field must be between 2 characters and 50 characters!") private String email; @NotNull(message = "Please Enter Your Password!") @NotEmpty(message = "Please Enter Your Password!") @ApiModelProperty(value = "User password",required = true) private String password; @Column(unique = true) @NotNull(message = "Please Enter Your Company Name!") @NotEmpty(message = "Please Enter Your Company Name!") @ApiModelProperty(value = "User company name",required = true) @Length(min = 2,max = 100, message = "Company Name field must be between 2 characters and 100 characters!") private String companyName; @NotNull(message = "Please Enter Your Company Address!") @NotEmpty(message = "Please Enter Your Company Address!") @ApiModelProperty(value = "User company address",required = true) @Length(min = 10,max = 200, message = "Company Address field must be between 10 characters and 200 characters!") private String companyAddress; @ApiModelProperty(value = "User biography",required = true) private String bio; @ApiModelProperty(value = "User birth date",required = true) private String birthday; @ApiModelProperty(value = "User company sector",required = true) private String companySector; @ApiModelProperty(value = "User profile image",required = true) private String profileImage; @Column(unique = true) @NotNull(message = "Please Enter Your Company Phone!") @NotEmpty(message = "Please Enter Your Company Phone!") @ApiModelProperty(value = "User company phone",required = true) @Length(min = 1,max = 13, message = "Company Phone must be in the format +90(xxx)-xxx-xx-xx!") private String companyPhone; private boolean enabled; private boolean tokenExpired; @JsonIgnore @ManyToMany(cascade = CascadeType.DETACH, fetch = FetchType.EAGER) @JoinTable(name = "user_roles",joinColumns = @JoinColumn(name = "user_id"),inverseJoinColumns = @JoinColumn(name = "roles_id")) private List<Role> roles; } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; @Data @Entity @ApiModel(value = "Customer Address Model", description = "Customer Address Model Variable Definitions") public class Address extends AuditEntity<String>{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(value = "Customer Address Id",required = true) private Integer id; @NotNull(message = "Invalid address type! (null)") @NotEmpty(message = "Invalid address type! (empty)") @ApiModelProperty(value = "Customer Address Type (Home or Work)",required = true) @Pattern(regexp = "Home|Work", message = "Address type must be either 'Home' or 'Work'") private String type; @Size(max = 200, message = "Address detail's size can be 200 at max!") @NotNull(message = "Invalid address detail! (null)") @NotEmpty(message = "Invalid address detail! (empty)") @ApiModelProperty(value = "Customer Address detail",required = true) private String detail; } <file_sep>package companyAll_MVC.repositories._elastic; import companyAll_MVC.documents.ElasticLikes; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; public interface ElasticLikesRepository extends ElasticsearchRepository<ElasticLikes,String> { @Query("{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}}") Page<ElasticLikes> findByOrderByIdAsc(Pageable pageable); @Query("{\"bool\":{\"must\":[],\"must_not\":[],\"should\":[{\"prefix\":{\"customerName\":\"?0\"}},{\"prefix\":{\"productName\":\"?0\"}}]}}") Page<ElasticLikes> findBySearchData(String data, Pageable pageable); @Query("{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}}") List<ElasticLikes> allLikes(); } <file_sep>package companyAll_MVC.repositories._jpa; import companyAll_MVC.entities.SurveyOption; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface SurveyOptionRepository extends JpaRepository<SurveyOption,Integer > { List<SurveyOption> findBySurvey_IdEquals(Integer id); } <file_sep>package companyAll_MVC.entities; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.*; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Positive; @Data @Entity @ApiModel(value = "Indent Model", description = "Indent Model Variable Definitions") public class Indent extends AuditEntity<String>{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(value = "Indent Id",required = true) private Integer id; @Column(unique = true) @NotNull(message = "Invalid indent no! (null)") @NotEmpty(message = "Invalid indent no! (empty)") @Pattern(regexp="(^$|[0-9]{10})", message = "Invalid indent no!") @ApiModelProperty(value = "Indent ten digits no",required = true) private String no; @OneToOne private Customer customer; @OneToOne private Product product; @NotNull(message = "Invalid indent date! (null)") @NotEmpty(message = "Invalid indent date! (empty)") @ApiModelProperty(value = "Indent save date",required = true) private String date; @NotNull(message = "Invalid address index! (null)") @ApiModelProperty(value = "Indent address index",required = true) private int adressIndex; @NotNull(message = "Invalid indent status! (null)") @NotEmpty(message = "Invalid indent status! (empty)") @ApiModelProperty(value = "Indent status (Active or Passive)",required = true) @Pattern(regexp = "Active|Delivered", message = "Indent status must be either 'Active' or 'Delivered'") private String status; @ApiModelProperty(value = "Indent indent status (true or false)",required = true) private boolean orderStatus=false; } <file_sep>package companyAll_MVC.controllers; import companyAll_MVC.documents.ElasticGallery; import companyAll_MVC.documents.ElasticGalleryCategory; import companyAll_MVC.entities.Gallery; import companyAll_MVC.entities.GalleryCategory; import companyAll_MVC.repositories._elastic.ElasticGalleryCategoryRepository; import companyAll_MVC.repositories._elastic.ElasticGalleryRepository; import companyAll_MVC.repositories._jpa.GalleryCategoryRepository; import companyAll_MVC.repositories._jpa.GalleryRepository; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Util; import org.apache.commons.io.FileUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.File; import java.io.IOException; import java.util.*; @Controller @RequestMapping("/gallery") public class GalleryController { int chosenId = 0; int sendCount = 0; int sendSuccessCount = 0; String errorMessage = ""; final ElasticGalleryRepository elasticGalleryRepository; final GalleryRepository galleryRepository; final ElasticGalleryCategoryRepository elasticGalleryCategoryRepository; final GalleryCategoryRepository galleryCategoryRepository; public GalleryController(ElasticGalleryRepository elasticGalleryRepository, GalleryRepository galleryRepository, ElasticGalleryCategoryRepository elasticGalleryCategoryRepository, GalleryCategoryRepository galleryCategoryRepository) { this.elasticGalleryRepository = elasticGalleryRepository; this.galleryRepository = galleryRepository; this.elasticGalleryCategoryRepository = elasticGalleryCategoryRepository; this.galleryCategoryRepository = galleryCategoryRepository; } @GetMapping("") public String gallery() { return "galleries"; } // Add Category @PostMapping("/categoryAdd") @ResponseBody public Map<Check, Object> categoryAdd(@RequestBody @Valid GalleryCategory galleryCategory, BindingResult bindingResult) { Map<Check, Object> map = new LinkedHashMap<>(); if (!bindingResult.hasErrors()) { if (galleryCategory.getId() != null) { Optional<GalleryCategory> optionalGalleryCategory = galleryCategoryRepository.findById(galleryCategory.getId()); if (optionalGalleryCategory.isPresent()) { try { GalleryCategory galleryCategory1 = galleryCategoryRepository.saveAndFlush(galleryCategory); ElasticGalleryCategory elasticGalleryCategory = new ElasticGalleryCategory(); elasticGalleryCategory.setId(Integer.toString(galleryCategory1.getId())); elasticGalleryCategory.setCategoryId(galleryCategory1.getId()); elasticGalleryCategory.setNo(Long.toString(galleryCategory1.getNo())); elasticGalleryCategory.setName(galleryCategory1.getName()); elasticGalleryCategory.setStatus(galleryCategory1.getStatus()); elasticGalleryCategoryRepository.save(elasticGalleryCategory); map.put(Check.status, true); map.put(Check.message, "Updated operations success!"); map.put(Check.result, galleryCategory); } catch (Exception ex) { System.err.println("Elastic gallery category update" + ex); } } } else { try { GalleryCategory galleryCategory1 = galleryCategoryRepository.saveAndFlush(galleryCategory); map.put(Check.status, true); map.put(Check.message, "Adding of Gallery Category Operations Successful!"); map.put(Check.result, galleryCategory); ElasticGalleryCategory elasticGalleryCategory = new ElasticGalleryCategory(); elasticGalleryCategory.setId(Integer.toString(galleryCategory1.getId())); elasticGalleryCategory.setCategoryId(galleryCategory.getId()); elasticGalleryCategory.setNo(Long.toString(galleryCategory.getNo())); elasticGalleryCategory.setName(galleryCategory.getName()); elasticGalleryCategory.setStatus(galleryCategory.getStatus()); elasticGalleryCategoryRepository.save(elasticGalleryCategory); } catch (Exception ex) { map.put(Check.status, false); if (ex.toString().contains("constraint")) { String error = "This gallery category name has alredy been registered!"; Util.logger(error, GalleryCategory.class); map.put(Check.message, error); } } } } else { map.put(Check.status, false); map.put(Check.errors, Util.errors(bindingResult)); } return map; } //List of Gallery Category with pagination @ResponseBody @GetMapping("/categoryList/{stShowNumber}/{stPageNo}") public Map<Check, Object> categoryList(@PathVariable String stShowNumber, @PathVariable String stPageNo) { Map<Check, Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo, showNumber); Page<ElasticGalleryCategory> categoryPage = elasticGalleryCategoryRepository.findByOrderByIdAsc(pageable); map.put(Check.status, true); map.put(Check.totalPage, categoryPage.getTotalPages()); map.put(Check.message, "Content listing on page " + (pageNo + 1) + " is successful"); map.put(Check.result, categoryPage.getContent()); } catch (Exception e) { map.put(Check.status, false); String error = "An error occurred during the operation!"; System.err.println(e); Util.logger(error, GalleryCategory.class); map.put(Check.message, error); } return map; } // Delete Category @ResponseBody @DeleteMapping("/categoryDelete/{stId}") public Map<Check, Object> delete(@PathVariable String stId) { Map<Check, Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); Optional<GalleryCategory> optionalGalleryCategory = galleryCategoryRepository.findById(id); if (optionalGalleryCategory.isPresent()) { ElasticGalleryCategory elasticGalleryCategory = elasticGalleryCategoryRepository.findById(id).get(); galleryCategoryRepository.deleteById(id); elasticGalleryCategoryRepository.deleteById(elasticGalleryCategory.getId()); map.put(Check.status, true); map.put(Check.message, "Data has been deleted!"); map.put(Check.result, optionalGalleryCategory.get()); } else { String error = "Gallery Category not found"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, GalleryCategory.class); } } catch (Exception e) { String error = "An error occurred during the delete operation"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, GalleryCategory.class); System.err.println(e); } return map; } // ElasticSearch Category @ResponseBody @GetMapping("/searchGalleryCategory/{data}/{stPageNo}/{stShowNumber}") public Map<Check, Object> searchGalleryCategory(@PathVariable String data, @PathVariable String stPageNo, @PathVariable String stShowNumber) { Map<Check, Object> map = new LinkedHashMap<>(); try { System.out.println("burada :"); int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo, showNumber); System.out.println("burada pageable:" + pageable); System.out.println("burada data:" + data); Page<ElasticGalleryCategory> searchPage = elasticGalleryCategoryRepository.findBySearchData(data, pageable); System.out.println("burada searchPage:" + searchPage); List<ElasticGalleryCategory> elasticGalleryCategoryList = searchPage.getContent(); System.out.println("burada elasticGalleryCategoryList:" + elasticGalleryCategoryList); int totalData = elasticGalleryCategoryList.size(); //for total data in table System.out.println("burada totalData:" + totalData); if (totalData > 0) { map.put(Check.status, true); map.put(Check.totalPage, searchPage.getTotalPages()); map.put(Check.message, "Search operation success!"); map.put(Check.result, elasticGalleryCategoryList); } else { map.put(Check.status, false); map.put(Check.message, "Could not find a result for your search!"); } } catch (NumberFormatException e) { map.put(Check.status, false); String error = "An error occurred during the search operation!"; System.err.println(e); Util.logger(error, GalleryCategory.class); map.put(Check.message, error); } return map; } // Category List @ResponseBody @GetMapping("/categoryList") public Map<Check, Object> categoryList() { Map<Check, Object> map = new LinkedHashMap<>(); map.put(Check.status, true); map.put(Check.message, "Gallery category list operations success!"); map.put(Check.result, galleryCategoryRepository.findAll()); return map; } // Gallery Add - Update @PostMapping("/add") @ResponseBody public Map<Check, Object> galleryAdd(@RequestBody @Valid Gallery gallery, BindingResult bindingResult) { System.out.println("okey"); Map<Check, Object> map = new LinkedHashMap<>(); if (!bindingResult.hasErrors()) { System.out.println("hata yok"); if (gallery.getId() != null) { System.out.println(gallery.getId()); Optional<Gallery> optionalGallery = galleryRepository.findById(gallery.getId()); if (optionalGallery.isPresent()) { try { Gallery gallery1 = galleryRepository.saveAndFlush(gallery); System.out.println("gallery1: " + gallery1); ElasticGallery elasticGallery = new ElasticGallery(); elasticGallery.setId(Integer.toString(gallery1.getId())); elasticGallery.setNo(Long.toString(gallery1.getNo())); elasticGallery.setTitle(gallery1.getTitle()); elasticGallery.setDescription(gallery1.getDescription()); elasticGallery.setStatus(gallery1.getStatus()); elasticGallery.setDate(gallery1.getDate()); elasticGallery.setCategoryName(gallery1.getGalleryCategory().getName()); elasticGallery.setCategoryId(Integer.toString(gallery1.getGalleryCategory().getId())); elasticGalleryRepository.save(elasticGallery); map.put(Check.status, true); map.put(Check.message, "Updated operations success!"); map.put(Check.result, gallery); } catch (Exception ex) { System.err.println("Elastic Gallery Update: " + ex); } } } else { try { System.out.println("galleryAddController"); Gallery gallery1 = galleryRepository.saveAndFlush(gallery); map.put(Check.status, true); map.put(Check.message, "Adding of Gallery Operations Successful!"); map.put(Check.result, gallery); ElasticGallery elasticGallery = new ElasticGallery(); elasticGallery.setId(Integer.toString(gallery1.getId())); elasticGallery.setNo(Long.toString(gallery1.getNo())); elasticGallery.setTitle(gallery1.getTitle()); elasticGallery.setDescription(gallery1.getDescription()); elasticGallery.setStatus(gallery1.getStatus()); elasticGallery.setDate(gallery1.getDate()); elasticGallery.setCategoryName(gallery1.getGalleryCategory().getName()); elasticGallery.setCategoryId(Integer.toString(gallery1.getGalleryCategory().getId())); elasticGalleryRepository.save(elasticGallery); } catch (Exception ex) { System.out.println("galleryAddControllerError"); map.put(Check.status, false); if (ex.toString().contains("constraint")) { String error = "This gallery name has already been registered!"; Util.logger(error, Gallery.class); map.put(Check.message, error); } } } } else { map.put(Check.status, false); map.put(Check.errors, Util.errors(bindingResult)); } return map; } //List of Gallery with pagination @ResponseBody @GetMapping("/gallerylist/{stShowNumber}/{stPageNo}") public Map<Check, Object> listGallery(@PathVariable String stShowNumber, @PathVariable String stPageNo) { Map<Check, Object> map = new LinkedHashMap<>(); //System.out.println(stShowNumber + " " + stPageNo); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo, showNumber); Page<ElasticGallery> galleryPage = elasticGalleryRepository.findByOrderByIdAsc(pageable); map.put(Check.status, true); map.put(Check.totalPage, galleryPage.getTotalPages()); map.put(Check.message, "Gallery listing on page " + (pageNo + 1) + " is successful"); map.put(Check.result, galleryPage.getContent()); } catch (Exception e) { map.put(Check.status, false); String error = "An error occurred during the operation!"; System.err.println(e); Util.logger(error, Gallery.class); map.put(Check.message, error); } return map; } // Get id data from Choosen Gallery @ResponseBody @GetMapping("/chosenId/{stId}") public int chosenId(@PathVariable String stId) { try { int id = Integer.parseInt(stId); Optional<Gallery> optionalGallery = galleryRepository.findById(id); if (optionalGallery.isPresent()) { chosenId = id; } } catch (Exception e) { System.err.println("Chosen Id Error: " + e); } System.out.println("Resim eklemek için seçilen ürünün ıd numarası: " + chosenId); return chosenId; } // Add Gallery Images @PostMapping("/imageUpload") public String imageUpload(@RequestParam("imageName") MultipartFile[] files) { System.out.println(chosenId); Optional<Gallery> optionalGallery = galleryRepository.findById(chosenId); List<String> imageNameList = new ArrayList<>(); File f = new File(Util.UPLOAD_DIR_GALLERY + ("" + chosenId)); boolean isDeleted = f.delete(); if (optionalGallery.isPresent()) { Gallery gallery = optionalGallery.get(); if (files != null && files.length != 0) { sendCount = files.length; String idFolder = "" + chosenId + "/"; File folderGallery = new File(Util.UPLOAD_DIR_GALLERY + idFolder); boolean status = folderGallery.mkdir(); for (MultipartFile file : files) { Map<Check, Object> imgResult = Util.imageUpload(file, Util.UPLOAD_DIR_GALLERY + idFolder); imageNameList.add(imgResult.get(Check.message).toString()); } gallery.setFileName(imageNameList); galleryRepository.saveAndFlush(gallery); Optional<ElasticGallery> elasticGalleryOptional = elasticGalleryRepository.findById(Integer.toString(gallery.getId())); if (elasticGalleryOptional.isPresent()) { ElasticGallery elasticGallery = elasticGalleryOptional.get(); elasticGallery.setFileName(imageNameList); elasticGalleryRepository.save(elasticGallery); } else { errorMessage = "Elastic Gallery is not found"; } } else { errorMessage = "Please choose an image"; System.err.println(errorMessage); } } else { errorMessage = "Gallery is not found"; System.err.println(errorMessage); } return "redirect:/gallery"; } //Detail of Gallery @ResponseBody @GetMapping("/detail/{stId}") public Map<Check, Object> detailGallery(@PathVariable String stId) { Map<Check, Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); map.put(Check.status, true); map.put(Check.message, "Gallery detail operation is successful!"); map.put(Check.result, galleryRepository.findById(id).get()); } catch (Exception e) { map.put(Check.status, false); String error = "An error occurred during the operation!"; System.err.println(e); Util.logger(error, Gallery.class); map.put(Check.message, error); } return map; } //Gallery delete @ResponseBody @DeleteMapping("/delete/{stId}") public Map<Check, Object> deleteGallery(@PathVariable String stId) { Map<Check, Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); Optional<Gallery> optionalGallery = galleryRepository.findById(id); if (optionalGallery.isPresent()) { //Images Delete Gallery gallery = optionalGallery.get(); gallery.getFileName().forEach(item -> { File file = new File(Util.UPLOAD_DIR_GALLERY + stId + "/" + item); file.delete(); }); File file = new File(Util.UPLOAD_DIR_GALLERY + stId); if (file.exists()) { file.delete(); } //Images Delete ElasticGallery elasticGallery = elasticGalleryRepository.findById(Integer.toString(id)).get(); galleryRepository.deleteById(id); elasticGalleryRepository.deleteById(elasticGallery.getId()); map.put(Check.status, true); map.put(Check.message, "Data has been deleted!"); map.put(Check.result, optionalGallery.get()); } else { String error = "Gallery is not found"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, Gallery.class); } } catch (Exception e) { String error = "An error occurred during the delete operation"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, Gallery.class); System.err.println(e); } return map; } //Elasticsearch for GAllery @ResponseBody @GetMapping("/search/{data}/{stPageNo}/{stShowNumber}") public Map<Check, Object> searchGallery(@PathVariable String data, @PathVariable String stPageNo, @PathVariable String stShowNumber) { Map<Check, Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo, showNumber); Page<ElasticGallery> searchPage = elasticGalleryRepository.findBySearchData(data, pageable); List<ElasticGallery> elasticGalleryList = searchPage.getContent(); int totalData = elasticGalleryList.size(); //for total data in table if (totalData > 0) { map.put(Check.status, true); map.put(Check.totalPage, searchPage.getTotalPages()); map.put(Check.message, "Search operation success!"); map.put(Check.result, elasticGalleryList); } else { map.put(Check.status, false); map.put(Check.message, "Could not find a result for your search!"); } } catch (NumberFormatException e) { map.put(Check.status, false); String error = "An error occurred during the search operation!"; System.err.println(e); Util.logger(error, Gallery.class); map.put(Check.message, error); } return map; } //Chosen image delete @ResponseBody @DeleteMapping("/chosenImages/delete/{images}") public Map<Check, Object> deleteChosenImage(@PathVariable List<String> images) { Map<Check, Object> map = new LinkedHashMap<>(); try { if (images.size() > 0) { for (int i = 0; i < images.size(); i++) { System.out.println("Silinmek istenen dosya: " + images.get(i)); galleryRepository.deleteImageByFileName(images.get(i)); File file = new File(Util.UPLOAD_DIR_GALLERY + chosenId + "/" + images.get(i)); file.delete(); } //Elasticsearch update images - Start Gallery gallery = galleryRepository.findById(chosenId).get(); System.out.println("Id ye ait resimler " + gallery.getFileName()); ElasticGallery elasticGallery = elasticGalleryRepository.findById(Integer.toString(chosenId)).get(); elasticGallery.setFileName(gallery.getFileName()); elasticGalleryRepository.save(elasticGallery); //Elasticsearch update images - End map.put(Check.status, true); map.put(Check.message, "The selected pictures have been deleted!"); } else { map.put(Check.status, false); map.put(Check.message, "Please select a picture!"); } } catch (Exception e) { String error = "An error occurred during the image delete operation"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, Gallery.class); System.err.println(e); } return map; } @GetMapping("/galleryDetail/get_image/id={id}name={name}") public void getImage(@PathVariable Integer id, @PathVariable String name, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg; image/jpg; image/png"); File file = new File(Util.UPLOAD_DIR_GALLERY + id + "/" + name); if (file.exists()) { System.out.println(file.exists()); byte[] fileContent = FileUtils.readFileToByteArray(file); response.getOutputStream().write(fileContent); } else { File defaultFile = new File(Util.UPLOAD_DIR_GALLERY + "default_image.jpg"); byte[] defaultFileContent = FileUtils.readFileToByteArray(defaultFile); response.getOutputStream().write(defaultFileContent); } response.getOutputStream().close(); } } <file_sep>package companyAll_MVC.repositories._elastic; import companyAll_MVC.documents.ElasticNews; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; public interface ElasticNewsRepository extends ElasticsearchRepository<ElasticNews,String > { @Query("{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}}") Page<ElasticNews> findByOrderByIdAsc(Pageable pageable); @Query("{\"bool\":{\"must\":[],\"must_not\":[],\"should\":[{\"prefix\":{\"categoryName\":\"?0\"}},{\"prefix\":{\"status\":\"?0\"}},{\"prefix\":{\"description\":\"?0\"}},{\"prefix\":{\"no\":\"?0\"}},{\"prefix\":{\"summary\":\"?0\"}},{\"prefix\":{\"title\":\"?0\"}}]}}") Page<ElasticNews> findBySearchData(String data, Pageable pageable); @Query("{\"bool\":{\"must\":[{\"match\":{\"categoryId\":\"?0\"}}],\"must_not\":[],\"should\":[]}}") Page<ElasticNews> findByNewsCategoryIdEquals(Integer categoryId,Pageable pageable); //Number of news by news status long countByStatusAllIgnoreCase(String status); //All news @Query("{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}},\"aggs\":{}") List<ElasticNews> allNews(); } <file_sep>package companyAll_MVC.repositories._elastic; import companyAll_MVC.documents.ElasticAddress; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.Optional; public interface ElasticAddressRepository extends ElasticsearchRepository<ElasticAddress, String> { @Query("{\"bool\":{\"must\":[{\"term\":{\"aid\":\"?0\"}}],\"must_not\":[],\"should\":[]}}") Optional<ElasticAddress> findByAid(Integer aid); } <file_sep>package companyAll_MVC.repositories._elastic; import companyAll_MVC.documents.ElasticAnnouncement; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; import java.util.Optional; public interface ElasticAnnouncementRepository extends ElasticsearchRepository<ElasticAnnouncement, String> { @Query("{\"bool\":{\"must\":[{\"term\":{\"aid\":\"?0\"}}],\"must_not\":[],\"should\":[]}}") Optional<ElasticAnnouncement> findByAid(Integer cid); @Query("{\"bool\":{\"should\":[{\"match\":{\"status\":\"?0\"}}],\"must_not\":[]}}") List<ElasticAnnouncement> findAllByStatus(String status); @Query("{\"bool\":{\"should\":[{\"match\":{\"status\":\"?0\"}}],\"must_not\":[]}}") Page<ElasticAnnouncement> findAllByStatus(String status, Pageable pageable); @Query("{\"bool\":{\"should\":[{\"prefix\":{\"no\":\"?0\"}},{\"prefix\":{\"title\":\"?0\"}}, " + "{\"prefix\":{\"detail\":\"?0\"}}," + "{\"prefix\":{\"status\":\"?1\"}}" + "],\"must_not\":[]}}") List<ElasticAnnouncement> searchByKeyAndStatus(String key, String status); @Query("{\"bool\":{\"should\":[{\"prefix\":{\"no\":\"?0\"}},{\"prefix\":{\"title\":\"?0\"}}, " + "{\"prefix\":{\"detail\":\"?0\"}}," + "{\"prefix\":{\"status\":\"?1\"}}" + "],\"must_not\":[]}}") Page<ElasticAnnouncement> searchByKeyAndStatus(String key, String status, Pageable pageable); } <file_sep>function getAllOrdersByPage(page, size) { $.ajax({ url: '/order/all' + '/status=' + selectedOrderStatus + '/page=' + page + 'size=' + size, type: 'GET', dataType: 'Json', success: function (data) { console.log(data.result) createOrderTable(data.result); dynamicPagination(data.totalPage, size); }, error: function (err) { console.log(err) } }) } function searchOrderByKey(key, page, size) { $.ajax({ url: '/order/search' + '/key=' + key + '/status=' + selectedOrderStatus + '/page=' + page + 'size=' + size, type: 'GET', dataType: 'Json', success: function (data) { createOrderTable(data.result); dynamicPagination(data.totalPage, size); }, error: function (err) { console.log(err) } }) } function dynamicPagination(totalPage, size) { $('#order_pagination').twbsPagination({ totalPages: totalPage, visiblePages: 5, prev: 'Prev', first: 'First', last: 'Last', startPage: 1, onPageClick: function (event, page) { if ($('#order_search').val() === "") { getAllOrdersByPage(page - 1, size); } else { searchOrderByKey($('#order_search').val(), page - 1, $('#order_pagesize').val()); } //$('#firstLast1-content').text('You are on Page ' + page); $('.pagination').find('li').addClass('page-item'); $('.pagination').find('a').addClass('page-link'); } }); } function getOrder(iid, index) { $.ajax({ url: '/order/get' + '/id=' + iid, type: 'GET', dataType: 'Json', success: function (data) { if (data.status === true) { selectedOrder = data.result; if (index === 1) { //product createProductModal(); } if (index === 2) { //address createAddressModal(); } } else { console.log(data.message); } }, error: function (err) { console.log(err) } }) return {}; } function deleteOrder(iid) { Swal.fire({ title: 'Are you sure?', text: "This order will be permanently deleted!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Delete', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: '/order/delete/id=' + iid, type: 'DELETE', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (data.status === true) { Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); selectedOrder = {}; $('#order_pagination').twbsPagination('destroy'); getAllOrdersByPage(0, $('#order_pagesize').val()); } else { Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } function changeOrderStatus(iid, statusInt) { let url; let text; let confirmButtonText; let successTitle; if(statusInt === 1){ //Deliver url = '/order/change-status/id=' + iid + 'status=Delivered'; text = "This order will be set as delivered.!"; confirmButtonText = "Deliver"; successTitle = "Delivered!" }else if(statusInt === 0){ //Undeliver url = '/order/change-status/id=' + iid + 'status=Active'; text = "This order will be set as active.!"; confirmButtonText = "Undeliver"; successTitle = "Undelivered!" }else{ return; } Swal.fire({ title: 'Are you sure?', text: text, icon: 'warning', showCancelButton: true, confirmButtonText: confirmButtonText, customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: url, type: 'GET', dataType: 'json', success: function (data) { if( data.status === true){ Swal.fire({ icon: 'success', title: successTitle, text: data.message, customClass: { confirmButton: 'btn btn-success' } }); selectedOrder = {}; $('#order_pagination').twbsPagination('destroy'); getAllOrdersByPage(0, $('#order_pagesize').val()); }else{ Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } function createOrderTable(orders) { let html = ``; let statusHtml = ``; let statusInt; for (let i = 0; i < orders.length; i++) { const order = orders[i]; let status = order.status; if(status === "Active"){ statusInt = 1; statusHtml = `<button type="button" class="btn btn-sm btn-outline-success" onclick="changeOrderStatus(` + order.iid + `, `+statusInt+`)"> <i class="fas fa-check-circle" style="font-size: 20px;"></i> </button>`; } if(status === "Delivered"){ statusInt = 0; statusHtml = `<button type="button" class="btn btn-sm btn-outline-danger" onclick="changeOrderStatus(` + order.iid + `, `+statusInt+`)"> <i class="fas fa-ban" style="font-size: 20px;"></i> </button>`; } html += ` <tr> <td>` + order.no + `</td> <td>` + order.cno + `</td> <td>` + order.cname + `</td> <td>` + order.pno + `</td> <td> <button type="button" class="btn btn-sm" onClick="getOrder(` + order.iid + `, ` + 1 + `)"> <i class="far fa-file-alt" style="font-size: 20px;"></i> </button> </td> <td>` + order.date + `</td> <td> <button type="button" class="btn btn-sm" onClick="getOrder(` + order.iid + `, ` + 2 + `)"> <i class="far fa-file-alt" style="font-size: 20px;"></i> </button> </td> <td> <button type="button" class="btn btn-sm btn-outline-danger" onclick="deleteOrder(` + order.iid + `)"> <i class="far fa-trash-alt" style="font-size: 20px; width: 13px;"></i> </button> </td> <td> `+statusHtml+` </td> </tr>`; } $('#tBodyOrders').html(html); } function createProductModal() { let html = ``; const product = selectedOrder.product; const imageArr = product.fileName; for (let i = 0; i < imageArr.length; i++) { const image = imageArr[i]; html += ` <div class="swiper-slide"> <img src="/productDetail/get_image/id=${product.id}name=${image}" class="img-fluid" alt="banner" /> </div>`; } const buttonHtml = `<button onclick='window.location.href="/productDetail/${product.id}"' class="btn btn-outline-primary">Details</button>`; $('#order_product_image_slider').html(html); $('#order_product_button_div').html(buttonHtml); $('#order_product_modal_title').text("Product No : " + product.no); $('#order_product_title').text(product.name); $('#order_product_detail').text(product.details); $('#order_product_modal').modal('toggle'); } function createAddressModal() { const address = selectedOrder.customer.addresses[selectedOrder.adressIndex]; $("#order_address_type").text("Type : " + address.type); $("#order_address_detail").text(address.detail); $("#order_address_modal_title").text("Order No : " + selectedOrder.no); $('#order_address_modal').modal('toggle'); } $('#order_pagesize').change(function () { if($('#order_search').val() === ""){ $('#order_pagination').twbsPagination('destroy'); getAllOrdersByPage(0, parseInt($(this).val())); }else{ searchOrderByKey($('#order_search').val(), page-1, $('#order_pagesize').val()); } }); $('#order_status').change(function () { selectedOrderStatus = $(this).val(); $("#tBodyOrders > tr").remove(); getAllOrdersByPage(0, $('#order_pagesize').val()); }); $('#order_search').keyup(function (event) { event.preventDefault(); const key = $(this).val(); if (key !== "") { $("#tBodyOrders > tr").remove(); $('#order_pagination').twbsPagination('destroy'); searchOrderByKey(key, 0, $('#order_pagesize').val()); } else { $('#order_pagination').twbsPagination('destroy'); getAllOrdersByPage(0, $('#order_pagesize').val()); } }); let selectedOrder = {}; let selectedOrderStatus = "Active"; $('#order_pagination').twbsPagination('destroy'); getAllOrdersByPage(0, 10); <file_sep>package companyAll_MVC.entities; import lombok.Data; import javax.persistence.*; import java.util.List; @Entity @Data public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) private Integer id; private String name; @ManyToMany(mappedBy = "roles",cascade = CascadeType.DETACH) private List<User> users; } <file_sep>package companyAll_MVC.controllers; import companyAll_MVC.documents.ElasticIndent; import companyAll_MVC.documents.ElasticProduct; import companyAll_MVC.documents.ElasticProductCategory; import companyAll_MVC.entities.Announcement; import companyAll_MVC.entities.Product; import companyAll_MVC.repositories._elastic.*; import companyAll_MVC.repositories._jpa.AnnouncementRepository; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Statics; import companyAll_MVC.utils.Util; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.*; @Controller @RequestMapping("/dashboard") public class DashboardController { final ElasticLikesRepository elasticLikesRepository; final ElasticCustomerRepository elasticCustomerRepository; final ElasticIndentRepository elasticIndentRepository; final ElasticContentsRepository elasticContentsRepository; final ElasticProductRepository elasticProductRepository; final ElasticAnnouncementRepository elasticAnnouncementRepository; final ElasticProductCategoryRepository elasticProductCategoryRepository; final ElasticNewsRepository elasticNewsRepository; final AnnouncementRepository announcementRepository; public DashboardController(ElasticLikesRepository elasticLikesRepository, ElasticCustomerRepository elasticCustomerRepository, ElasticIndentRepository elasticIndentRepository, ElasticContentsRepository elasticContentsRepository, ElasticProductRepository elasticProductRepository, ElasticAnnouncementRepository elasticAnnouncementRepository, ElasticProductCategoryRepository elasticProductCategoryRepository, ElasticNewsRepository elasticNewsRepository, AnnouncementRepository announcementRepository) { this.elasticLikesRepository = elasticLikesRepository; this.elasticCustomerRepository = elasticCustomerRepository; this.elasticIndentRepository = elasticIndentRepository; this.elasticContentsRepository = elasticContentsRepository; this.elasticProductRepository = elasticProductRepository; this.elasticAnnouncementRepository = elasticAnnouncementRepository; this.elasticProductCategoryRepository = elasticProductCategoryRepository; this.elasticNewsRepository = elasticNewsRepository; this.announcementRepository = announcementRepository; } @GetMapping("") public String dashboard(Model model){ model.addAttribute("activeNews",elasticNewsRepository.countByStatusAllIgnoreCase("Active")); model.addAttribute("passiveNews",elasticNewsRepository.countByStatusAllIgnoreCase("Passive")); model.addAttribute("totalNews",elasticNewsRepository.allNews().size()); return "dashboard"; } //News Chart @ResponseBody @GetMapping("/newsChart") public Map<Statics,Object> newsChart(){ Map<Statics,Object> map = new LinkedHashMap<>(); map.put(Statics.status,true); map.put(Statics.message,"News statics information listing operation success!"); map.put(Statics.activeNews,elasticNewsRepository.countByStatusAllIgnoreCase("Active")); map.put(Statics.passiveNews,elasticNewsRepository.countByStatusAllIgnoreCase("Passive")); map.put(Statics.totalNews,elasticNewsRepository.allNews().size()); return map; } //General Statics @ResponseBody @GetMapping("/generalStatics") public Map<Statics,Object> generalStatics(){ Map<Statics,Object> map = new LinkedHashMap<>(); map.put(Statics.status,true); map.put(Statics.message,"General statics information listing operation success!"); map.put(Statics.totalLikes,elasticLikesRepository.allLikes().size()); map.put(Statics.totalCustomers,elasticCustomerRepository.allCustomers().size()); map.put(Statics.totalOrders,elasticIndentRepository.allOrders().size()); map.put(Statics.totalContents,elasticContentsRepository.allContents().size()); return map; } //Last Added 6 Product @ResponseBody @GetMapping("/lastAddSixProduct") public Map<Statics,Object> lastAddSixProduct(){ Map<Statics,Object> map = new LinkedHashMap<>(); Pageable pageable = PageRequest.of(0,6); Page<ElasticProduct> elasticProductPage = elasticProductRepository.findByOrderByProductIdDesc(pageable); map.put(Statics.status,true); map.put(Statics.message,"Last added 6 product information listing operation success!"); map.put(Statics.lastAddedSixProduct,elasticProductPage.getContent()); return map; } //Last Six Orders @ResponseBody @GetMapping("/lastSixOrder") public Map<Statics,Object> lastSixOrder(){ Map<Statics,Object> map = new LinkedHashMap<>(); Pageable pageable = PageRequest.of(0,6); Page<ElasticIndent> elasticIndentPage = elasticIndentRepository.findAllByOrderByIidDesc(pageable); map.put(Statics.status,true); map.put(Statics.message,"Last 6 order information listing operation success!"); map.put(Statics.lastSixOrder,elasticIndentPage.getContent()); return map; } //Chosen Product Detail @ResponseBody @GetMapping("/chosenProductDetail/{stId}") public Map<Check,Object> chosenProductDetail(@PathVariable String stId){ Map<Check,Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); Optional<ElasticProduct> elasticProductOptional = elasticProductRepository.findById(id); if(elasticProductOptional.isPresent()){ map.put(Check.status,true); map.put(Check.message,"Product listing operation is success!"); map.put(Check.result,elasticProductOptional.get()); }else{ map.put(Check.status,false); map.put(Check.message,"Product is not found!"); } } catch (NumberFormatException e) { String error = "An error occurred during the operation!"; map.put(Check.status, false); map.put(Check.message, error); Util.logger(error, Product.class); System.err.println(e); } return map; } //Category Info @ResponseBody @GetMapping("/productCategoryInfo/{stId}") public Map<Check,Object> productCategoryInfo(@PathVariable String stId){ Map<Check,Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); Optional<ElasticProductCategory> productCategoryOptional = elasticProductCategoryRepository.findById(id); if(productCategoryOptional.isPresent()){ map.put(Check.status,true); map.put(Check.message,"Product category information listing operations success!"); map.put(Check.result,productCategoryOptional.get()); }else { map.put(Check.status,false); map.put(Check.message,"Product category is not found!"); } } catch (Exception e) { System.err.println(e); } return map; } //All Categories @ResponseBody @GetMapping("/allProductCategories") public Map<Check,Object> allProductCategories(){ Map<Check,Object> map = new LinkedHashMap<>(); List<ElasticProductCategory> elasticProductCategoryList = elasticProductCategoryRepository.findAllByOrderByCategoryIdAsc(); map.put(Check.status,true); map.put(Check.message,"All Product category listing operations success!"); map.put(Check.result,elasticProductCategoryList); return map; } //Total product by Category Id @ResponseBody @GetMapping("/totalProductByCategoryId/{stId}") public Map<Check,Object> totalProductByCategoryId(@PathVariable String stId){ Map<Check,Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); List<ElasticProduct> elasticProductList = elasticProductRepository.findByProductCategoryIdEquals(id); map.put(Check.status,true); map.put(Check.message,"Total Product by category Id listing operations success!"); map.put(Check.result,elasticProductList.size()); } catch (NumberFormatException e) { map.put(Check.status, false); map.put(Check.message, "An error occurred in total product by category Id listing operation!"); } return map; } //Daily Announcment List @ResponseBody @GetMapping("/dailyAnnouncment/{stPageNo}") public Map<Check,Object> dailyAnnouncment(@PathVariable String stPageNo){ Map<Check,Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); String[] date = Util.getDateFormatter().split(" "); Pageable pageable = PageRequest.of(pageNo,1); Page<Announcement> announcementPage = announcementRepository.findByDateContainsIgnoreCaseOrderByIdAsc(date[0],pageable); //System.out.println(announcementPage.getContent()); map.put(Check.status,true); map.put(Check.message,"Daily Announcment Listing Operation Success!"); map.put(Check.totalPage,announcementPage.getTotalPages()); map.put(Check.result,announcementPage.getContent()); } catch (Exception e) { String error = "An error occurred in Daily Announcment Listing listing operation!"; map.put(Check.status, false); map.put(Check.message,error); System.err.println(e); Util.logger(error, Announcement.class); } return map; } } <file_sep>package companyAll_MVC.repositories._elastic; import companyAll_MVC.documents.ElasticNewsCategory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.Optional; public interface ElasticNewsCategoryRepository extends ElasticsearchRepository<ElasticNewsCategory,String> { @Query("{\"bool\":{\"must\":[{\"term\":{\"categoryId\":\"?0\"}}],\"must_not\":[],\"should\":[]}}") Optional<ElasticNewsCategory> findById(Integer categoryId); @Query("{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}}") Page<ElasticNewsCategory> findByOrderByIdAsc(Pageable pageable); @Query("{\"bool\":{\"must\":[],\"must_not\":[],\"should\":[{\"prefix\":{\"date\":\"?0\"}},{\"prefix\":{\"detail\":\"?0\"}},{\"prefix\":{\"name\":\"?0\"}},{\"prefix\":{\"no\":\"?0\"}},{\"prefix\":{\"status\":\"?0\"}},{\"prefix\":{\"subname\":\"?0\"}}]}}") Page<ElasticNewsCategory> findBySearchData(String data, Pageable pageable); } <file_sep>$('#survey_pagination').twbsPagination('destroy'); getAllSurveysByPage(1, $("#survey_pagesize").val()); // Functions - Start function noGenerator() { const date = new Date(); const time = date.getTime(); const key = time.toString().substring(4); return key; } function fncDate() { const d = new Date(); const ye = new Intl.DateTimeFormat('tr', {year: 'numeric'}).format(d) const mo = new Intl.DateTimeFormat('tr', {month: '2-digit'}).format(d) const da = new Intl.DateTimeFormat('tr', {day: '2-digit'}).format(d) const date = `${da}-${mo}-${ye}` return date; } function fncReset() { $("#surveyForm").trigger("reset") select_id = 0 } // Functions - End /*------------------------------ Survey Add - Start ------------------------------*/ let select_id = 0 let globalArrSurvey = [] var success = $('#type-success'); if (success.length) { $('#surveyForm').submit((event) => { event.preventDefault() console.log("tıklandı"); const title = $("#title").val() const detail = $("#detail").val() const status = $("#status").val() const obj = { title: title, detail: detail, status: status == 1 ? "Active" : "Passive", no: noGenerator(), date: fncDate(), } if (select_id != 0) { // update obj["id"] = select_id; } $.ajax({ url: './surveys/add', type: 'POST', data: JSON.stringify(obj), dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (data.status == true && data.result != null) { Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonStyling: false }); getAllSurveysByPage(0, 10); } else if (data.status == true && data.result == null) { Swal.fire({ title: "Warning!", text: "Returned Data is Empty!", icon: "Warning", customClass: { confirmButton: 'btn btn-primary' }, buttonStyling: false }); } else { Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonStyling: false }); } console.log(data); fncReset(); }, error: function (err) { Swal.fire({ title: "Error!", text: "An Error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonStyling: false }); console.log(err) } }) }); /*------------------------------ Survey Data To Table - Start ------------------------------*/ function createRowToTable(data) { let html = `` console.log("createRowToTable") console.log(data) data.forEach((row) => { html += `<tr role="row" class="odd"> <td>` + row.no + `</td> <td>` + row.title + `</td> <td>` + row.detail + `</td> <td>` + row.status + `</td> <td>` + row.date + `</td> <td class="text-left"> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown"> <i class="fas fa-ellipsis-v"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" type="button" href="javascript:surveyUpdate(${row.id}) "> <i class="mr-50 fas fa-pen"></i> <span>Edit</span> </a> <a class="dropdown-item" href="javascript:surveyOption(${row.id})"> <i class="mr-50 fas fa-plus"></i> <span>Add Option</span> </a> <a class="dropdown-item" type="button" href="javascript:surveyDelete(${row.id})" > <i class="mr-50 far fa-trash-alt"></i> <span>Delete</span> </a> </div> </div> </td> </tr>`; }) $('#surveyTableBody').html(html); } /*------------------------------ Survey Data To Table - End ------------------------------*/ } /*------------------------------ Survey Add - Start ------------------------------*/ /*------------------------------ Survey List Pageble - Start ------------------------------*/ function getAllSurveysByPage(page, size) { $.ajax({ url: '/surveys/all/' + page + '/' + size, type: 'GET', dataType: 'Json', success: function (data) { createRowData(data) //createRowToTable(data.result); dynamicPagination(data.totalPage, size); globalArrSurvey = data.result; }, error: function (err) { console.log(err) } }) } /*------------------------------ Survey List Pageble - End ------------------------------*/ /*------------------------------ Survey Delete - Start ------------------------------*/ function surveyDelete(id) { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './surveys/delete/' + id, type: 'delete', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (id != null) { Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); getAllSurveysByPage(0, 10); } else { Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } /*------------------------------ Survey Delete - End ------------------------------*/ /*------------------------------ Survey Update - Start ------------------------------*/ function surveyUpdate(id) { $('#surveyAdd_modal').modal("toggle"); const itm = globalArrSurvey.find(item => id); console.log("itm : ", itm) select_id = itm.id; $("#title").val(itm.title); $("#detail").val(itm.detail); $("#status").val(itm.status == "Active" ? 1 : 2) $(window).scrollTop(0); } /*------------------------------ Survey Update - End ------------------------------*/ /*------------------------------ Survey List Pagination - Start ------------------------------*/ let globalArr=[] function dynamicPagination(totalPage, size) { $('#survey_pagination').twbsPagination({ totalPages: totalPage, visiblePages: 5, prev: 'Prev', first: 'First', last: 'Last', startPage: 1, onPageClick: function (event, page) { //console.log("Page click"); if($('#searchSurvey').val() === ""){ getAllSurveysByPage(page - 1, size); }else{ search(page,size,$('#searchSurvey').val()) } //$('#firstLast1-content').text('You are on Page ' + page); $('.pagination').find('li').addClass('page-item'); $('.pagination').find('a').addClass('page-link'); } }); } $('#survey_pagesize').change(function () { if($('#searchSurvey').val() === ""){ $('#survey_pagination').twbsPagination('destroy'); getAllSurveysByPage(0, parseInt($(this).val())); }else{ search( page, $('#survey_pagesize').val(),$('#searchSurvey').val()); } //console.log("Show number Change " + parseInt($(this).val())); }); getAllSurveysByPage(0, 10); /*------------------------------ Survey List Pagination - End ------------------------------*/ /*------------------------------------------------------------ SURVEY OPTİON - Start ------------------------------------------------------------*/ /*------------------------------ Survey Option Add - Start ------------------------------*/ var success1 = $('#type-success1'); if (success1.length) { $('#surveyOptionAddForm').submit((event) => { event.preventDefault() console.log(globalOptionId); const titleOption = $("#titleOption").val() const obj = { title: titleOption, date: fncDate(), no: noGenerator(), survey: { id: globalOptionId } } console.log(surveyOption.surveyId) $.ajax({ url: './surveysOption/add', type: 'POST', data: JSON.stringify(obj), dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (data.status === true && data.result != null) { Swal.fire({ title: 'Success!', text: data.message, icon: "success", customClass: { confirmButton: 'btn btn-primary' }, buttonStyling: false }); } else if (data.status == true && data.result == null) { Swal.fire({ title: "Warning!", text: "Returned Data is Empty!", icon: "Warning", customClass: { confirmButton: 'btn btn-primary' }, buttonStyling: false }); } else { Swal.fire({ title: 'Error!', text: data.message, icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonStyling: false }); } updateModal(globalOptionId) }, error: function (err) { Swal.fire({ title: "Error!", text: "An Error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonStyling: false }); console.log(err) } }) }); /*------------------------------ Survey Option Add - End ------------------------------*/ /*------------------------------ Survey Option List By SurveyId - Start ------------------------------*/ let globalOptionSurvey; function optionsBySurveyId(surveyId) { var output; $.ajax({ url: './surveysOption/list/' + surveyId, type: 'GET', contentType: 'application/json; charset=utf-8', async: false, success: function (data) { output = data; globalOptionSurvey = output; console.log("option data list:" + data); }, error: function (err) { console.log("allBuy Error : " + err) } }) return output; } /*------------------------------ Survey Option List By SurveyId - End ------------------------------*/ /*------------------------------ Survey Option Add Table - Start ------------------------------*/ var globalOptionId; function surveyOption(id) { optionsBySurveyId(id); globalOptionId = id; console.log(id); $(' #surveyOptionAdd_modal').modal("toggle"); let html = `` console.log(globalOptionSurvey) globalOptionSurvey.forEach((row) => { html += `<tr role="row" class="odd"> <td>` + row.survey.title + `</td> <td>` + row.title + `</td> <td>` + row.vote + `</td> <td class="text-left"> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown"> <i class="fas fa-ellipsis-v"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" type="button" href="javascript:surveyOptionDelete(${row.id})" > <i class="mr-50 far fa-trash-alt"></i> <span>Delete</span> </a> </div> </div> </td> </tr>`; }) $('#surveyOptionTableBody').html(html); } /*------------------------------ Survey Option Add Table - End ------------------------------*/ /*------------------------------ Survey Option Modal Update(add-delete => Refresh) - Start ------------------------------*/ function updateModal(globalOptionId) { optionsBySurveyId(globalOptionId); let html = `` console.log(globalOptionSurvey) globalOptionSurvey.forEach((row) => { html += `<tr role="row" class="odd"> <td>` + row.survey.title + `</td> <td>` + row.title + `</td> <td>` + row.vote + `</td> <td class="text-left"> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown"> <i class="fas fa-ellipsis-v"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" type="button" href="javascript:surveyOptionDelete(${row.id})" > <i class="mr-50 far fa-trash-alt"></i> <span>Delete</span> </a> </div> </div> </td> </tr>`; }) $('#surveyOptionTableBody').html(html); } /*------------------------------ Survey Option Modal Update(add-delete => Refresh) - End ------------------------------*/ /*------------------------------ Survey Option Delete - Start ------------------------------*/ function surveyOptionDelete(id) { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it!', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-outline-danger ml-1' }, buttonsStyling: false }).then(function (result) { if (result.value) { $.ajax({ url: './surveysOption/delete/' + id, type: 'delete', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { if (id != null) { Swal.fire({ icon: 'success', title: "Deleted!", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); updateModal(globalOptionId) } else { Swal.fire({ icon: 'error', title: "Error", text: data.message, customClass: { confirmButton: 'btn btn-success' } }); } }, error: function (err) { Swal.fire({ icon: 'error', title: "Error", text: "An error occurred during the delete operation", customClass: { confirmButton: 'btn btn-success' } }); console.log(err) } }) } }); } } /*------------------------------ Survey Option Delete - End ------------------------------*/ /*------------------------------------------------------------ SURVEY OPTİON - End ------------------------------------------------------------*/ //-------------------------------------- Survey Search - Start --------------------------------------------// function search(page, showPageSize, searchData) { //console.log(searchData) $.ajax({ url: './surveys/search/' + searchData + "/" + (page - 1) + "/" + showPageSize, type: 'get', dataType: "json", contentType: 'application/json; charset=utf-8', success: function (data) { //console.log("Data result " + JSON.stringify(data)) createRowData(data) dynamicPagination(data.totalPage, showPageSize) }, error: function (err) { Swal.fire({ title: "Error!", text: "An error occurred during the operation!", icon: "error", customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); console.log(err) } }) } $('#searchSurvey').keyup(function (event) { event.preventDefault(); const searchData = $(this).val() console.log("Key " + searchData) if (searchData !== "") { $("#surveyTableBody > tr").remove() $('#survey_pagination').twbsPagination('destroy'); search(1, $("#survey_pagesize").val(), searchData) } else { $('#survey_pagination').twbsPagination('destroy'); getAllSurveysByPage(1, $("#survey_pagesize").val()); } }) //-------------------------------------- Survey Search - End ----------------------------------------------// //-------------------------------------- Survey Create Row - Start ------------------------------------------// function createRowData(data) { let html = `` //console.log("createRowData") //console.log(data) for (let i = 0; i < data.result.length; i++) { globalArr = data.result const itm = data.result[i] //console.log(itm.title + " " + itm.details) html += `<tr> <td>` + itm.no + `</td> <td>` + itm.title + `</td> <td>` + itm.detail + `</td> <td>` + itm.status + `</td> <td>` + itm.date + `</td> <td class="text-left"> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown"> <i class="fas fa-ellipsis-v"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" type="button" href="javascript:surveyUpdate(${itm.id}) "> <i class="mr-50 fas fa-pen"></i> <span>Edit</span> </a> <a class="dropdown-item" href="javascript:surveyOption(${itm.id})"> <i class="mr-50 fas fa-plus"></i> <span>Add Option</span> </a> <a class="dropdown-item" type="button" href="javascript:surveyDelete(${itm.id})" > <i class="mr-50 far fa-trash-alt"></i> <span>Delete</span> </a> </div> </div> </td> </tr>` } $("#surveyTableBody").html(html) } //-------------------------------------- Survey Create Row - End --------------------------------------------// <file_sep># Company-All-Project <NAME>, <NAME>, <NAME> <file_sep>package companyAll_MVC.dto; import companyAll_MVC.documents.ElasticProduct; import companyAll_MVC.documents.ElasticProductCategory; import companyAll_MVC.entities.Product; import companyAll_MVC.entities.ProductCategory; import companyAll_MVC.repositories._elastic.ElasticProductCategoryRepository; import companyAll_MVC.repositories._elastic.ElasticProductRepository; import companyAll_MVC.repositories._jpa.ProductCategoryRepository; import companyAll_MVC.repositories._jpa.ProductRepository; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Util; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.PathVariable; import javax.swing.text.html.Option; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @Service public class ProductDto { final ProductRepository productRepository; final ProductCategoryRepository productCategoryRepository; final ElasticProductCategoryRepository elasticProductCategoryRepository; final ElasticProductRepository elasticProductRepository; public ProductDto(ProductRepository productRepository, ProductCategoryRepository productCategoryRepository, ElasticProductCategoryRepository elasticProductCategoryRepository, ElasticProductRepository elasticProductRepository) { this.productRepository = productRepository; this.productCategoryRepository = productCategoryRepository; this.elasticProductCategoryRepository = elasticProductCategoryRepository; this.elasticProductRepository = elasticProductRepository; } //================================== Product Category Section - Start ==================================// //Product category List public Map<Check,Object> categoryList(@PathVariable String stShowNumber, @PathVariable String stPageNo){ Map<Check,Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo,showNumber); Page<ElasticProductCategory> categoryPage = elasticProductCategoryRepository.findByOrderByIdAsc(pageable); map.put(Check.status,true); map.put(Check.totalPage,categoryPage.getTotalPages()); map.put(Check.message, "Content listing on page " + (pageNo + 1) + " is successful"); map.put(Check.result,categoryPage.getContent()); } catch (Exception e) { map.put(Check.status,false); String error = "An error occurred during the operation!"; System.err.println(e); Util.logger(error, ProductCategory.class); map.put(Check.message,error); } return map; } //================================== Product Category Section - End ====================================// //================================== Product Section - Start ====================================// //Last added 10 product public Map<Check,Object> addedLast10product(){ Map<Check,Object> map = new LinkedHashMap<>(); map.put(Check.status,true); map.put(Check.message,"Last added 10 products listing operation success!"); Pageable pageable = PageRequest.of(0,10); Page<ElasticProduct> elasticProductPage = elasticProductRepository.findByOrderByProductIdDesc(pageable); map.put(Check.result,elasticProductPage.getContent()); return map; } //List of product with pagination public Map<Check, Object> listProductwithPagination(String stShowNumber,String stPageNo){ Map<Check,Object> map = new LinkedHashMap<>(); //System.out.println(stShowNumber + " " + stPageNo); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo,showNumber); Page<ElasticProduct> productPage = elasticProductRepository.findByOrderByIdAsc(pageable); map.put(Check.status,true); map.put(Check.totalPage,productPage.getTotalPages()); map.put(Check.message, "Product listing on page " + (pageNo + 1) + " is successful"); map.put(Check.result,productPage.getContent()); } catch (Exception e) { map.put(Check.status,false); String error = "An error occurred during the operation!"; System.err.println(e); Util.logger(error, Product.class); map.put(Check.message,error); } return map; } //Product List by Category Id public Map<Check,Object> productListByCategoryId(String stId,String stShowNumber,String stPageNo){ Map<Check,Object> map = new LinkedHashMap<>(); try { int categoryId = Integer.parseInt(stId); int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo,showNumber); Page<ElasticProduct> elasticProductPage = elasticProductRepository.findByProductCategoryIdEquals(categoryId,pageable); map.put(Check.status,true); map.put(Check.message,"Product list operation succesful!"); map.put(Check.totalPage,elasticProductPage.getTotalPages()); map.put(Check.result,elasticProductPage.getContent()); } catch (Exception e) { String error = "An error occurred during the operation!"; Util.logger(error, Product.class); map.put(Check.status,false); map.put(Check.message,error); System.err.println(e); } return map; } //Elasticsearch for product public Map<Check,Object> searchProduct(String data,String stPageNo,String stShowNumber){ Map<Check,Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); // .th number of page int showNumber = Integer.parseInt(stShowNumber); // Get the show number value Pageable pageable = PageRequest.of(pageNo,showNumber); Page<ElasticProduct> searchPage = elasticProductRepository.findBySearchDataMatch(data,pageable); List<ElasticProduct> elasticProductList = searchPage.getContent(); int totalData = elasticProductList.size(); //for total data in table if(totalData > 0 ){ map.put(Check.status,true); map.put(Check.totalPage,searchPage.getTotalPages()); map.put(Check.message,"Search operation success!"); map.put(Check.result,elasticProductList); }else{ map.put(Check.status,false); map.put(Check.message,"Could not find a result for your search!"); } } catch (NumberFormatException e) { map.put(Check.status,false); String error = "An error occurred during the search operation!"; System.err.println(e); Util.logger(error, Product.class); map.put(Check.message,error); } return map; } //Product detail public Map<Check,Object> detail(String stId){ Map<Check,Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); Optional<ElasticProduct> elasticProductOptional = elasticProductRepository.findById(id); if(elasticProductOptional.isPresent()){ ElasticProduct elasticProduct = elasticProductOptional.get(); map.put(Check.status,true); map.put(Check.message,"Product detail operation success!"); map.put(Check.result,elasticProduct); }else { map.put(Check.status,false); map.put(Check.message,"Product detail is not found!"); } } catch (Exception e) { map.put(Check.status,false); String error = "An error occurred during the search operation!"; System.err.println(e); Util.logger(error, Product.class); map.put(Check.message,error); } return map; } //================================== Product Section - End ======================================// } <file_sep>package companyAll_MVC.dto; import companyAll_MVC.documents.ElasticIndent; import companyAll_MVC.documents.ElasticProduct; import companyAll_MVC.entities.Announcement; import companyAll_MVC.repositories._elastic.*; import companyAll_MVC.repositories._jpa.AnnouncementRepository; import companyAll_MVC.utils.Check; import companyAll_MVC.utils.Statics; import companyAll_MVC.utils.Util; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Service public class DashboardDto { final ElasticLikesRepository elasticLikesRepository; final ElasticCustomerRepository elasticCustomerRepository; final ElasticIndentRepository elasticIndentRepository; final ElasticContentsRepository elasticContentsRepository; final ElasticProductRepository elasticProductRepository; final ElasticAnnouncementRepository elasticAnnouncementRepository; final ElasticProductCategoryRepository elasticProductCategoryRepository; final AnnouncementRepository announcementRepository; final ElasticNewsRepository elasticNewsRepository; public DashboardDto(ElasticLikesRepository elasticLikesRepository, ElasticCustomerRepository elasticCustomerRepository, ElasticIndentRepository elasticIndentRepository, ElasticContentsRepository elasticContentsRepository, ElasticProductRepository elasticProductRepository, ElasticAnnouncementRepository elasticAnnouncementRepository, ElasticProductCategoryRepository elasticProductCategoryRepository, AnnouncementRepository announcementRepository, ElasticNewsRepository elasticNewsRepository) { this.elasticLikesRepository = elasticLikesRepository; this.elasticCustomerRepository = elasticCustomerRepository; this.elasticIndentRepository = elasticIndentRepository; this.elasticContentsRepository = elasticContentsRepository; this.elasticProductRepository = elasticProductRepository; this.elasticAnnouncementRepository = elasticAnnouncementRepository; this.elasticProductCategoryRepository = elasticProductCategoryRepository; this.announcementRepository = announcementRepository; this.elasticNewsRepository = elasticNewsRepository; } //News Chart public Map<Statics,Object> newsChart(){ Map<Statics,Object> map = new LinkedHashMap<>(); map.put(Statics.status,true); map.put(Statics.message,"News statics information listing operation success!"); map.put(Statics.activeNews,elasticNewsRepository.countByStatusAllIgnoreCase("Active")); map.put(Statics.passiveNews,elasticNewsRepository.countByStatusAllIgnoreCase("Passive")); map.put(Statics.totalNews,elasticNewsRepository.allNews().size()); return map; } //General Statics Information public Map<Statics,Object> generalStatics(){ Map<Statics,Object> map = new LinkedHashMap<>(); map.put(Statics.status,true); map.put(Statics.message,"General statics information listing operation success!"); map.put(Statics.totalLikes,elasticLikesRepository.allLikes().size()); map.put(Statics.totalCustomers,elasticCustomerRepository.allCustomers().size()); map.put(Statics.totalOrders,elasticIndentRepository.allOrders().size()); map.put(Statics.totalContents,elasticContentsRepository.allContents().size()); return map; } //Last Added 6 Product public Map<Statics,Object> lastAddSixProduct(){ Map<Statics,Object> map = new LinkedHashMap<>(); Pageable pageable = PageRequest.of(0,8); Page<ElasticProduct> elasticProductPage = elasticProductRepository.findByOrderByProductIdDesc(pageable); map.put(Statics.status,true); map.put(Statics.message,"Last added 6 product information listing operation success!"); map.put(Statics.lastAddedSixProduct,elasticProductPage.getContent()); return map; } //Last Six Order public Map<Statics,Object> lastSixOrder(){ Map<Statics,Object> map = new LinkedHashMap<>(); Pageable pageable = PageRequest.of(0,8); Page<ElasticIndent> elasticIndentPage = elasticIndentRepository.findAllByOrderByIidDesc(pageable); map.put(Statics.status,true); map.put(Statics.message,"Last 6 order information listing operation success!"); map.put(Statics.lastSixOrder,elasticIndentPage.getContent()); return map; } //Total product by Category Id public Map<Check,Object> totalProductByCategoryId(String stId){ Map<Check,Object> map = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); List<ElasticProduct> elasticProductList = elasticProductRepository.findByProductCategoryIdEquals(id); map.put(Check.status,true); map.put(Check.message,"Total Product by category Id listing operations success!"); map.put(Check.result,elasticProductList.size()); } catch (NumberFormatException e) { map.put(Check.status, false); map.put(Check.message, "An error occurred in total product by category Id listing operation!"); } return map; } //Daily Announcment public Map<Check,Object> dailyAnnouncment(String stPageNo){ Map<Check,Object> map = new LinkedHashMap<>(); try { int pageNo = Integer.parseInt(stPageNo); String[] date = Util.getDateFormatter().split(" "); Pageable pageable = PageRequest.of(pageNo,1); Page<Announcement> announcementPage = announcementRepository.findByDateContainsIgnoreCaseOrderByIdAsc(date[0],pageable); //System.out.println(announcementPage.getContent()); map.put(Check.status,true); map.put(Check.message,"Daily Announcment Listing Operation Success!"); map.put(Check.totalPage,announcementPage.getTotalPages()); map.put(Check.result,announcementPage.getContent()); } catch (Exception e) { String error = "An error occurred in Daily Announcment Listing listing operation!"; map.put(Check.status, false); map.put(Check.message,error); System.err.println(e); Util.logger(error, Announcement.class); } return map; } }
475370d59a771b575270f2e6375de1de447d99c0
[ "JavaScript", "Java", "Markdown" ]
64
Java
oguzkaansari/Company-All-Project
68ff734f7a92e7c920fa472bbc162a2bbe9e5d0a
31d157489c2338502ce868b8cd15bc4a06b06dba
refs/heads/master
<repo_name>nunnly/dva-boot-admin<file_sep>/src/components/Form/TableForm.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Modal, Button } from 'antd'; import DataTable from '../DataTable'; import $$ from 'cmn-utils'; import isEqual from 'react-fast-compare'; import PageHelper from '@/utils/pageHelper'; import assign from 'object-assign'; const Pagination = DataTable.Pagination; /** * formItem: { type: 'table', rowKey: 'id', titleKey: 'name', dataSource, columns: innerColumns, onChange: (form, value) => console.log('。。。:', value), loadData: self.onLoadTableData, initialValue: [11, 3, 5], } */ class TableControlled extends Component { static propTypes = { value: PropTypes.array, dataSource: PropTypes.object, onChange: PropTypes.func, loadData: PropTypes.func }; static defaultProps = { rowKey: 'id', titleKey: 'title', modal: {} }; constructor(props) { super(props); const { value, dataSource } = props; this.state = { value: value, dataSource: dataSource || PageHelper.create(), visible: false, loading: false }; } componentDidMount() { const { loadData } = this.props; if (loadData) { this.onChange({ pageNum: 1 }); } } componentWillReceiveProps(nextProps) { const { dataSource, value, loadData } = nextProps; if ( !isEqual(this.props.dataSource, dataSource) || !isEqual(this.props.value, value) ) { const newState = { value }; if (!loadData && dataSource) { newState.dataSource = dataSource; } this.setState(newState); } } onSelect = (keys, rows) => { this.setState({ value: keys }); const onChange = this.props.onChange; if (onChange) { onChange(keys, rows); } }; async onChange({ pageNum, pageSize }) { const { loadData } = this.props; const { dataSource } = this.state; if (loadData) { this.setState({ loading: true }); const newDataSource = await loadData( dataSource.jumpPage(pageNum, pageSize) ); this.setState({ loading: false, dataSource: assign(dataSource, newDataSource) }); } } showModal = () => { this.setState({ visible: true }); }; hideModal = () => { this.setState({ visible: false }); }; render() { const { modal, columns, titleKey, rowKey, selectType, showNum, ...otherProps } = this.props; const { dataSource, value, loading } = this.state; const dataTableProps = { loading, columns, rowKey, dataItems: dataSource, selectedRowKeys: value, selectType: typeof selectType === 'undefined' ? 'checkbox' : selectType, showNum: typeof showNum === 'undefined' ? true : showNum, isScroll: true, onChange: ({ pageNum, pageSize }) => this.onChange({ pageNum, pageSize }), onSelect: (keys, rows) => this.onSelect(keys, rows) }; if (modal) { return ( <div> <Button onClick={this.showModal}> 请选择 {otherProps.title} </Button> &nbsp; {value && value.length ? ( <span> 已选择: {value.length}项 </span> ) : null} <Modal className="antui-table-modal" title={'请选择' + otherProps.title} visible={this.state && this.state.visible} width={modal.width || 600} onOk={this.hideModal} onCancel={this.hideModal} footer={[ <Pagination key="paging" size="small" showSizeChanger={false} showQuickJumper={false} {...dataTableProps} />, <Button key="back" onClick={this.hideModal}> 取消 </Button>, <Button key="submit" type="primary" onClick={this.hideModal}> 确定 </Button> ]} {...modal} > <DataTable {...dataTableProps} /> </Modal> </div> ); } return ( <DataTable pagination={{ showSizeChanger: false, showQuickJumper: false }} {...dataTableProps} /> ); } } /** * TableForm组件 */ export default ({ form, name, formFieldOptions = {}, record, initialValue, rules, onChange, dataSource, normalize, rowKey, ...otherProps }) => { const { getFieldDecorator } = form; let initval = initialValue; if (record) { initval = record[name]; } // 如果存在初始值 if (initval !== null && typeof initval !== 'undefined') { if ($$.isFunction(normalize)) { formFieldOptions.initialValue = normalize(initval); } else { formFieldOptions.initialValue = initval; } } // 如果有rules if (rules && rules.length) { formFieldOptions.rules = rules; } // 如果需要onChange if (typeof onChange === 'function') { formFieldOptions.onChange = (value, rows) => onChange(form, value, rows); // form, value } return getFieldDecorator(name, formFieldOptions)( <TableControlled dataSource={dataSource} rowKey={rowKey || name} {...otherProps} /> ); };
a30abfcac09b451f5d8f8a3bd11cf47c1dd0fa63
[ "JavaScript" ]
1
JavaScript
nunnly/dva-boot-admin
7e3901f299f55fd6e9c634ddd91dba8bc34cf5a5
f98377b5db1399b86e86e7eac2be505fc7d2ad4f
refs/heads/master
<file_sep>export class Parameters { fechaInicial: Date; fechaFinal: Date; clienteId: number; tipoComprobante: string; } <file_sep>export class Estadistica { cliente:string; ingreso:number; egreso:number; traslado:number; nomina:number; pago:number total:number; } <file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule,ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { LoginComponent } from './usuarios/login.component'; import { ClienteComponent } from './clientes/cliente.component'; import {RouterModule,Routes} from '@angular/router'; import { HttpClientModule} from '@angular/common/http'; import { CreateComponent } from './usuarios/create/create.component'; import { HeaderComponent } from './header/header.component'; import { FooterComponent } from './footer/footer.component'; import { VerComponent } from './clientes/ver/ver.component'; import { EditarComponent } from './clientes/editar/editar.component'; import { CfdiComponent } from './cfdi/cfdi.component'; import { DataTablesModule } from "angular-datatables"; import { DatePipe } from '@angular/common'; import { VerUsuarioComponent } from './usuarios/ver-usuario/ver-usuario.component'; import { EditarUsuarioComponent } from './usuarios/editar-usuario/editar-usuario.component'; import { AuthGuard } from './usuarios/guards/auth.guard'; import { HeaderMobileComponent } from './header-mobile/header-mobile.component'; import { ContentComponent } from './content/content.component'; import { HomeComponent } from './home/home.component'; import { PanelComponent } from './panel/panel.component'; import { CfdiSatComponent } from './cfdi-sat/cfdi-sat.component'; const routes:Routes=[ //definicion pagina principal {path: '', redirectTo:'/login',pathMatch:'full'}, //{path:'home',component:HeaderComponent}, {path:'home',component:HomeComponent}, {path:'login',component:LoginComponent}, {path:'usuarios/crear', component:CreateComponent}, {path:'usuarios/ver', component:VerUsuarioComponent , canActivate:[AuthGuard]}, {path:'usuario/editar/:id',component:EditarUsuarioComponent, canActivate:[AuthGuard]}, {path:'clientes/ver',component:VerComponent, canActivate:[AuthGuard]}, {path:'cliente/crear',component:ClienteComponent, canActivate:[AuthGuard]}, {path:'cliente/editar/:id',component:EditarComponent, canActivate:[AuthGuard]}, {path:'cfdi/ver',component:CfdiComponent, canActivate:[AuthGuard]}, {path:'cfdi/sat/ver', component:CfdiSatComponent, canActivate:[AuthGuard]} ] @NgModule({ declarations: [ AppComponent, LoginComponent, ClienteComponent, CreateComponent, HeaderComponent, FooterComponent, VerComponent, EditarComponent, CfdiComponent, VerUsuarioComponent, EditarUsuarioComponent, HeaderMobileComponent, ContentComponent, HomeComponent, PanelComponent, CfdiSatComponent ], imports: [ BrowserModule, ReactiveFormsModule, FormsModule, HttpClientModule, DataTablesModule, RouterModule.forRoot(routes) ], providers: [DatePipe], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Paises } from "../enum/paises.enum"; export class Cliente { id:number; nombre:string; status:boolean; email:string; nombreLogo:string; logo:string; razonSocial:string; rfc:string; codigoPostal:string; //pais:string; pais:Paises; nombreFileCer:string cer:string; nombreFileKey:string; key:string; passwordKey:string; servidor:string; keyXsa:string; fechaInicial:string; //cfdiPrincipal:string[] isChecked:boolean= false; } <file_sep>import { HttpClient, HttpResponse } from '@angular/common/http'; import { Component, OnDestroy, OnInit, Renderer2, ViewChild } from '@angular/core'; import { Cfdi } from './cfdi'; import { CfdiService } from './cfdi.service'; import { saveAs } from 'file-saver'; import { StatusService } from '../authorization/status.service'; import { DatePipe } from '@angular/common'; import { DataTableDirective } from 'angular-datatables'; import { ClienteService } from '../clientes/cliente.service'; import { Cliente } from '../clientes/cliente'; import { Parameters } from './parameters'; import { Router } from '@angular/router'; import swal from 'sweetalert2'; import { AuthService } from '../usuarios/auth.service'; import { Comprobantes } from './comprobante/comprobantes'; import { ResponseDataTable } from './response-data-table'; @Component({ selector: 'app-cfdi', templateUrl: './cfdi.component.html', styleUrls: ['./cfdi.component.css'] }) export class CfdiComponent implements OnDestroy, OnInit { currentDate:Date; //input filtrado dataTable public params:Parameters= new Parameters(); public loading: boolean; clientes:Cliente[]; comprobantes:Comprobantes[]; id:number; tComprobante: any[] = []; dataCfdi: Cfdi[]; @ViewChild(DataTableDirective, {static: false}) datatableElement: DataTableDirective; dtOptions: DataTables.Settings = {}; tableData = []; blob: Blob; idCliente; comprobante; constructor(public http:HttpClient,public cfdiservice:CfdiService,public statusService:StatusService ,public clienteService:ClienteService,private router:Router,public renderer: Renderer2, private datepipe: DatePipe, public authService:AuthService) { this.currentDate = new Date(); } ngOnInit(): void { this.clienteService.getClientes().subscribe( clientes => this.clientes = clientes ); this.cfdiservice.getComprobantes().subscribe( comprobante => this.comprobantes = comprobante ); this.tComprobante=this.cfdiservice.enumSelect(); //dataTable this.getDataFromSource(); } onCheckboxChange(e) { } filterByInput(): void { //parseo fechas date a string let fechaIn=this.datepipe.transform(this.params.fechaInicial,'yyyy-MM-dd'); let fechaFin=this.datepipe.transform(this.params.fechaFinal,'yyyy-MM-dd'); this.idCliente = $('#clienteId').val(); this.comprobante = $('#comprobante').val(); this.params.clienteId = this.idCliente; this.params.tipoComprobante = this.comprobante; if(fechaIn==null || fechaFin==null) { swal.fire('// WARNING: ','Fecha inicial o Fecha final requerido!','warning'); }else{ this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => { dtInstance.draw(); }); } } getDataFromSource() { this.dtOptions = { pagingType: 'full_numbers', serverSide: true, processing: true, destroy:true, ajax: (dataTablesParameters: any, callback)=>{ this.cfdiservice.getDataInput(dataTablesParameters,this.params).subscribe(resp=>{ this.dataCfdi=resp.data callback({ recordsTotal: resp.recordsTotal, recordsFiltered: resp.recordsFiltered, data: [] }); }) }, columns: [ { data: 'tfdUuid'}, { data: 'folio' }, { data: 'fecha' }, { data: 'total' }, { data: 'id' }] }; } ngOnDestroy(): void { $.fn['dataTable'].ext.search.pop(); } downloadXml(id:number):void{ this.cfdiservice.downloadXmlId(id).subscribe((resp: HttpResponse<Blob>) =>{ //obtengo el nombre del archivo const filename=resp.headers.get('content-disposition').split(';')[1].split('filename')[1].split('=')[1].trim(); saveAs(resp.body,filename); },error=>{ if(this.statusService.isNoAuthorizado(error.status)){ } }) } downloadPdf(id:number):void{ this.cfdiservice.downloadPdfId(id).subscribe((resp:HttpResponse<Blob>) =>{ //obtengo el nombre del archivo const filename=resp.headers.get('content-disposition').split(';')[1].split('filename')[1].split('=')[1].trim(); saveAs(resp.body,filename); },error=>{ console.log(error); this.statusService.isNoAuthorizado(error.status) }) } downloadZipAll(params:Parameters):void{ this.loading = true; this.cfdiservice.downloadZipAllFiles(params).subscribe((resp: HttpResponse<Blob>) =>{ const filename=resp.headers.get('content-disposition').split(';')[1].split('filename')[1].split('=')[1].trim(); if(filename!='undefined') { this.loading = false; saveAs(resp.body,filename); } },error=>{ this.loading = false; console.log(error); this.statusService.isNoAuthorizado(error.status) }) } ngAfterViewInit(): void { $('.menu-item').click(function(){ $('.menu-item').addClass('menu-item-there'); }); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../usuarios/auth.service'; import swal from 'sweetalert2'; @Injectable({ providedIn: 'root' }) export class StatusService { constructor(public http:HttpClient,private router:Router,public authService:AuthService) { } //mensajes de no authorizado public isNoAuthorizado(e):boolean{ if(e.status == 401){ if(this.authService.isAuthenticated()){ this.authService.logout(); } this.router.navigate(['/login']); return true; } if(e.status == 500){ return true; } return false; } } <file_sep>import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../usuarios/auth.service'; import swal from 'sweetalert2'; import { Observable, throwError } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { TipoComprobante } from '../enum/tipo-comprobante.enum'; import { StatusService } from '../authorization/status.service'; import { ResponseDataTable } from './response-data-table'; import { Comprobantes } from './comprobante/comprobantes'; @Injectable({ providedIn: 'root' }) export class CfdiService { private urlEndpoint:string = 'http://192.168.127.12:8087/api'; private httpHeaders = new HttpHeaders({'Content-type': 'application/json'}); private username2:string = this.authService.usuario.username; constructor(private http:HttpClient,private router:Router,private authService:AuthService,private statusService:StatusService) { } //agrega authorizacion del token en httpHeaders private agregarAuthorization(){ let token =this.authService.token; if(token != null){ return this.httpHeaders.append('Authorization','Bearer ' + token); } return this.httpHeaders; } downloadXmlId(id):Observable<HttpResponse<Blob>>{ var url = this.urlEndpoint+"/downloadXml"; return this.http.get<Blob>(`${url}/${id}` , {headers:this.agregarAuthorization(),observe:'response', responseType:'blob' as 'json'}) .pipe(catchError(e=>{ if(e.status== 400) swal.fire('Error','Error el archivo no se encuentra!','error'); return throwError(e); })); } downloadPdfId(id):Observable<HttpResponse<Blob>>{ var url = this.urlEndpoint+"/downloadPdf"; return this.http.get<Blob>(`${url}/${id}` , {headers:this.agregarAuthorization(),observe:'response',responseType:'blob' as 'json'}) .pipe(catchError(e=>{ console.log(e.status) if(e.status== 400) console.log(e.error) swal.fire('Error','Error el archivo no se encuentra!','error'); return throwError(e); })); } downloadZipAllFiles(params):Observable<HttpResponse<Blob>>{ var url = this.urlEndpoint+"/downloadZip?inicial="+params.fechaInicial+"&final="+params.fechaFinal +"&clienteId="+params.clienteId+"&tipoComp="+params.tipoComprobante+"&username="+this.username2; return this.http.get<Blob>(`${url}` , {headers:this.agregarAuthorization(),observe:'response', responseType:'blob' as 'json'}) .pipe(catchError(e=>{ if(e.status== 500) swal.fire('Error',e.error.messaje,'error'); return throwError(e); })); } getDataInput(dataTablesParameters,params):Observable<ResponseDataTable>{ let username =this.authService.usuario.username; const url = `${this.urlEndpoint}/data/cfdi?inicial=${params.fechaInicial}&final=${params.fechaFinal}&clienteId=${params.clienteId}&tipoComp=${params.tipoComprobante}&username=${username}` return this.http.post<ResponseDataTable>(`${url}`,dataTablesParameters,{headers:this.agregarAuthorization()}).pipe (catchError(e=>{ if(this.statusService.isNoAuthorizado(e)){ return throwError(e); } this.router.navigate(['/cfdi/ver']); console.error(e.error.mensaje); swal.fire('Error',e.error.mensaje,'error'); return throwError(e); }));; } getComprobantes(): Observable<Comprobantes[]> { let username =this.authService.usuario.username; return this.http.get<Comprobantes[]>(`${this.urlEndpoint}/comprobantes?username=${username}`,{headers:this.agregarAuthorization()}).pipe( map(response => response as Comprobantes[]) ); } enumSelect(){ var tComprobante: any[] = []; for(let item in TipoComprobante){ if(isNaN(Number(item))){ tComprobante.push({text:item , value: TipoComprobante[item]}); } } return tComprobante; } } <file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders,} from '@angular/common/http'; import { Observable } from 'rxjs'; import { Usuario } from './usuario'; import { AuthService } from './auth.service'; import { map, catchError, tap } from 'rxjs/operators'; import { TipoComprobante } from '../enum/tipo-comprobante.enum'; import { Cliente } from '../clientes/cliente'; import { StatusService } from '../authorization/status.service'; import swal from 'sweetalert2'; import { throwError } from 'rxjs'; import { Estatus } from '../enum/estatus.enum'; import { Rol } from './rol'; @Injectable({ providedIn: 'root' }) export class UsuarioService { private urlEndpoint:string = 'http://192.168.3.11:8087/api'; private httpHeaders = new HttpHeaders({'Content-type': 'application/json'}); constructor(private http:HttpClient, private authService: AuthService, private statusService:StatusService) { } private agregarAuthorizationHeader() { let token = this.authService.token; if (token != null) { return this.httpHeaders.append('Authorization', 'Bearer ' + token); } return this.httpHeaders; } create(usuario:Usuario):Observable<Usuario>{ return this.http.post<Usuario>(`${this.urlEndpoint}/usuarios/crear`,usuario,{headers:this.httpHeaders}) } getAllUsuario(): Observable<Usuario[]> { return this.http.get<Usuario[]>(`${this.urlEndpoint}/usuarios`,{headers:this.agregarAuthorizationHeader()}) .pipe(map(response=> response as Usuario[]) ,catchError(e =>{ if(this.statusService.isNoAuthorizado(e)){ return throwError(e); } console.error(e.error.mensaje); swal.fire('Error',e.error.mensaje,'error'); return throwError(e); })); } getUsuarioById(id):Observable<Usuario>{ return this.http.get<Usuario>(`${this.urlEndpoint}/usuario/${id}` , {headers:this.agregarAuthorizationHeader()}).pipe( catchError(e =>{ if(this.statusService.isNoAuthorizado(e)){ return throwError(e); } console.error(e.error.mensaje); swal.fire('Error',e.error.mensaje,'error'); return throwError(e); }) ) } deleteUsuario(id:number):Observable<Usuario>{ return this.http.delete<Usuario>(`${this.urlEndpoint}/usuario/${id}`,{headers:this.agregarAuthorizationHeader()}).pipe( catchError(e=> { if(this.statusService.isNoAuthorizado(e)){ return throwError(e); } console.error(e.error.mensaje); swal.fire(e.error.mensaje,e.error,'error'); return throwError(e); }) ) } update(usuario:Usuario):Observable<Usuario>{ return this.http.put<Usuario>(`${this.urlEndpoint}/usuario/${usuario.id}`,usuario,{headers:this.agregarAuthorizationHeader()}) .pipe(catchError(e=> { if(this.statusService.isNoAuthorizado(e)){ return throwError(e); } console.error(e.error.mensaje); swal.fire(e.error.mensaje,e.error,'error'); return throwError(e); })); } enumSelectComprobante(){ var tComprobante: any[] = []; var isChecked:Boolean=false; for(let item in TipoComprobante){ if(isNaN(Number(item))){ tComprobante.push({text:item , value: TipoComprobante[item],isChecked:isChecked}); } } return tComprobante; } enumSelectEstatus(){ var estatus: any[] = []; for(let item in Estatus){ if(isNaN(Number(item))){ estatus.push({text:item , value: Estatus[item]}); } } return estatus; } getAllRoles():Observable<Rol[]>{ return this.http.get<Rol[]>(`${this.urlEndpoint}/roles`) .pipe(map(response=> response as Rol[])); } } <file_sep>export class Comprobantes { id:number; nombre:string; descripcion:string; } <file_sep>export class Cfdi { id:number; razonSocial:string; rfc:string; folio:string; uuid:string; fecha:string; total:string; serie:string; } <file_sep>import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import {HttpClient, HttpHeaders } from '@angular/common/http' import { Usuario } from './usuario'; import { Rol } from './rol'; @Injectable({ providedIn: 'root' }) export class AuthService { private _usuario:Usuario; private _token: string; rol:Rol constructor(private http:HttpClient) { } public get usuario(): Usuario { if (this._usuario != null) { return this._usuario; } else if (this._usuario == null && sessionStorage.getItem('usuario') != null) { this._usuario = JSON.parse(sessionStorage.getItem('usuario')) as Usuario; return this._usuario; } return new Usuario(); } public get token(): string { if (this._token != null) { return this._token; } else if (this._token == null && sessionStorage.getItem('token') != null) { this._token = sessionStorage.getItem('token'); return this._token; } return null; } login(usuario:Usuario):Observable<any>{ const urlEndpoint = 'http://191.96.42.214:8087/oauth/token'; const credenciales = btoa('centroCfdi'+':'+'12345'); const httpHeaders = new HttpHeaders({'Content-Type':'application/x-www-form-urlencoded', 'Authorization':'Basic ' + credenciales}); let params = new URLSearchParams(); params.set('grant_type','password'); params.set('username',usuario.username); params.set('password',<PASSWORD>); //obtenemos el token return this.http.post<any>(urlEndpoint,params.toString(),{headers:httpHeaders}) } guardarUsuario(acccessToken:string):void{ let payload = this.obtenerDatosToken(acccessToken); this._usuario = new Usuario(); this._usuario.username = payload.user_name; this._usuario.email = payload.email; this._usuario.roles = payload.authorities; sessionStorage.setItem('usuario',JSON.stringify(this._usuario)); } guardarToken(acccessToken:string):void{ this._token = acccessToken; sessionStorage.setItem('token',acccessToken); } obtenerDatosToken(acccessToken:string):any{ if(acccessToken!=null){ return JSON.parse(atob(acccessToken.split(".")[1])) } return null; } isAuthenticated():boolean{ let payload = this.obtenerDatosToken(this.token); if(payload!=null && payload.user_name && payload.user_name.length>0){ //console.log(payload); // console.log(payload.user_name); // console.log(payload.user_name.legth) return true; } return false; } hasRole(role: string): boolean { var rol; for(var x=0;x<this.usuario.roles.length;x++){ rol = this.usuario.roles[x]; if(rol == role){ return true; } } return false } logout():void{ this._token=null; this._usuario = null; sessionStorage.clear(); sessionStorage.removeItem('token'); sessionStorage.removeItem('usuario'); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-cfdi-sat', templateUrl: './cfdi-sat.component.html', styleUrls: ['./cfdi-sat.component.css'] }) export class CfdiSatComponent implements OnInit { tipo:String; formCiecc:boolean=false; formFiel:boolean=false; constructor() { } ngOnInit(): void { } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpEvent, HttpHeaders, HttpRequest } from '@angular/common/http'; import { Router } from '@angular/router'; import { AuthService } from '../usuarios/auth.service'; import { Estadistica } from './estadistica'; import { map, catchError, tap } from 'rxjs/operators'; import { Observable, throwError } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class HomeService { private urlEndpoint:string = 'http://172.16.58.3:8087/api'; private httpHeaders = new HttpHeaders({'Content-type': 'application/json'}); constructor(public http:HttpClient,private router:Router,public authService:AuthService) { } getEstadisticaComprobante(): Observable<Estadistica[]> { let username =this.authService.usuario.username; return this.http.get<Estadistica[]>(`${this.urlEndpoint}/estadistica?username=${username}`).pipe( map(response => response as Estadistica[]) ); } } <file_sep>export enum Paises { USA = 2, MEXICO= 1 } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Usuario } from '../usuario'; import { UsuarioService } from '../usuario.service'; import swal from 'sweetalert2'; import { ClienteService } from 'src/app/clientes/cliente.service'; import { Cliente } from 'src/app/clientes/cliente'; import { Rol } from '../rol'; import { AuthService } from '../auth.service'; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'] }) export class CreateComponent implements OnInit { public usuario:Usuario = new Usuario(); usuarios:Usuario[]; clientes:Cliente[]; tComprobante: any[] = []; checkClienteId=[]; checkTipoComprobante=[]; errores:string[] roles:Rol[]; role:Rol=null; activeCheck:boolean=false constructor(public usuarioService:UsuarioService ,private clienteService:ClienteService, private router:Router ,public authService:AuthService) { } ngOnInit(): void { this.clienteService.getClientesAll().subscribe( clientes => this.clientes = clientes ); this.tComprobante=this.usuarioService.enumSelectComprobante(); this.usuarioService.getAllRoles().subscribe( roles => this.roles = roles ); } validExistTokeAndUser():boolean{ if(this.authService.usuario.username!=null && this.authService.token!=null){ return true; } return false; } onSelectRol(){ if(this.role!=null){ if(this.role.nombre=="ROLE_USER"){ this.activeCheck=true }else{ this.activeCheck=false ; } this.usuario.roles.push(this.role) } } onCheckboxCliente() { this.checkClienteId = [] this.clientes.forEach((value, index) => { if (value.isChecked) { this.checkClienteId.push(value.id); } }); } onCheckboxTipo(){ this.checkTipoComprobante = [] this.tComprobante.forEach((value, index) => { if (value.isChecked) { this.checkTipoComprobante.push(value.value); } }); } public create():void{ if(this.usuario.roles.length<1 || this.role==null ){ swal.fire('// WARNING: ','seleccionar rol!','warning') }else if(this.checkClienteId.length < 1 && this.role.nombre=="ROLE_USER"){ swal.fire('// WARNING: ','seleccionar empresa!','warning') }else if (this.checkTipoComprobante.length < 1 && this.role.nombre=="ROLE_USER"){ swal.fire('// WARNING: ','seleccionar comprobante!','warning') }else{ this.usuario.clienteId=this.checkClienteId; this.usuario.comprobante=this.checkTipoComprobante; this.usuarioService.create(this.usuario).subscribe( response=> { swal.fire('Nuevo usuario','usuario '+ response.nombre +' creado con exito!','success'); },error =>{ if(error.status==400){ console.error(error.error.error) } if(error.status==409){ console.error(error.error.mensaje) swal.fire('Error Usuario',error.error.mensaje, 'error'); } }); } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router , ActivatedRoute} from '@angular/router'; import { Cliente } from '../cliente'; import { ClienteService } from '../cliente.service'; import swal from 'sweetalert2'; import { HttpEventType } from '@angular/common/http'; import { Paises } from 'src/app/enum/paises.enum'; @Component({ selector: 'app-editar', templateUrl: './editar.component.html', styleUrls: ['./editar.component.css'] }) export class EditarComponent implements OnInit { public cliente:Cliente = new Cliente(); progreso: number = 0; private logoSeleccionada: File; private cerSeleccionada: File; private keySeleccionada: File; params; paises:any[] = []; object; constructor(private clienteService:ClienteService, private router:Router, private activatedRoute:ActivatedRoute) { } ngOnInit(): void { this.cargarCliente(); this.params = this.clienteService.stringEnumToKeyValue(Paises); this.paises=this.clienteService.enumSelect(); } cargarCliente():void{ this.activatedRoute.params.subscribe(params => { let id = params['id']; if(id){ this.clienteService.getClienteById(id).subscribe((cliente) => this.cliente = cliente); console.log(this.cliente) } }) } editar():void{ console.log(this.cliente.id); if(this.cliente.rfc==null && this.cliente.nombre==null && this.cliente.razonSocial==null && this.cliente.codigoPostal==null && this.cliente.pais==null ){ this.router.navigate(['/cliente/editar/'+this.cliente.id]); swal.fire("Error","Campos Nombre, Razon social, Rfc, Codigo postal, País no deben quedar vacios!",'error'); } this.clienteService.create(this.cliente,this.cerSeleccionada,this.keySeleccionada,this.logoSeleccionada).subscribe( event =>{ if(event.type === HttpEventType.UploadProgress){ this.progreso = Math.round((event.loaded / event.total) * 100); } else if (event.type === HttpEventType.Response) { let response: any = event.body; this.cliente = response.cliente as Cliente; console.log(response.mensaje); this.router.navigate(['/clientes']); swal.fire('Cliente actualizado Exitosamente!', response.mensaje, 'success'); } }) } seleccionaLogo(event) { this.logoSeleccionada = event.target.files[0]; this.progreso = 0; console.log(this.logoSeleccionada); if (this.logoSeleccionada.type.indexOf('image') < 0) { swal.fire('Error seleccionar imagen: ', 'El archivo debe ser del tipo imagen', 'error'); event.target.value=""; this.logoSeleccionada = null; } } seleccionaCer(event) { this.cerSeleccionada = event.target.files[0]; if(this.cerSeleccionada!=null){ if(!(/\.(CER|cer)$/i).test(this.cerSeleccionada.name)){ console.log("Archivo invalido") swal.fire("Error","Error tipo de archivo Cer incorrecto!","error"); this.cerSeleccionada = null; event.target.value=""; }else{ console.log("Archivo valido") } } this.progreso = 0; } seleccionaKey(event) { this.keySeleccionada = event.target.files[0]; if(this.keySeleccionada!=null){ if(!(/\.(KEY|key)$/i).test(this.keySeleccionada.name)){ console.log("Archivo invalido") swal.fire("Error","Error tipo de archivo Key incorrecto!","error"); this.keySeleccionada = null; event.target.value=""; }else{ console.log("Archivo valido") } } this.progreso = 0; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Usuario } from '../usuario'; import { UsuarioService } from '../usuario.service'; import swal from 'sweetalert2'; import { Rol } from '../rol'; import { ClienteService } from 'src/app/clientes/cliente.service'; import { Cliente } from 'src/app/clientes/cliente'; @Component({ selector: 'app-editar-usuario', templateUrl: './editar-usuario.component.html', styleUrls: ['./editar-usuario.component.css'] }) export class EditarUsuarioComponent implements OnInit { public usuario:Usuario = new Usuario(); estatus:any[]=[]; clientes:Cliente[]; tComprobante: any[] = []; habilitar:boolean=false; passwordN<PASSWORD>:string=<PASSWORD>; passwordRepetida:string=<PASSWORD>; roles:Rol[]; rol:Rol; activeCheck:boolean=false checkClienteId=[]; checkTipoComprobante=[]; //client:Cliente[]; nameRol:string; constructor(public usuarioService:UsuarioService,public activatedRoute:ActivatedRoute,private router:Router, public clienteService:ClienteService) { } ngOnInit(): void { this.estatus=this.usuarioService.enumSelectEstatus(); this.cargarUsuario(); this.usuarioService.getAllRoles().subscribe( roles => this.roles = roles); this.cargaCliente(); this.tComprobante=this.usuarioService.enumSelectComprobante(); } //se activa despues de detetctar nuevos cambios ngDoCheck():void{ this.onSelectRol() this.activacheckCliente(); this.activacheckComprobante(); } cargaCliente(){ this.clienteService.getClientesAll().subscribe( clientes => this.clientes = clientes ); } cargarUsuario():void{ this.activatedRoute.params.subscribe(params => { let id = params['id']; if(id){ this.usuarioService.getUsuarioById(id).subscribe(usuario => {this.usuario = usuario ,this.usuario.roles.forEach(element => { this.rol=element ,this.nameRol=element.nombre }),this.usuario.clientes.forEach(element => { this.checkClienteId.push(element.id) }),this.usuario.comprobantes.forEach(element => { this.checkTipoComprobante.push(element.nombre) }); } );} }) } update():void{ if(this.habilitar){ if(this.passwordNueva==null || this.passwordRepetida==null){ swal.fire('// WARNING: ',"Las contraseña no pueden ir vacias",'warning'); }else{ this.usuario.nuevaPassword=<PASSWORD>; this.updateRole(); this.updateUsuario(); } if(this.passwordNueva!=this.passwordRepetida ){ swal.fire('// WARNING: ',"Las contraseñas no coinciden",'warning'); } }else{ this.updateRole(); this.updateUsuario(); } } updateUsuario(){ this.usuario.clienteId=this.checkClienteId; this.usuario.comprobante=this.checkTipoComprobante; this.usuarioService.update(this.usuario) .subscribe(usuario =>{ this.router.navigate(['/usuarios/ver']) swal.fire('Usuario actualizado','Usuario actualizado con exíto!','success'); }) } updateRole(){ var index=0; var rol for(var x=0;x<this.usuario.roles.length;x++) { rol=this.usuario.roles[x].nombre; if(rol != this.rol.nombre){ this.usuario.roles.splice(x, 1); this.usuario.roles.push(this.rol) } index++; } } compararRol(o1:Rol,o2:Rol){ return o1 ==null || o2==null? false : o1.id===o2.id } onSelectRol(){ if(this.rol!=null){ if(this.rol.nombre=="ROLE_USER"){ this.activeCheck=true; }else{ this.activeCheck=false; this.checkClienteId.length=0; this.checkTipoComprobante.length=0; } // this.usuario.roles.push(this.rol) } } onCheckboxCliente() { this.checkClienteId = [] this.clientes.forEach((value, index) => { if (value.isChecked) { this.checkClienteId.push(value.id); } }); console.log(this.checkClienteId) } onCheckboxTipo(){ this.checkTipoComprobante = [] this.tComprobante.forEach((value, index) => { if (value.isChecked) { this.checkTipoComprobante.push(value.value); } }); console.log(this.checkTipoComprobante) } activacheckCliente(){ if(this.clientes!=undefined){ for(var x=0;x<this.clientes.length;x++){ for(var y=0;y<this.checkClienteId.length;y++){ if(this.clientes[x].id==this.checkClienteId[y]){ this.clientes[x].isChecked=true; } } } } } activacheckComprobante(){ if(this.tComprobante!=undefined){ for(var x=0;x<this.tComprobante.length;x++){ for(var y=0;y<this.checkClienteId.length;y++){ if(this.tComprobante[x].value==this.checkTipoComprobante[y]){ this.tComprobante[x].isChecked=true; } } } } } } <file_sep>import { HttpClient, HttpEvent, HttpHeaders, HttpRequest } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { Cliente } from './cliente'; import { map, catchError, tap } from 'rxjs/operators'; import { AuthService } from '../usuarios/auth.service'; import { Router } from '@angular/router'; import swal from 'sweetalert2'; import { Paises } from '../enum/paises.enum'; @Injectable({ providedIn: 'root' }) export class ClienteService { private urlEndpoint:string = 'http://192.168.127.12:8087/api'; private httpHeaders = new HttpHeaders({'Content-type': 'application/json'}); constructor(private http:HttpClient,private router:Router,private authService:AuthService) { } //se agrega el metodo en los observables con token private agregarAuthorization(){ let token =this.authService.token; if(token != null){ return this.httpHeaders.append('Authorization','Bearer ' + token); } return this.httpHeaders; } private isNoAuthorizado(e):boolean{ if(e.status == 401){ if(this.authService.isAuthenticated()){ this.authService.logout(); } this.router.navigate(['/login']); return true; } if(e.status == 403){ swal.fire('Acceso denegado',`Hola ${this.authService.usuario.username} no tienes acceso a este recurso!`,'warning'); this.router.navigate(['/clientes']) return true; } return false; } create(cliente:Cliente,cerSeleccionada,keySeleccionada,fotoSeleccionada):Observable<HttpEvent<{}>>{ const formData = new FormData(); let json = JSON.stringify(cliente); const blob = new Blob([json], { type: 'application/json' }); formData.append("archivoCer", cerSeleccionada); formData.append("archivoKey",keySeleccionada); formData.append("logo",fotoSeleccionada); formData.append("cliente",blob); let httpHeaders = new HttpHeaders(); let token = this.authService.token; if(token!=null){ httpHeaders = httpHeaders.append('Authorization', 'Bearer ' + token); } const req = new HttpRequest('POST', `${this.urlEndpoint}/cliente`, formData, { reportProgress: true, headers:httpHeaders }); return this.http.request(req).pipe( catchError(e =>{ this.isNoAuthorizado(e); return throwError(e); }) ); } getClientes(): Observable<Cliente[]> { let username =this.authService.usuario.username; return this.http.get<Cliente[]>(`${this.urlEndpoint}/cliente?username=${username}`).pipe( map(response => response as Cliente[]) ); } getClientesAll(): Observable<Cliente[]> { let username =this.authService.usuario.username; return this.http.get<Cliente[]>(`${this.urlEndpoint}/clientes`).pipe( map(response => response as Cliente[]) ); } getClienteById(id):Observable<Cliente>{ return this.http.get<Cliente>(`${this.urlEndpoint}/cliente/${id}` , {headers:this.agregarAuthorization()}).pipe( catchError(e =>{ if(this.isNoAuthorizado(e)){ return throwError(e); } this.router.navigate(['/clientes']); console.error(e.error.mensaje); swal.fire('Error',e.error.mensaje,'error'); return throwError(e); }) ) } deleteCliente(id:number):Observable<Cliente>{ return this.http.delete<Cliente>(`${this.urlEndpoint}/cliente/${id}`,{headers:this.agregarAuthorization()}).pipe( catchError(e=> { if(this.isNoAuthorizado(e)){ return throwError(e); } console.error(e.error.mensaje); swal.fire(e.error.mensaje,e.error,'error'); return throwError(e); }) ) } //otra forma de parsear los enum en un array para los select stringEnumToKeyValue(paises) { var keys =Object.keys(paises) .map(key => ({ id: paises[key], name: key })) var keyValues = keys.slice(keys.length /2); return keyValues; } //forma mas compleja para parsear los enum para los select enumSelect(){ var paises: any[] = []; for(let item in Paises){ if(isNaN(Number(item))){ paises.push({text:item , value: Paises[item]}); } } return paises; } } <file_sep>import { Comprobantes } from "../cfdi/comprobante/comprobantes"; import { Cliente } from "../clientes/cliente"; import { Rol } from "./rol"; export class Usuario { id:number; nombre:string; apellidos:string; username:string; password:string; email:string; estatus:boolean; roles:Rol[]=[]; clientes:Cliente[]=[]; comprobantes:Comprobantes[]=[]; clienteId:number[]=[]; comprobante:string[]=[]; nuevaPassword:string; } <file_sep>export enum TipoComprobante { INGRESOS = "I", EGRESOS = "E", TRASLADO = "T", NOMINA = "N", PAGO = "P" } <file_sep>import { Component, OnInit } from '@angular/core'; import { AuthService } from '../usuarios/auth.service'; import swal from 'sweetalert2'; import { Router } from '@angular/router'; @Component({ selector: 'app-panel', templateUrl: './panel.component.html', styleUrls: ['./panel.component.css'] }) export class PanelComponent implements OnInit { username:string; constructor(public authService:AuthService,private router:Router) { } ngOnInit(): void { this.username = this.authService.usuario.username } logout():void{ let username =this.authService.usuario.username; this.authService.logout(); swal.fire("Logout", `hola ${username}, has cerrado sesión con éxito!`,'success'); this.router.navigate(["/login"]); } } <file_sep>export enum Estatus { INACTIVO= "false", ACTIVO = "true" } <file_sep>import { Component, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; import { Usuario } from '../usuario'; import { UsuarioService } from '../usuario.service'; import swal from 'sweetalert2'; @Component({ selector: 'app-ver-usuario', templateUrl: './ver-usuario.component.html', styleUrls: ['./ver-usuario.component.css'] }) export class VerUsuarioComponent implements OnInit { usuarios: Usuario[] =[]; dtOptions: DataTables.Settings = {}; dtTrigger: Subject<any> = new Subject<any>(); constructor(private usuarioService:UsuarioService) { } ngOnInit(): void { this.usuarioService.getAllUsuario().subscribe( usuarios=> {this.usuarios = usuarios this.dtTrigger.next(); }); this.dtOptions = { pagingType: 'full_numbers' }; } delete(usuario: Usuario): void { swal.fire({ title: 'Está seguro?', text: `¿Seguro que desea eliminar al username ${usuario.username}?`, showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Si, eliminar!', cancelButtonText: 'No, cancelar!', buttonsStyling: true, reverseButtons: true }).then((result) => { if (result.value) { this.usuarioService.deleteUsuario(usuario.id).subscribe( () => { this.usuarios = this.usuarios.filter(cli => cli !== usuario) swal.fire( 'Username Eliminado!', `Username ${usuario.username} eliminado con éxito.`, 'success' ) } ) } }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { HomeService } from './home.service'; import { Estadistica } from './estadistica'; import { Subject } from 'rxjs'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { estadisticas: Estadistica[] =[]; dtOptions: DataTables.Settings = {}; dtTrigger: Subject<any> = new Subject<any>(); constructor(private homeService:HomeService) { } ngOnInit(): void { this.homeService.getEstadisticaComprobante().subscribe( estadistica => {this.estadisticas = estadistica this.dtTrigger.next(); }); this.dtOptions = { pagingType: 'full_numbers' }; } }
362d5de205349b410f97eacdf5cd2683bb51199c
[ "TypeScript" ]
24
TypeScript
njmube/centro-CFDI-Angular
8ee121b0971ff0c4dde77f945b9480e22e630350
7b4879fbba2496e83c9b81b9f6d5392453ceaf01
refs/heads/master
<repo_name>mkwill/assignment_3<file_sep>/app/src/main/java/lwtech/itad230/micahwilliams/assignment_three/TimerActivity.java package lwtech.itad230.micahwilliams.assignment_three; import android.content.Intent; import android.os.Parcelable; import android.provider.AlarmClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class TimerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timer); } public void onClickTimer(View view){ String duration = findViewById(R.id.duration).toString(); Integer i = Integer.valueOf(duration); String message = findViewById(R.id.message).toString(); Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER) .putExtra(AlarmClock.EXTRA_LENGTH, i) .putExtra(AlarmClock.EXTRA_MESSAGE, message) .putExtra(AlarmClock.EXTRA_SKIP_UI, true); if(intent.resolveActivity(getPackageManager()) != null){ startActivity(intent); } } } <file_sep>/app/src/main/java/lwtech/itad230/micahwilliams/assignment_three/NoteActivity.java package lwtech.itad230.micahwilliams.assignment_three; import android.content.Intent; import android.provider.AlarmClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class NoteActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); } public void onClickNote(View view){ String name = findViewById(R.id.Name).toString(); String note = findViewById(R.id.Note).toString(); Intent intent = new Intent(NoteIntents.ACTION_CREATE_NOTE) .putExtra(NoteIntents.EXTRA_NAME, name) .putExtra(NoteIntents.EXTRA_MESSAGE, note); if(intent.resolveActivity(getPackageManager()) != null){ startActivity(intent); } } } <file_sep>/app/src/main/java/lwtech/itad230/micahwilliams/assignment_three/AlarmActivity.java package lwtech.itad230.micahwilliams.assignment_three; import android.content.Intent; import android.os.Parcelable; import android.provider.AlarmClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class AlarmActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm); } public void onClickAlarm(View view){ String hours = findViewById(R.id.Hours).toString(); Integer i = Integer.valueOf(hours); String minutes = findViewById(R.id.minutes).toString(); Integer j = Integer.valueOf(minutes); Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM) .putExtra(AlarmClock.EXTRA_HOUR, i) .putExtra(AlarmClock.EXTRA_MINUTES, j) .putExtra(AlarmClock.EXTRA_SKIP_UI, true); if(intent.resolveActivity(getPackageManager()) != null){ startActivity(intent); } } }
3bf8ec162f44d48507458944fd4f1d3bd3a3ab63
[ "Java" ]
3
Java
mkwill/assignment_3
5b8477cbc8cfc576b01cb8209d550719853d8b9c
4e96855e2089275127403cccbf7a8a91d1a7f2b6
refs/heads/master
<repo_name>djbrown/riddlebase<file_sep>/entrypoint-dev.sh #!/bin/sh export DJANGO_SETTINGS_MODULE="riddlebase.settings" ./manage.py migrate ./manage.py collectstatic --no-input uvicorn --reload --host 0.0.0.0 --port 8000 riddlebase.asgi:application # ./manage.py runserver 0.0.0.0:8000 <file_sep>/riddles/static/riddles/js/riddle-manager.js export const RIDDLE_CELL_SIZE = 30; export const PICKER_CELL_SIZE = 25; const OFFSET = 2; const DEFAULT_ZOOM_FACTOR = 1.4; let zoomFactor = 1; function applyZoom() { document.getElementById("full-screen").classList.remove("active"); const svg = document.getElementById("riddle"); svg.classList.remove("full-screen"); //noinspection JSUnresolvedFunction const bBox = svg.getBBox(); const width = bBox.width + 2 * OFFSET; const svgWidth = width * zoomFactor; svg.setAttribute("width", svgWidth.toString()); } function setZoomFactor(newZoomFactor) { if (newZoomFactor < 0) { return; } zoomFactor = newZoomFactor; applyZoom(); } export function resetZoom() { setZoomFactor(DEFAULT_ZOOM_FACTOR); } function createSetZoomDeltaFunction(zoomDelta) { return function () { setZoomFactor(zoomFactor += zoomDelta); }; } function toggleFullScreen() { const svg = document.getElementById("riddle"); svg.classList.toggle("full-screen"); document.getElementById("full-screen").classList.toggle("active"); } function initUserControls() { // TODO: init user controls (save, restore, comment, rate) } export function init() { const zoomDelta = 0.2; document.getElementById("shrink").addEventListener("click", createSetZoomDeltaFunction(-zoomDelta)); document.getElementById("enlarge").addEventListener("click", createSetZoomDeltaFunction(zoomDelta)); document.getElementById("restore-size").addEventListener("click", resetZoom); document.getElementById("full-screen").addEventListener("click", toggleFullScreen); if (document.getElementById("save") !== null) { initUserControls(); } } export function adjustViewBox() { const svg = document.getElementById("riddle"); //noinspection JSUnresolvedFunction const bBox = svg.getBBox(); const x = -OFFSET; const y = -OFFSET; const width = bBox.width + 2 * OFFSET; const height = bBox.height + 2 * OFFSET; svg.setAttribute("viewBox", `${x} ${y} ${width} ${height}`); } export function createSvgElement(qualifiedName) { return document.createElementNS("http://www.w3.org/2000/svg", qualifiedName); } export function check(state, correctFallbackFunction) { const ajax = new XMLHttpRequest(); ajax.onreadystatechange = function () { if (ajax.readyState === 4 && ajax.status === 200) { const response = JSON.parse(ajax.responseText); if (response.correct === true) { correctFallbackFunction(); } } }; ajax.open("POST", "check/", true); ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajax.send(`state=${state}`); } export function updateStateInputValue(state) { document.getElementById("state").innerHTML = state; } <file_sep>/sudoku/views.py from django.http import Http404, HttpRequest, HttpResponse, JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from riddles.models import Riddle from sudoku.models import Sudoku def view_index(request) -> HttpResponse: return render(request, 'sudoku/index.html', { 'pks': list(sudoku.pk for sudoku in Riddle.objects.filter(riddle_type__name='sudoku')), }) def view_riddle(request: HttpRequest, sudoku_number: int) -> HttpResponse: try: sudoku = Sudoku.objects.get(pk=sudoku_number) except Riddle.DoesNotExist: raise Http404("Sudoku does not exist") context = sudoku.riddle.get_context(request.user) context.update({ 'box_rows': sudoku.box_rows, }) return render(request, 'sudoku/riddle.html', context) def view_creator(request: HttpRequest) -> HttpResponse: return render(request, 'sudoku/creator.html') @csrf_exempt @require_POST def rest_check(request: HttpRequest, riddle_id: int) -> JsonResponse: try: sudoku = Sudoku.objects.get(pk=riddle_id) except Sudoku.DoesNotExist: raise Http404("Sudoku does not exist") proposal = request.POST.get("proposal") correct = proposal is not None and proposal == sudoku.solution response = {'correct': correct} return JsonResponse(response) @require_POST def rest_create(request: HttpRequest) -> JsonResponse: error = [] if not request.user.has_perm("riddles.add_sudoku"): error.append("no permission") solution = request.POST.get("solution") pattern = request.POST.get("pattern") if solution is None: error.append("no solution") if pattern is None: error.append("no pattern") if error: return JsonResponse({'error': error}) riddle = Riddle(solution=solution, pattern=pattern, state=pattern, difficulty=5, box_rows=3) riddle.save() return JsonResponse({'pk': riddle.pk}) <file_sep>/riddles/util.py def is_square(num: int) -> bool: if num < 0: return False if num == 0 or num == 1: return True x = num // 2 seen = {x} while x * x != num: x = (x + (num // x)) // 2 if x in seen: return False seen.add(x) return True <file_sep>/riddlebase/urls.py from django.contrib import admin from django.urls import include, path import riddles.urls from base.views import index urlpatterns = [ path('', index, name='index'), path('admin/', admin.site.urls), path('riddles/', include(riddles.urls)), ] <file_sep>/riddles/urls.py from django.urls import include, path from . import views app_name = 'riddles' urlpatterns = [ path('', views.index, name='index'), path('category/<int:pk>/', views.category, name='category'), path('type/<int:pk>/', views.riddle_type, name='type'), path('riddle/<int:pk>/', views.riddle, name='riddle'), path('riddle/<int:pk>/check/', views.check, name='check'), ] <file_sep>/riddles/migrations/0001_initial.py # Generated by Django 3.1.3 on 2020-11-09 16:21 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='RiddleCategory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100, unique=True)), ('description', models.TextField()), ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='riddles.riddlecategory')), ], ), migrations.CreateModel( name='RiddleType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100, unique=True)), ('description', models.TextField()), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='riddles.riddlecategory')), ], ), migrations.CreateModel( name='Riddle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('solution', models.CharField(max_length=1000)), ('pattern', models.CharField(max_length=1000)), ('difficulty', models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10)])), ('created_on', models.DateTimeField(auto_now_add=True)), ('modified_on', models.DateTimeField(auto_now=True)), ('riddle_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='riddles.riddletype')), ], ), migrations.CreateModel( name='RiddleState', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.TextField()), ('modified_on', models.DateTimeField(auto_now=True)), ('riddle', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='riddles.riddle')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'unique_together': {('user', 'riddle')}, }, ), ] <file_sep>/sudoku/migrations/0001_initial.py # Generated by Django 2.1.1 on 2018-09-18 20:06 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('riddles', '0001_initial'), ] operations = [ migrations.CreateModel( name='Sudoku', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('box_rows', models.IntegerField(validators=[django.core.validators.MinValueValidator(2)], verbose_name='Number of horizontal box-rows')), ('riddle', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='riddles.Riddle')), ], ), ] <file_sep>/Dockerfile FROM python:3.8.6-alpine3.12 as python-base ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ PIP_NO_CACHE_DIR=off \ PIP_DISABLE_PIP_VERSION_CHECK=on \ PIP_DEFAULT_TIMEOUT=100 \ POETRY_VERSION=1.1.4 \ POETRY_HOME="/opt/poetry" \ POETRY_VIRTUALENVS_IN_PROJECT=true \ POETRY_NO_INTERACTION=1 \ PYSETUP_PATH="/opt/pysetup" \ VENV_PATH="/opt/pysetup/.venv" ENV PATH="$POETRY_HOME/bin:$VENV_PATH/bin:$PATH" FROM python-base as builder-base RUN wget -O - https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python WORKDIR $PYSETUP_PATH COPY poetry.lock pyproject.toml ./ RUN poetry install --no-dev FROM python-base as development ENV FASTAPI_ENV=development WORKDIR $PYSETUP_PATH COPY --from=builder-base $POETRY_HOME $POETRY_HOME COPY --from=builder-base $PYSETUP_PATH $PYSETUP_PATH RUN apk add --no-cache --update gcc musl-dev RUN poetry install WORKDIR /code/ EXPOSE 8000 CMD ["/code/entrypoint-dev.sh"] FROM python-base as production ENV FASTAPI_ENV=production COPY --from=builder-base $PYSETUP_PATH $PYSETUP_PATH COPY . /code/ WORKDIR /code/ CMD ["gunicorn", "--worker-class", "uvicorn.workers.UvicornWorker", "--host", "0.0.0.0", "--port", "8000", "myproject.asgi:application"] <file_sep>/.github/CONTRIBUTING.md # Code of Conduct See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) # How to Contribute to Open Source Want to contribute to open source?<br /> A guide to making open source contributions, for first-timers and for veterans:<br /> https://opensource.guide/ # Issues The preferred way of giving feedback is via GitHub Issues.<br /> You should choose one of the [Issue Templates](https://github.com/djbrown/riddlebase/issues/new/choose) # Developing Python ## Package Management If you want to add new dependencies to the project, make sure their license is compatible with the MIT license. This Project uses [Poetry](https://github.com/python-poetry/poetry) for managing Python Packages.<br /> Install new dependencies from pypi via `poetry add <PACKAGE>`. Add `--dev` flag for development dependencies. ## Format and Style Guide You can contribute to this Project using any IDE, Editor or Terminal you like, as long as your modifications obey the conventions defined by the [Style Guide for Python Code (PEP8)](https://www.python.org/dev/peps/pep-0008/). The following command will clean your code accordingly: `poetry run autopep8 -ir .` Also make sure to check messages from the following commands before proposing: * `poetry run mypy .` * `poetry run flake8` <file_sep>/sudoku/models.py import math from django.core.validators import MinValueValidator from django.db import models from riddles.models import Riddle class Sudoku(models.Model): riddle = models.OneToOneField(Riddle, on_delete=models.CASCADE) box_rows = models.IntegerField(verbose_name='Number of horizontal box-rows', validators=[ MinValueValidator(2)]) @property def cells(self) -> int: return len(self.riddle.solution) @property def size(self) -> int: return int(math.sqrt(self.cells)) @property def solution_as_list(self) -> list: return list(self.riddle.solution) @property def pattern_as_list(self) -> list: return list(self.riddle.pattern) @property def solution_as_two_dimensional_array(self) -> list: array = [] for row_i in range(self.size): cell_i = row_i * self.size row = list(self.riddle.solution[cell_i:cell_i + self.size]) array.append(row) return array @staticmethod def check_solution(pattern, solution) -> bool: raise NotImplementedError def __str__(self) -> str: return "Sudoku: {}".format(self.pk) <file_sep>/riddles/templatetags/templatetags.py from django import template register = template.Library() @register.filter def index(my_list: list, i: int): return my_list[int(i)] <file_sep>/riddles/views.py import datetime from django.conf import settings from django.http import Http404, HttpRequest, HttpResponse, JsonResponse from django.shortcuts import get_object_or_404, render from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from .models import Riddle, RiddleCategory, RiddleType def index(request: HttpRequest) -> HttpResponse: return render(request, 'riddles/index.html') def category(request: HttpRequest, pk: int) -> HttpResponse: riddle_category = get_object_or_404(RiddleCategory, pk=pk) return render(request, 'riddles/category.html', { "category": riddle_category, }) def riddle_type(request: HttpRequest, pk: int) -> HttpResponse: _riddle_type = get_object_or_404(RiddleType, pk=pk) return render(request, 'riddles/type.html', { "riddle_type": _riddle_type, }) def riddle(request: HttpRequest, pk: int) -> HttpResponse: riddle = get_object_or_404(Riddle, pk=pk) context = { 'riddle': riddle, 'previous': Riddle.objects.filter(pk__lt=pk).order_by('pk').last(), 'next': Riddle.objects.filter(pk__gt=pk).order_by('pk').first(), } state = request.POST.get('state', request.session.get('state', riddle.pattern)) if request.POST.get('revert'): state = riddle.pattern request.session['state'] = state context['state'] = state if state == riddle.solution: context['correct'] = True if request.POST.get('submit'): if state != riddle.solution: context['incorrect'] = True return render(request, 'riddles/riddle.html', context) @csrf_exempt @require_POST def check(request: HttpRequest, pk: int) -> JsonResponse: riddle = get_object_or_404(Riddle, pk=pk) state = request.POST.get("state") correct = state == riddle.solution response = {'correct': correct} return JsonResponse(response) <file_sep>/slither/views.py from django.http import Http404, HttpRequest, JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from slither.models import Slither def view_index(request): return render(request, 'slither/index.html', { 'pks': list(riddle.pk for riddle in Slither.objects.all()), }) def view_riddle(request, riddle_id): try: riddle = Slither.objects.get(pk=riddle_id) except Slither.DoesNotExist: raise Http404("Riddle does not exist") context = riddle.get_context(request.user) context.update({"breadth": riddle.breadth}) return render(request, 'slither/riddle.html', context) @csrf_exempt @require_POST def rest_check(request, riddle_id): try: riddle = Slither.objects.get(pk=riddle_id) except Slither.DoesNotExist: raise Http404("Riddle does not exist") proposal = request.POST.get("proposal") correct = proposal is not None and proposal == riddle.solution response = {'correct': correct} return JsonResponse(response) def view_creator(request): return render(request, 'slither/creator.html') @require_POST def rest_create(request: HttpRequest) -> JsonResponse: error = [] if not request.user.has_perm("riddles.add_slither"): error.append("no permission") solution = request.POST.get("slither") pattern = request.POST.get("pattern") if solution is None: error.append("no solution") if pattern is None: error.append("no pattern") if error: return JsonResponse({'error': error}) created = Slither(solution=solution, pattern=pattern, state=pattern, difficulty=5, box_rows=3) created.save() return JsonResponse({'id': created.id}) <file_sep>/base/views.py from django.shortcuts import render from riddles.models import RiddleCategory def index(request): context = { 'category_list': RiddleCategory.objects.all() } return render(request, 'index.html', context) <file_sep>/slither/migrations/0001_initial.py # Generated by Django 2.1.1 on 2018-09-14 01:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('riddles', '0001_initial'), ] operations = [ migrations.CreateModel( name='Slither', fields=[ ('riddle_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='riddles.Riddle')), ('width', models.IntegerField()), ('height', models.IntegerField()), ], bases=('riddles.riddle',), ), migrations.CreateModel( name='Square', fields=[ ('slither_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='slither.Slither')), ], bases=('slither.slither',), ), ] <file_sep>/pyproject.toml [tool.poetry] name = "riddlebase" version = "0.1.0" description = "A Web Platform for logic puzzle games" license = "MIT" authors = ["<NAME> <<EMAIL>>"] [tool.poetry.dependencies] python = "^3.7" Django = "^3.1.2" uvicorn = "^0.12.2" gunicorn = "^20.0.4" [tool.poetry.dev-dependencies] poethepoet = "^0.9.0" pytest = "^5.2" selenium = "^3.141.0" sauceclient = "^1.0.0" rope = "^0.18.0" mypy = "^0.790" autopep8 = "^1.5.4" pylint = "^2.6.0" pylint-django = "^2.3.0" bandit = "^1.6.2" flake8 = "^3.8.4" pylama = "^7.7.1" # prospector = "^1.3.1" coverage = "^5.3" codacy-coverage = "^1.3.11" codecov = "^2.1.10" coveralls = "^2.1.2" safety = "^1.9.0" dparse = "^0.5.1" ptpython = "^3.0.7" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" [tool.poe.tasks] riddlebase = "./manage.py runserver" test = "./manage.py test" coverage = "coverage run --branch --source=. --omit=*/migrations/* ./manage.py test" delmig = { shell = "find . -path \"*/migrations/*.py\" -not -name \"__init__.py\" -delete" } <file_sep>/slither/static/slither/js/riddle.js var RiddleManager; var Riddle = (function () { function createBorderClickFunction(row, column) { return function () { var picker = document.getElementById("picker"); var pickerIsOpen = !picker.classList.contains("hide"); if (select) { endSelection(); } var isClosing = select === this && pickerIsOpen; if (!isClosing) { select = this; startSelection(row, column); } }; } function addIndicator(parent, value, x, y, id, classNames) { var indicator = RiddleManager.createSvgElement("text"); indicator.setAttribute("id", id); indicator.setAttribute("x", x); indicator.setAttribute("y", y); classNames.forEach(function (className) { indicator.classList.add(className); }); var textNode = document.createTextNode(value); indicator.appendChild(textNode); parent.appendChild(indicator); } function addRiddleCell(pattern, state, row, column, numbers) { var indicatorsGroup = document.getElementById("riddle-indicators"); var cell = RiddleManager.createSvgElement("g"); cell.classList.add("riddle-cell"); var size = RiddleManager.RIDDLE_CELL_SIZE; var x = size * column; var y = size * row; var transform = "translate(" + x + ", " + y + ")"; cell.setAttribute("transform", transform); var classNames = ["value", "riddle-cell-value"]; var value = pattern[row * numbers + column]; if (value === "-") { value = state[row * numbers + column]; classNames.push("state"); cell.classList.add("state"); if (value === "-") { value = ""; } } else { classNames.push("pattern"); cell.classList.add("pattern"); } addRect(cell, 0, 0, size, size, ["riddle-cell-background"]); var textX = size / 2; var textY = size / 2; var id = "riddle-value-" + row + "-" + column; addIndicator(cell, value, textX, textY, id, classNames); if (classNames.indexOf("state") !== -1) { var riddleCellClickFunction = createBorderClickFunction(row, column); cell.addEventListener("click", riddleCellClickFunction); } indicatorsGroup.appendChild(cell); } function createIndicators(indicators, breadth) { var diagonale = breadth * 2 - 1; for (var row = 0; row < diagonale; row++) { var columns = breadth + row; for (var column = 0; column < columns; column++) { addRiddleCell(); } columns++; } } function addBorder(parent, x, y, size, orientation, isBold, classNames) { var border = RiddleManager.createSvgElement("line"); border.setAttribute("stroke-linecap", "square"); border.classList.add("border"); classNames.forEach(function (className) { border.classList.add(className); }); if (isBold) { border.classList.add("bold"); } var x2 = x; var y2 = y; if (orientation === "h") { x2 += size; } else if (orientation === "v") { y2 += size; } else { throw "Invalid border orientation: '" + orientation + "'" + " (expected 'h' or 'v'"; } border.setAttribute("x1", x); border.setAttribute("y1", y); border.setAttribute("x2", x2); border.setAttribute("y2", y2); parent.appendChild(border); } function createRiddleGridRow(numbers, size, row, boxColumns, boxRows, gridBold, gridThin, classNames) { var y = size * row; for (var column = 0; column < numbers; column++) { var x = size * column; var isVBoxBorder = column % boxColumns === 0; var isHBoxBorder = row % boxRows === 0; var vGrid = isVBoxBorder ? gridBold : gridThin; var hGrid = isHBoxBorder ? gridBold : gridThin; addBorder(vGrid, x, y, size, "v", isVBoxBorder, classNames); addBorder(hGrid, x, y, size, "h", isHBoxBorder, classNames); } // create rightmost vertical border addBorder(gridBold, size * numbers, y, size, "v", true, classNames); } function createGrid(numbers, boxRows, boxColumns) { var gridThin = document.getElementById("riddle-grid-thin"); var gridBold = document.getElementById("riddle-grid-bold"); var size = RiddleManager.RIDDLE_CELL_SIZE; var classNames = []; for (var row = 0; row < numbers; row++) { createRiddleGridRow(numbers, size, row, boxColumns, boxRows, gridBold, gridThin, classNames); } // create lowest horizontal borders for (var column = 0; column < numbers; column++) { var lastRowBorderX = size * column; var lastRowBorderY = size * numbers; addBorder(gridBold, lastRowBorderX, lastRowBorderY, size, "h", true, classNames); } } function showWinningAnimation() { var backgrounds = document.getElementsByClassName("riddle-cell-background"); for (var i = 0; i < backgrounds.length; i++) { backgrounds[i].classList.add("winning"); } } function propose() { var proposal = ""; var cellValues = document.getElementsByClassName("riddle-cell-value"); for (var i = 0; i < cellValues.length; i++) { var cellValue = cellValues[i].innerHTML; if (cellValue.trim() === "") { return; } else { proposal += cellValue; } } RiddleManager.check(proposal, showWinningAnimation); } function init(pattern, indicators, state, breadth) { createIndicators(indicators, breadth); createGrid(pattern, state, breadth); } return { init }; }()); <file_sep>/README.md # RiddleBase [![Travis-CI Build Status](https://travis-ci.org/djbrown/riddlebase.svg?branch=master)](https://travis-ci.org/djbrown/riddlebase) [![Docker Hub Build Status](https://img.shields.io/docker/build/djbrown/riddlebase.svg)](https://hub.docker.com/r/djbrown/riddlebase/builds/) [![Coveralls Coverage Status](https://coveralls.io/repos/github/djbrown/riddlebase/badge.svg)](https://coveralls.io/github/djbrown/riddlebase) [![Codecov Coverage Status](https://codecov.io/github/djbrown/riddlebase/coverage.svg)](http://codecov.io/github/djbrown/riddlebase/) [![Codacy Quality Status](https://api.codacy.com/project/badge/Grade/9c0920594c0544d9b63caf9fab3970d8)](https://www.codacy.com/app/djbrown/riddlebase?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=djbrown/riddlebase&amp;utm_campaign=Badge_Grade) [![Mypy Badge](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/) [![Sauce Test Status](https://saucelabs.com/buildstatus/djbrown-riddlebase)](https://saucelabs.com/u/djbrown-riddlebase) [![FOSSA License Status](https://app.fossa.com/api/projects/custom%2B5488%2Fgithub.com%2Fdjbrown%2Friddlebase.svg?type=shield)](https://app.fossa.com/projects/custom%2B5488%2Fgithub.com%2Fdjbrown%2Friddlebase?ref=badge_shield) [![Sauce Labs Browsers](https://saucelabs.com/browser-matrix/djbrown-riddlebase.svg)](https://saucelabs.com/u/djbrown-riddlebase) This is a Web Platform for logic puzzle games. RiddleBase is powered by Django [<img src="https://www.djangoproject.com/m/img/logos/django-logo-positive.svg" height="50" alt="Django Logo"/>](https://www.djangoproject.com/) ## Running via Docker `docker run -p 8000:8000 djbrown/riddlebase`<br/> Container is reachable under [127.0.0.1:8000](http://127.0.0.1:8000) ## Running natively ### Requirements 1. Python 3.8 (easy via [pyenv](https://github.com/pyenv/pyenv/)) 2. [poetry](https://github.com/python-poetry/poetry) ### Installation `poetry install`<br/> `poetry run ./manage.py migrate` ### Start Application `poetry run ./manage.py runserver` ## License The project is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). [![FOSSA License Report](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fdjbrown%2Friddlebase.svg?type=large)](https://app.fossa.com/projects/custom%2B5488%2Fgithub.com%2Fdjbrown%2Friddlebase?ref=badge_large) ## Contributing See [CONTRIBUTING.md](.github/CONTRIBUTING.md) <file_sep>/riddles/static/riddles/js/sudoku.js import * as RiddleManager from './riddle-manager.js'; let select; function hidePicker() { document.getElementById("picker").classList.add("picker-hidden"); } function hideSelectionHighlight() { select.classList.remove("selected"); } function endSelection() { hidePicker(); hideSelectionHighlight(); } function showPicker(row, column) { const picker = document.getElementById("picker"); //noinspection JSUnresolvedFunction const pickerWidth = picker.getBBox().width; //noinspection JSUnresolvedFunction const pickerHeight = picker.getBBox().height; const svg = document.getElementById("riddle"); //noinspection JSUnresolvedFunction const svgWidth = svg.getBBox().width; //noinspection JSUnresolvedFunction const svgHeight = svg.getBBox().height; const size = RiddleManager.RIDDLE_CELL_SIZE; let pickerX = size * (column + 1); let pickerY = size * (row + 1); if (pickerX + pickerWidth > svgWidth) { pickerX = (size * (column - 1)) - pickerWidth; } if (pickerY + pickerHeight > svgHeight) { pickerY = (size * (row - 1)) - pickerHeight; } const transform = "translate(" + pickerX + ", " + pickerY + ")"; picker.setAttribute("transform", transform); picker.classList.remove("picker-hidden"); } function showSelectionHighlight() { select.classList.add("selected"); } function startSelection(row, column) { showPicker(row, column); showSelectionHighlight(); } function createRiddleCellClickFunction(row, column) { return function () { const picker = document.getElementById("picker"); const pickerIsOpen = !picker.classList.contains("picker-hidden"); if (select) { endSelection(); } const isClosing = select === this && pickerIsOpen; if (!isClosing) { select = this; startSelection(row, column); } }; } function addRect(parent, x, y, width, height, classNames) { const rect = RiddleManager.createSvgElement("rect"); rect.setAttribute("x", x); rect.setAttribute("y", y); rect.setAttribute("width", width); rect.setAttribute("height", height); classNames.forEach(function (className) { rect.classList.add(className); }); parent.appendChild(rect); } function addText(parent, value, x, y, id, classNames) { const text = RiddleManager.createSvgElement("text"); text.setAttribute("id", id); text.setAttribute("x", x); text.setAttribute("y", y); classNames.forEach(function (className) { text.classList.add(className); }); const textNode = document.createTextNode(value); text.appendChild(textNode); parent.appendChild(text); } function addRiddleCell(pattern, state, row, column, numbers) { const values = document.getElementById("riddle-values"); const cell = RiddleManager.createSvgElement("g"); cell.classList.add("riddle-cell"); const size = RiddleManager.RIDDLE_CELL_SIZE; const x = size * column; const y = size * row; const transform = "translate(" + x + ", " + y + ")"; cell.setAttribute("transform", transform); const classNames = ["value", "riddle-cell-value"]; let value = pattern[row * numbers + column]; if (value === "-") { value = state[row * numbers + column]; classNames.push("state"); cell.classList.add("state"); if (value === "-") { value = ""; } } else { classNames.push("pattern"); cell.classList.add("pattern"); } addRect(cell, 0, 0, size, size, ["riddle-cell-background"]); const textX = size / 2; const textY = size / 2; const id = "riddle-value-" + row + "-" + column; addText(cell, value, textX, textY, id, classNames); if (classNames.indexOf("state") !== -1) { const riddleCellClickFunction = createRiddleCellClickFunction(row, column); cell.addEventListener("click", riddleCellClickFunction); } values.appendChild(cell); } function createRiddleCells(pattern, state) { const numbers = Math.sqrt(pattern.length); for (let row = 0; row < numbers; row++) { for (let column = 0; column < numbers; column++) { addRiddleCell(pattern, state, row, column, numbers); } } } function addBorder(parent, x, y, size, orientation, isBold, classNames) { const border = RiddleManager.createSvgElement("line"); border.setAttribute("stroke-linecap", "square"); border.classList.add("border"); classNames.forEach(function (className) { border.classList.add(className); }); if (isBold) { border.classList.add("bold"); } let x2 = x; let y2 = y; if (orientation === "h") { x2 += size; } else if (orientation === "v") { y2 += size; } else { throw "Invalid border orientation: '" + orientation + "'" + " (expected 'h' or 'v'"; } border.setAttribute("x1", x); border.setAttribute("y1", y); border.setAttribute("x2", x2); border.setAttribute("y2", y2); parent.appendChild(border); } function createRiddleGridRow(numbers, size, row, boxColumns, boxRows, gridBold, gridThin, classNames) { const y = size * row; for (let column = 0; column < numbers; column++) { const x = size * column; const isVBoxBorder = column % boxColumns === 0; const isHBoxBorder = row % boxRows === 0; const vGrid = isVBoxBorder ? gridBold : gridThin; const hGrid = isHBoxBorder ? gridBold : gridThin; addBorder(vGrid, x, y, size, "v", isVBoxBorder, classNames); addBorder(hGrid, x, y, size, "h", isHBoxBorder, classNames); } // create rightmost vertical border addBorder(gridBold, size * numbers, y, size, "v", true, classNames); } function createRiddleGrid(numbers, boxRows, boxColumns) { const gridThin = document.getElementById("riddle-grid-thin"); const gridBold = document.getElementById("riddle-grid-bold"); const size = RiddleManager.RIDDLE_CELL_SIZE; const classNames = []; for (let row = 0; row < numbers; row++) { createRiddleGridRow(numbers, size, row, boxColumns, boxRows, gridBold, gridThin, classNames); } // create lowest horizontal borders for (let column = 0; column < numbers; column++) { const lastRowBorderX = size * column; const lastRowBorderY = size * numbers; addBorder(gridBold, lastRowBorderX, lastRowBorderY, size, "h", true, classNames); } } function showWinningAnimation() { const backgrounds = document.getElementsByClassName("riddle-cell-background"); for (let i = 0; i < backgrounds.length; i++) { backgrounds[i].classList.add("winning"); } } function gatherState() { let state = ""; const cellValues = document.getElementsByClassName("riddle-cell-value"); for (let i = 0; i < cellValues.length; i++) { const cellValue = cellValues[i].innerHTML; if (cellValue.trim() === "") { state += "-"; } else { state += cellValue; } } return state; } function check() { let state = ""; const cellValues = document.getElementsByClassName("riddle-cell-value"); for (let i = 0; i < cellValues.length; i++) { const cellValue = cellValues[i].innerHTML; if (cellValue.trim() === "") { return; } else { state += cellValue; } } RiddleManager.check(state, showWinningAnimation); } function createPickerCellClickFunction(value) { return function () { const text = select.getElementsByClassName("riddle-cell-value")[0]; text.innerHTML = value; const stateInput = document.getElementById("state"); const state = gatherState(); stateInput.value = state; endSelection(); check(); }; } function addPickerCell(value, row, column) { const values = document.getElementById("picker-values"); const cell = RiddleManager.createSvgElement("g"); cell.classList.add("picker-cell"); const size = RiddleManager.PICKER_CELL_SIZE; const x = size * column; const y = size * row; const transform = "translate(" + x + ", " + y + ")"; cell.setAttribute("transform", transform); addRect(cell, 0, 0, size, size, ["picker-cell-background"]); const textX = size / 2; const textY = size / 2; const textId = "picker-value-" + value; const textClassNames = ["value", "picker-value"]; addText(cell, value, textX, textY, textId, textClassNames); const pickerCellClickFunction = createPickerCellClickFunction(value); cell.addEventListener("click", pickerCellClickFunction); values.appendChild(cell); } function calculatePickerSize(numbers) { let rows = Math.sqrt(numbers); let columns = rows; rows = Math.ceil(rows); columns = Math.round(columns); return { rows, columns }; } function createPickerCells(numbers) { const pickerSpecs = calculatePickerSize(numbers); const rows = pickerSpecs.rows; const columns = pickerSpecs.columns; let value = 1; for (let row = 0; row < rows; row++) { for (let column = 0; column < columns; column++) { if (value <= numbers) { addPickerCell(value, row, column); } value++; } } } function createPickerGridRow(columns, size, row, gridOuter, gridInner, borderClassNames) { const y = size * row; for (let column = 0; column < columns; column++) { const x = size * column; const isVBoxBorder = column === 0; const isHBoxBorder = row === 0; const vGrid = isVBoxBorder ? gridOuter : gridInner; const hGrid = isHBoxBorder ? gridOuter : gridInner; addBorder(vGrid, x, y, size, "v", isVBoxBorder, borderClassNames); addBorder(hGrid, x, y, size, "h", isHBoxBorder, borderClassNames); } addBorder(gridOuter, size * columns, y, size, "v", true, borderClassNames); } function createPickerGrid(numbers) { const gridInner = document.getElementById("picker-grid-inner"); const gridOuter = document.getElementById("picker-grid-outer"); const values = document.getElementById("picker-values"); // TODO: write Tests for row and column calculation const size = RiddleManager.PICKER_CELL_SIZE; const pickerSpecs = calculatePickerSize(numbers); const rows = pickerSpecs.rows; const columns = pickerSpecs.columns; const borderClassNames = ["picker-border"]; for (let row = 0; row < rows; row++) { createPickerGridRow(columns, size, row, gridOuter, gridInner, borderClassNames); } for (let column = 0; column < columns; column++) { addBorder(gridOuter, size * column, size * rows, size, "h", true, borderClassNames); } //noinspection JSUnresolvedFunction const bBox = document.getElementById("picker").getBBox(); const background = document.getElementById("picker-background"); background.setAttribute("width", bBox.width); background.setAttribute("height", bBox.height); } export function init(pattern, state, boxRows = Math.pow(pattern.length, 1 / 4)) { const numbersCount = Math.sqrt(pattern.length); const boxColumns = numbersCount / boxRows; createRiddleCells(pattern, state); createRiddleGrid(numbersCount, boxRows, boxColumns); createPickerCells(numbersCount); createPickerGrid(numbersCount); hidePicker(); check(); } <file_sep>/.pylintrc [MASTER] load-plugins = django max-line-length = 120 <file_sep>/sudoku/admin.py from django.contrib import admin from .models import Sudoku admin.site.register(Sudoku) <file_sep>/slither/apps.py from django.apps import AppConfig class SlitherConfig(AppConfig): name = 'slither' <file_sep>/slither/models.py from django.db import models from riddles.models import Riddle class Slither(Riddle): width = models.IntegerField() height = models.IntegerField() @staticmethod def check_solution(pattern: str, solution: str) -> bool: pass class Square(Slither): pass <file_sep>/riddles/tests/test_util.py from django.test import TestCase from riddles import util class TestIsSquare(TestCase): # Square numbers def test_0_is_square(self): self.assertTrue(util.is_square(0)) def test_1_is_square(self): self.assertTrue(util.is_square(1)) def test_4_is_square(self): self.assertTrue(util.is_square(4)) def test_9_is_square(self): self.assertTrue(util.is_square(9)) def test_81_is_square(self): self.assertTrue(util.is_square(81)) # Non square numbers def test_2_is_not_square(self): self.assertFalse(util.is_square(2)) def test_500_is_not_square(self): self.assertFalse(util.is_square(500)) # Negative numbers def test_neg0_is_square(self): self.assertTrue(util.is_square(-0)) def test_neg1_is_not_square(self): self.assertFalse(util.is_square(-1)) def test_neg2_is_not_square(self): self.assertFalse(util.is_square(-2)) def test_neg81_is_not_square(self): self.assertFalse(util.is_square(-81)) def test_neg500_is_not_square(self): self.assertFalse(util.is_square(-500)) class TestDummy(TestCase): def test_dummy(self): self.assertTrue(True) <file_sep>/riddles/admin.py from django.contrib import admin from riddles.models import Riddle, RiddleCategory, RiddleState, RiddleType admin.site.register(RiddleCategory) admin.site.register(RiddleType) admin.site.register(Riddle) admin.site.register(RiddleState) <file_sep>/sudoku/urls.py from django.conf.urls import url from . import views app_name = 'sudoku' urlpatterns = [ url(r'^$', views.view_index, name='index'), url(r'^(?P<riddle_id>[0-9]+)/$', views.view_riddle, name='riddle'), url(r'^(?P<riddle_id>[0-9]+)/check/$', views.rest_check, name='check'), url(r'^create/$', views.view_creator, name='creator'), url(r'^submit-new/$', views.rest_create, name='create'), ] <file_sep>/sudoku/static/sudoku/js/creator.js var Creator = (function () { var csrfToken; function handleSubmitResponse(json) { } function submit() { var ajax = new XMLHttpRequest(); ajax.onreadystatechange = function () { if (ajax.readyState === 4 && ajax.status === 200) { handleSubmitResponse(JSON.parse(ajax.responseText)) } }; ajax.open("POST", "../submit-new/", true); ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajax.setRequestHeader("X-CSRFToken", csrfToken); var data = "solution=123"; data += "&pattern=123"; ajax.send(data); } function init(_csrfToken) { csrfToken = _csrfToken; var submitButton = document.getElementById("submit"); submitButton.addEventListener("click", submit); } return { init } }());<file_sep>/riddles/models.py from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from riddles import util class RiddleCategory(models.Model): name = models.CharField(max_length=100, unique=True) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) description = models.TextField() def clean(self): if self.parent == self: raise ValidationError('You cannot set the parent to the object itself.') def __str__(self): return self.name class RiddleType(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField() category = models.ForeignKey(RiddleCategory, on_delete=models.CASCADE) def __str__(self): return self.name class Riddle(models.Model): riddle_type = models.ForeignKey(RiddleType, on_delete=models.CASCADE) solution = models.CharField(max_length=1000) pattern = models.CharField(max_length=1000) difficulty = models.PositiveSmallIntegerField(blank=True, null=True, validators=[ MinValueValidator(1), MaxValueValidator(10)]) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) def previous_pk(self): previous_set = Riddle.objects.filter(pk__lt=self.pk).order_by('-pk') return previous_set[0].pk if previous_set else None def next_pk(self): next_set = Riddle.objects.filter(pk__gt=self.pk).order_by('pk') return next_set[0].pk if next_set else None def clean(self): pat_len = len(self.pattern) sol_len = len(self.solution) if pat_len != sol_len: raise ValidationError('Pattern length does not match solution length.') if not util.is_square(pat_len): raise ValidationError('Riddle value length is not square.') def get_or_create_state(self, user: User) -> str: state_values = self.pattern if user.is_authenticated(): try: state = self.riddlestate state_values = state.values except ObjectDoesNotExist: state = RiddleState(user=user, riddle=self, values=self.pattern) state.save() state_values = state.values return state_values def __str__(self): return f"{self.riddle_type.name} {self.pk}" class RiddleState(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) riddle = models.ForeignKey(Riddle, on_delete=models.CASCADE) value = models.TextField() modified_on = models.DateTimeField(auto_now=True) class Meta: unique_together = ("user", "riddle") def __str__(self) -> str: return f"{self.riddle.riddle_type.name} {self.riddle.pk} {self.user.name}"
9076a8f1bc07b21721691a58a4c2e8617f801a23
[ "JavaScript", "Markdown", "TOML", "INI", "Python", "Dockerfile", "Shell" ]
29
Shell
djbrown/riddlebase
b2260f96024c687e5d7cb32021938a706d3ed388
29284cfaf7f31ffa550b05f94e10046b30a6e755
refs/heads/master
<file_sep>package edu.usna.mobileos.project; public class Report { String type, desc, reporter; String timestamp; String location; public Report(String type, String desc, String reporter, String location, String timestamp) { this.type = type; this.desc = desc; this.location = location; this.timestamp = timestamp; this.reporter = reporter; } public String getDesc() { return desc; } public String getType() { return type; } public String getReporter() { return reporter; } public String getLocation() { return location; } public String getTimestamp() { return timestamp; } public void setDesc(String desc) { this.desc = desc; } public void setLocation(String location) { this.location = location; } public void setType(String type) { this.type = type; } public void updateDesc(String update) { this.desc += "\n\n" + update; } public String toString() { return "[" + timestamp + "] " + type; } }<file_sep>package edu.usna.mobileos.project; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.json.JSONObject; import java.net.HttpURLConnection; public class LoginActivity extends AppCompatActivity { private String username, password, fname, lname, phone; boolean loggedIn, admin = false; EditText userField, passField; HttpURLConnection server = null; String TAG = "IT472"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // if saved credentials exist, // load them into the EditText fields and execute the login() method } @Override protected void onResume() { super.onResume(); Log.i(TAG, "LoginActivity: onResume()"); } @Override protected void onPause() { super.onPause(); Log.i(TAG, "LoginActivity: onPause()"); } @Override protected void onDestroy() { super.onDestroy(); HttpConnections.endConnection(server); Log.i(TAG, "LoginActivity: onDestroy()"); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch(id) { case R.id.about: // create and show a Dialog that describes the app Bundle bundle = new Bundle(); bundle.putString("title", "About"); bundle.putInt("layout", R.layout.about); bundle.putString("message", getString(R.string.about)); CustomDialogFragment f1 = CustomDialogFragment.newInstance(bundle); f1.show(getSupportFragmentManager(), "AboutDialogFragment"); //Toast.makeText(getBaseContext(), "About selected", Toast.LENGTH_SHORT).show(); break; default: return super.onOptionsItemSelected(item); } return true; } public void login(View v) { // get the username and password input fields userField = findViewById(R.id.username); passField = findViewById(R.id.password); // get the username and password from the appropriate fields username = userField.getText().toString(); password = passField.getText().toString(); // unset the username and password fields userField = null; passField = null; final String urlString = HttpConnections.serverURL + "app/login.php"; Thread loginThread = new Thread() { @Override public void run() { server = HttpConnections.establishConnection(urlString); if(server != null) { boolean connected = HttpConnections.writeToConnection(server, "username", username, "password", password); password = <PASSWORD>; if(connected) { try { JSONObject jsonObject = new JSONObject(HttpConnections.readFromConnection(server)); //Log.i(TAG, jsonObject.toString()); loggedIn = jsonObject.getString("un").compareTo("null") != 0; //Log.i(TAG, "Username: " + jsonObject.getString("un")); admin = jsonObject.getInt("admin") == 1; //Log.i(TAG, "Admin: " + jsonObject.getInt("admin")); // FIXME: separate user_info from user_auth; database redesign fname = jsonObject.getString("first"); lname = jsonObject.getString("last"); phone = jsonObject.getString("phone"); } catch (Exception e) { e.printStackTrace(); } //Log.i(TAG, "Logged in: " + (loggedIn ? "true" : "false")); } } HttpConnections.endConnection(server); } }; loginThread.start(); try { loginThread.join(); if(loggedIn) { Toast.makeText(getBaseContext(), "Login success", Toast.LENGTH_SHORT).show(); // go to the dashboard Intent intent = new Intent(getBaseContext(), DashboardActivity.class); // send relevant info to dashboard intent.putExtra("username", username); intent.putExtra("admin", admin); intent.putExtra("first", fname); intent.putExtra("last", lname); intent.putExtra("phone", phone); // start DashboardActivity and end LoginActivity startActivity(intent); finish(); } else { Toast.makeText(getBaseContext(), "Incorrect username or password", Toast.LENGTH_SHORT).show(); } } catch (InterruptedException e) { e.printStackTrace(); } } public void register(View v) { // final String urlString = HttpConnections.serverURL + "app/register.php"; // start RegisterActivity //Toast.makeText(getBaseContext(), "Redirecting to registration page...", Toast.LENGTH_SHORT).show(); startActivity(new Intent(getBaseContext(), RegisterActivity.class)); } }<file_sep>package edu.usna.mobileos.project; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; class HttpConnections { // static String serverURL = "http://midn.cs.usna.edu/~m197116/"; static String serverURL = "http://ec2-52-15-192-159.us-east-2.compute.amazonaws.com/"; static HttpURLConnection establishConnection(String targetURL) { // connect to the server HttpURLConnection urlConnection = null; try { URL url = new URL(targetURL); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("GET"); } catch (Exception e) { e.printStackTrace(); } return urlConnection; } static boolean writeToConnection(HttpURLConnection conn, String... content) { conn.setDoOutput(true); try { OutputStream out = new BufferedOutputStream(conn.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8)); String data = ""; for(int i=0; i<content.length; i+=2) { data += content[i] + "=" + URLEncoder.encode(content[i+1], "UTF-8") + "&"; } writer.write(data); writer.flush(); writer.close(); out.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } static String readFromConnection(HttpURLConnection conn) { StringBuilder builder = new StringBuilder(); try { InputStream content = new BufferedInputStream(conn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } catch (Exception e) { e.printStackTrace(); } return builder.toString(); } static void endConnection(HttpURLConnection conn) { if(conn != null) { conn.disconnect(); } } }
73225be7c323827ffbe17a8454e4b035496cb519
[ "Java" ]
3
Java
TheRealVincentXu/First-Response
0aab13a5f44ba96c94fcdc5e8356dc50322706af
a8b96bd59993fc689f9904a31fe25ee2f0b2e767
refs/heads/master
<repo_name>Sharmajay89/openchat<file_sep>/README.md # openchat Open chat application using firebase <file_sep>/app/src/main/java/com/service/openchat/activity/ChatActivity.java package com.service.openchat.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.service.openchat.LoginActivity; import com.service.openchat.R; import com.service.openchat.Util; import com.service.openchat.adapter.ChatFirebaseAdapter; import com.service.openchat.adapter.ClickListenerChatFirebase; import com.service.openchat.model.ChatModel; import com.service.openchat.model.UserModel; import java.util.Calendar; import hani.momanii.supernova_emoji_library.Actions.EmojIconActions; import hani.momanii.supernova_emoji_library.Helper.EmojiconEditText; /* This is use as a chat screen in openchat application created by avishvakarma */ public class ChatActivity extends AppCompatActivity implements View.OnClickListener , ClickListenerChatFirebase { //Firebase and GoogleApiClient private FirebaseAuth mFirebaseAuth; private FirebaseUser mFirebaseUser; private DatabaseReference mFirebaseDatabaseReference; FirebaseStorage storage = FirebaseStorage.getInstance(); static final String CHAT_REFERENCE = "chatmodel"; //CLass Model private UserModel userModel; //Views UI private RecyclerView rvListMessage; private LinearLayoutManager mLinearLayoutManager; private ImageView btSendMessage,btEmoji; private EmojiconEditText edMessage; private View contentRoot; private EmojIconActions emojIcon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); if (!Util.verificaConexao(this)){ Util.initToast(this,"Você não tem conexão com internet"); finish(); }else{ bindViews(); verifyLogedInUser(); } } /** * Vincular views com Java API */ private void bindViews(){ contentRoot = findViewById(R.id.contentRoot); edMessage = (EmojiconEditText)findViewById(R.id.editTextMessage); btSendMessage = (ImageView)findViewById(R.id.buttonMessage); btSendMessage.setOnClickListener(ChatActivity.this); btEmoji = (ImageView)findViewById(R.id.buttonEmoji); emojIcon = new EmojIconActions(this,contentRoot,edMessage,btEmoji); emojIcon.ShowEmojIcon(); rvListMessage = (RecyclerView)findViewById(R.id.messageRecyclerView); mLinearLayoutManager = new LinearLayoutManager(this); mLinearLayoutManager.setStackFromEnd(true); } public void verifyLogedInUser(){ mFirebaseAuth = FirebaseAuth.getInstance(); mFirebaseUser = mFirebaseAuth.getCurrentUser(); if (mFirebaseUser == null){ startActivity(new Intent(this, LoginActivity.class)); finish(); }else{ String uEmailId = mFirebaseUser.getEmail(); String uname = null; String uId= null; String uProfilePic= null; if(mFirebaseUser.getDisplayName()!= null){ uname = mFirebaseUser.getDisplayName(); } if(mFirebaseUser.getUid()!= null){ uId = mFirebaseUser.getUid(); } if(mFirebaseUser.getPhotoUrl()!= null){ uProfilePic = mFirebaseUser.getPhotoUrl().toString(); } userModel = new UserModel(uname!= null?uname:uEmailId,uProfilePic != null?uProfilePic:"https://www.google.co.in/imgres?imgurl=https%3A%2F%2Fmedia.licdn.com%2Fmpr%2Fmpr%2Fshrinknp_200_200%2FAAEAAQAAAAAAAAdCAAAAJDQyMmY0OWJjLWMyOTAtNDlkYS1iNThmLTRjODg0YzY1NmM2NQ.jpg&imgrefurl=https%3A%2F%2Fin.linkedin.com%2Fin%2Fajaya-vishvakarma-84538954&docid=OAu_nYNbcdF0HM&tbnid=uz9si_1iQ6docM%3A&vet=10ahUKEwiB3cqQ2e_UAhUBuI8KHS27BmQQMwgiKAAwAA..i&w=200&h=200&itg=1&bih=810&biw=1440&q=ajaya%20vishvakarma&ved=0ahUKEwiB3cqQ2e_UAhUBuI8KHS27BmQQMwgiKAAwAA&iact=mrc&uact=8", uId!= null?uId:"531265374779312ID" ); fetchMessagensFirebase(); } } /** * fetch collections chatmodel Firebase */ private void fetchMessagensFirebase(){ mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference(); final ChatFirebaseAdapter firebaseAdapter = new ChatFirebaseAdapter(mFirebaseDatabaseReference.child(CHAT_REFERENCE),userModel.getName(),this); firebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); int friendlyMessageCount = firebaseAdapter.getItemCount(); int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition(); if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1) && lastVisiblePosition == (positionStart - 1))) { rvListMessage.scrollToPosition(positionStart); } } }); rvListMessage.setLayoutManager(mLinearLayoutManager); rvListMessage.setAdapter(firebaseAdapter); } /** * Enviar msg de texto simples para chat */ private void sendMessageFirebase(){ ChatModel model = new ChatModel(userModel,edMessage.getText().toString(), Calendar.getInstance().getTime().getTime()+"",null); mFirebaseDatabaseReference.child(CHAT_REFERENCE).push().setValue(model); edMessage.setText(null); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.buttonMessage: sendMessageFirebase(); break; } } @Override public void clickImageChat(View view, int position, String nameUser, String urlPhotoUser, String urlPhotoClick) { } @Override public void clickImageMapChat(View view, int position, String latitude, String longitude) { } }
38103f100e8c0fda0b2a36ea90a4e6489e78b84e
[ "Markdown", "Java" ]
2
Markdown
Sharmajay89/openchat
fb121504664762f436a93aa652a69f15f1cf44ab
09ad6f679dfc3f83aee93e941a8679981b665ac0
refs/heads/master
<file_sep>package aj.custom.graph; public interface Graph { void addEdge(Node n1, Node n2); void add(Node n1); }
9a189bd0632e50b06c1efda9d294791311c05821
[ "Java" ]
1
Java
Ashwin1421/Expression-Tree
9c5b896bdcbe722ee892183d3a97870790d338de
40c35fde3e54e6207985c98bdd7051de12642645
refs/heads/master
<file_sep>package com.example.milan.slider; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.Spinner; import info.androidhive.introslider.R; /** * Created by XMAN on 3.12.2016. */ public class ProfileActivity extends AppCompatActivity { private ImageButton signup; private PrefManager prefManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); prefManager = new PrefManager(this); if (!prefManager.isFirstTimeLaunch()) { launchGuideScreen(); finish(); } signup = (ImageButton) findViewById(R.id.cal); signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchGuideScreen(); } }); } private void launchGuideScreen() { prefManager.setFirstTimeLaunch(true); startActivity(new Intent(ProfileActivity.this, EventsActivity.class)); finish(); } } <file_sep>package com.example.milan.slider; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.os.Bundle; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import info.androidhive.introslider.R; /** * Created by XMAN on 3.12.2016. */ public class GuideActivity extends AppCompatActivity { private Button next; private PrefManager prefManager; private CheckBox ch; private EditText et; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_guide); prefManager = new PrefManager(this); if (!prefManager.isFirstTimeLaunch()) { launchCategoryScreen(); finish(); } next = (Button) findViewById(R.id.btnNext); ch = (CheckBox) findViewById(R.id.checkBox1); et = (EditText) findViewById(R.id.edit); et.setVisibility(View.VISIBLE); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchCategoryScreen(); } }); ch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(ch.isChecked()){ et.setVisibility(View.VISIBLE); }else{ et.setVisibility(View.GONE); } } }); } private void launchCategoryScreen() { prefManager.setFirstTimeLaunch(true); startActivity(new Intent(GuideActivity.this, ProfileActivity.class)); finish(); } }
75ef3a0f792f7b9d76cd7893bb53f05c0c031475
[ "Java" ]
2
Java
hdzana/Volunteer
7f9208c0a129b78f3bcfaccff7047fdf23ba650f
48338fdb31a917a47c059f35ec7e7e0c9abeb162
refs/heads/main
<file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include <stdlib.h> //EXIT_SUCCESS #include <signal.h> //sigaction() #include <stdbool.h> //bool bool running = 1; void stop_handler( int sig ) { printf("\n Signal %d reçu.\n", sig); running = 0; return; } struct sigaction act; // act.sa_handler = stop_handler; // act.sa_flags = 0; void exit_message() { printf("\nExit Message ! \n"); } int main() { printf("Avant la boucle...\n"); act.sa_handler = stop_handler; act.sa_flags = 0; sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); // SIGTERM; kill <pid> affiche le message sigaction(SIGKILL, &act, NULL);// SIGKILL; kill -9 <pid> affiche le message while(running) { printf("pid = %d\n", getpid()); printf("ppid = %d\n", getppid()); printf("nombre aleatoire = %d\n", rand() % 100); sleep(1); } printf("Apres la boucle...\n"); atexit(exit_message); return EXIT_SUCCESS; } /* - SIGKILL avec kill -9 <ppid> : le terminal est directement ferme - SIGKILL avec kill <ppid> : le programme continue l'execution Quand stop_handler ne modifie pas running: - ^C ==> le programme ne s'arrete pas - kill <pid> ==> le programme ne s'arrete pas - kill -9 <pid> ==> le programme s'arrete Message de fin : - ^C ==> le message s'affiche - kill <pid> ==> le message s'affiche - kill -9 <pid> ==> le message ne s'affiche pas */<file_sep>CC=g++ CFLAGS = -pthread -std=c++17 LDFLAGS = -Igoogletest/googletest/include -Lgtest/lib -lgtest tests: Expression.o TestExpression.o $(CC) $(CFLAGS) -o tests TestExpression.o Expression.o $(LDFLAGS) Expression.o: Expression.cpp $(CC) $(CFLAGS) -c Expression.cpp TestExpression.o: TestExpression.cpp Expression.hpp $(CC) $(CFLAGS) -c TestExpression.cpp $(LDFLAGS) clean: rm -rf *.o<file_sep>#include <gtest/gtest.h> #include "Nombre.h" #include <utility> #include <sstream> Nombre factorielle( unsigned int n ); TEST( TestNombre, TestNombreVide_Defaut ) { Nombre n; std::ostringstream os; os << n; EXPECT_EQ( os.str(), "0" ); } TEST( TestNombre, TestNombreNul ) { Nombre n{ 0 }; std::ostringstream os; os << n; EXPECT_EQ( os.str(), "0" ); } TEST( TestNombre, TestNombre12345678 ) { Nombre n{ 12345678 }; std::ostringstream os; os << n; EXPECT_EQ( os.str(), "12345678" ); } TEST( TestNombre, TestConstructionCopy ) { Nombre n{ 246854 }; Nombre n2 = Nombre(n); std::ostringstream os; os << n2; EXPECT_EQ( os.str(), "246854" ); } TEST( TestNombre, TestOpAffectCopy ) { Nombre n{ 13579 }; Nombre n2 = n; std::ostringstream os; os << n2; EXPECT_EQ( os.str(), "13579" ); } TEST( TestNombre, TestLectureGrandNombre ) { std::string big{ "123456789123456789123456789123456789" }; std::istringstream in{ big }; Nombre n; in >> n; std::ostringstream os; os << n; EXPECT_EQ( os.str(), big ); } TEST( TestNombre, Testaddition ) { unsigned int add1 = 15; unsigned int add2 = 16; Nombre n{ add1 }; n += add2; char str[10]; sprintf(str,"%d",add1+add2); std::ostringstream os; os << n; EXPECT_EQ( os.str(), str ); } TEST( TestNombre, Testaddition2Nombre ) { unsigned int add1 = 99; unsigned int add2 = 1; Nombre n{ add1 }; Nombre n2{ add2 }; n += n2; char str[10]; sprintf(str,"%d",add1+add2); std::ostringstream os; os << n; EXPECT_EQ( os.str(), str ); } TEST( TestNombre, Testmultiplication ) { unsigned int mul1 = 434556; unsigned int mul2 = 256; Nombre n{ mul1 }; n *= mul2; char str[10]; sprintf(str,"%d",mul1*mul2); std::ostringstream os; os << n; EXPECT_EQ( os.str(), str ); } TEST( TestNombre, TestFactorielle123 ) { std::ostringstream os; os << factorielle( 123 );; EXPECT_EQ( os.str(), "12146304367025329675766243241881295855454217088483382315328918161829235892362167668831156960612640202170735835221294047782591091570411651472186029519906261646730733907419814952960000000000000000000000000000" ); } int main( int argc, char * argv[] ) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); // unsigned int mul1 = 54; // unsigned int mul2 = 10; // Nombre n{ mul1 }; // Nombre n2{ 0 }; // std::cout << n2 << std::endl; // for(int k = 0; k<mul2; k++){ // n2 += n; // std::cout << n2 << std::endl; // } // Nombre n {0}; // std::cout << n << std::endl; // Nombre n2{ 54 }; // for(int i = 0 ; i < 20 ; i++){ // n+=n2; // std::cout << n << std::endl; // } // return 0; }<file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include <stdlib.h> //EXIT_SUCCESS #include <signal.h> //sigaction() #include <stdbool.h> //bool #include <sys/types.h> // wait() #include <sys/wait.h> // wait() bool running = 1; void stop_handler( int sig ) { printf("\n Signal %d reçu.\n", sig); int running = 0; return; } void exit_message() { printf("Exit Message ! \n"); } struct sigaction act; int main() { printf("Avant la boucle...\n"); act.sa_handler = stop_handler; act.sa_flags = 0; sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); sigaction(SIGKILL, &act, NULL); int pid=fork(); // creer deux process if (pid < 0) { printf("error in fork!"); exit(EXIT_FAILURE); } else if (pid == 0) { // printf("Je suis le fils. mon id est %d\n", getpid()); while(running) { printf("Je suis le fils. mon id est %d\n", getpid()); printf("Je suis le fils. pere id est %d\n", getppid()); printf("nombre aleatoire = %d\n", rand() % 100); sleep(2); } exit(0); } else { // printf("Je suis le pere. mon id est %d\n", getpid()); while(running) { printf("Je suis le pere. mon id est %d\n", getpid()); printf("Je suis le pere. pere id est %d\n", getppid()); printf("nombre aleatoire = %d\n", rand() % 100); sleep(2); } wait(NULL); exit(0); } // sigaction(SIGINT, &act, NULL); // SIGINT; ^C affiche le message // sigaction(SIGTERM, &act, NULL); // SIGTERM; kill <pid> affiche le message // sigaction(SIGKILL, &act, NULL);// SIGKILL; kill -9 <pid> affiche le message // while(running) // { // printf("pid = %d\n", getpid()); // printf("ppid = %d\n", getppid()); // printf("nombre aleatoire = %d\n", rand() % 100); // sleep(1); // } printf("Apres la boucle...\n"); atexit(exit_message); return EXIT_SUCCESS; } //********************************************************* /* 2.1 Même code fork() ==> On peut distinguer les codes de pères et de fils en suivant le numéro <pid>. Après kill le fils ==> le père continue l'execution, avec ps a on voit qu'avant il y a deux server_3 en execution, après il ne reste qu'un. Relance, kill le pere ==> le fils continue l'execution, mais son ppid devient 1. wait() ^C ==> les deux s'arretent kill <pid> ==> le pere commencent l'execution kill -9 <pid> ==> le pere commencent l'execution */ //********************************************************* /*Brouillon while(running) { printf("Je suis le pere. mon id est %d\n", getpid()); printf("Je suis le pere. pere id est %d\n", getppid()); printf("nombre aleatoire = %d\n", rand() % 100); sleep(1); } sigaction(SIGINT, &act, NULL); // SIGINT; ^C affiche le message sigaction(SIGTERM, &act, NULL); // SIGTERM; kill <pid> affiche le message sigaction(SIGKILL, &act, NULL);// SIGKILL; kill -9 <pid> affiche le message while(running) { printf("Je suis le fils. mon id est %d\n", getpid()); printf("Je suis le fils. pere id est %d\n", getppid()); printf("nombre aleatoire = %d\n", rand() % 100); sleep(1); } sigaction(SIGINT, &act, NULL); // SIGINT; ^C affiche le message sigaction(SIGTERM, &act, NULL); // SIGTERM; kill <pid> affiche le message sigaction(SIGKILL, &act, NULL);// SIGKILL; kill -9 <pid> affiche le message */ <file_sep>#include <sstream> #include "Expression.hpp" #include "gtest/gtest.h" // int compteur = 0; // int compteur2 = 0; TEST( TestDerivation, TestAffichageNombre ) { Nombre n( 2 ); std::ostringstream os; os << n; EXPECT_EQ( os.str(), "2" ); } TEST( TestDerivation, TestAffichageVariable ) { const Expression * e = new Variable( "x" ); std::ostringstream os; os << *e; EXPECT_EQ(os.str(), "x" ); delete e; } TEST( TestDerivation, TestDerivationNombre ) { const Expression * e = new Nombre( -2 ); const Expression * f = e->derive( "x" ); ASSERT_TRUE( nullptr != f ); std::ostringstream os; os << *f; EXPECT_EQ( os.str(), "0" ); delete e; delete f; } TEST( TestDerivation, TestDerivationVariable ) { const Expression * e = new Variable( "x" ); const Expression * f = e->derive( "x" ); ASSERT_TRUE( nullptr != f ); std::ostringstream os1; os1 << *f; EXPECT_EQ( os1.str(), "1" ); delete f; f = e->derive( "y" ); ASSERT_TRUE( nullptr != f ); std::ostringstream os2; os2 << *f; EXPECT_EQ( os2.str(), "0" ); delete e; delete f; } // TEST( TestDerivation, TestNombreInstance ) // { // compteur = 0; // compteur2 = 0; // int c = 0; // int c2 = 0; // const Expression * e = new Variable( "x" ); // c+=1; // c2+=1; // const Expression * f = e->derive( "x" ); // c+=1; // c2+=1; // EXPECT_EQ( compteur2, c2 ); // EXPECT_EQ( compteur, c ); // delete f; // c-=1; // EXPECT_EQ( compteur, c ); // f = e->derive( "y" ); // c+=1; // c2+=1; // EXPECT_EQ( compteur2, c2 ); // EXPECT_EQ( compteur, c ); // delete e; // c-=1; // delete f; // c-=1; // EXPECT_EQ( compteur, c ); // } TEST( TestDerivation, TestAffichageAddition ) { const Expression * e = new Addition( new Variable( "x" ), new Nombre( -2 )); std::ostringstream os; os << *e; EXPECT_EQ( os.str(), "(x + -2)" ); delete e; } TEST( TestDerivation, TestDerivationAddition ) { const Expression * e = new Addition( new Variable( "x" ), new Nombre( -10 )); //*e = (x + -10) const Expression * f = e->derive( "x" ); // *f = (x + -10)' = (1 + 0) ASSERT_TRUE( nullptr != f ); std::ostringstream os; os << *f; EXPECT_EQ( os.str(), "(1 + 0)" ); delete e; delete f; } TEST( TestDerivation, TestAffichageMultiplication ) { const Expression * e = new Multiplication( new Variable( "y" ), new Variable( "z" )); std::ostringstream os; os << *e; EXPECT_EQ( os.str(), "(y * z)" ); delete e; } TEST( TestDerivation, TestDerivationMultiplication ) { // This test expects (f * g)' = f' * g + f * g' const Expression * e = new Multiplication( new Variable( "x" ), new Multiplication( new Variable( "y" ), new Variable( "z" )) ); const Expression * f = e->derive( "x" ); ASSERT_TRUE( nullptr != f ); std::ostringstream os; os << *f; EXPECT_EQ( os.str(), "((1 * (y * z)) + (x * ((0 * z) + (y * 0))))" ); delete e; delete f; } // TEST( TestDerivation, TestSimplification ) // { // // This test expects (f * g)' = f' * g + f * g' // const Expression * e = new Addition( // new Nombre( 4 ), // new Multiplication( new Nombre( 2 ), new Variable( 3 )) // ); // // const Expression * f = e->derive( "x" ); // // ASSERT_TRUE( nullptr != f ); // std::ostringstream os; // os << *e; // EXPECT_EQ( os.str(), "((1 * (y * z)) + (x * ((0 * z) + (y * 0))))" ); // delete e; // delete f; // } int main( int argc, char * argv[] ) { // ::testing::InitGoogleTest( &argc, argv ); // return RUN_ALL_TESTS(); const Expression * e = new Addition( new Addition(new Nombre( 4 ), new Nombre( 3 )), new Multiplication( new Nombre( 2 ), new Nombre( 3 )) ); cout << *e << endl; e->simplifie(); cout << *e << endl; return 0; }<file_sep>// #include "class.h" #include <iostream> #include <sstream> #include <random> #include <thread> #include <mutex> #include <condition_variable> #include <unistd.h> #include <sys/wait.h> #include <boost/interprocess/shared_memory_object.hpp> #include<boost/interprocess/sync/scoped_lock.hpp> #include<boost/interprocess/sync/interprocess_mutex.hpp> #include<boost/interprocess/sync/interprocess_condition.hpp> #include <boost/interprocess/mapped_region.hpp> // #include <main> using namespace std; using namespace boost::interprocess; /* * Générateur de nombres aléatoires * Il n'est pas nécessaire de comprendre son fonctionnement * * Exemple d'utilisation pour une attente de durée aléatoire entre 0 et 50 ms * Random random( 50 ); * using milliseconds = std::chrono::duration< int, std::milli >; * std::this_thread::sleep_for( milliseconds( random() )); */ class Random { public: explicit Random( int max ) : dist_( 0, max ) {} int operator()() { return dist_( rd_ ); } private: std::random_device rd_; std::uniform_int_distribution< int > dist_; }; /* * FIFO d'echange de messages entre producteurs et consommateurs */ class MessageBox { public: MessageBox( ) // : box_size_( box_size ) // : box_( box_size_, -1 ) // , put_index_( 0 ) // , get_index_( 0 ) { for(int i=0; i< box_size_; i++){ box_[i] = -1; } put_index_ = 0; get_index_ = 0; } void put( int message ) { // TODO : ajouter les mecanismes de synchronisation unique_lock< mutex > lock( mutex_ ); while (box_[put_index_] != -1){ box_not_full_.wait( lock ); } box_[ put_index_ ] = message; put_index_ = ( put_index_ + 1 ) % box_size_; box_not_empty_.notify_one(); } int get() { // TODO : ajouter les mecanismes de synchronisation unique_lock< mutex > lock( mutex_ ); while( box_[get_index_]==-1){ box_not_empty_.wait( lock ); } int message = box_[get_index_]; // Pour détecter les erreurs box_[get_index_] = -1; get_index_ = ( get_index_ + 1 ) % box_size_; box_not_full_.notify_one(); return message; } private: // FIFO réalisée par un tableau géré en tampon circulaire via 2 indices (dépôt et retrait) static const unsigned box_size_ = 2; std::array<int, box_size_> box_; unsigned put_index_; unsigned get_index_; // TODO : ajouter les objets de synchronisation // unsigned int nb_messages_; condition_variable box_not_empty_; condition_variable box_not_full_; std::mutex mutex_; }; /* * Super-classe pour les producteurs et consommateurs */ class ProdOrCons { public: ProdOrCons( unsigned name, MessageBox & box, Random & random, unsigned nb_messages ) : name_( name ) , box_( box ) , random_( random ) , nb_messages_( nb_messages ) {} virtual ~ProdOrCons() {} virtual void operator()() = 0; // virtual affiche protected: // nom sous la forme d'un entier unsigned name_; // FIFO ou écrire/lire les messages MessageBox & box_; // générateur de nombres aléatoires Random & random_; // nombre de messages à produire ou lire const unsigned nb_messages_; }; /* * Producteur de messages */ class Producer : public ProdOrCons { public: using ProdOrCons::ProdOrCons; void operator()() override { // TODO : déposer dans box nb_messages nombres entiers positifs avec attente // aléatoire entre chaque. Afficher des messages pour suivre l'avancement. for (int i = 0; i < nb_messages_; i++){ //attente aléatoire // Random random(50); // using milliseconds = std::chrono::duration< int, std::milli >; // std::this_thread::sleep_for( milliseconds( random() )); // sleep(2); //put message int message = rand(); box_.put(message); printf("Producer %d send : %d\n", name_, message); // cout << "Producer " << name_ << " send : " << message << endl; } } }; /* * Consommateur de messages */ class Consumer : public ProdOrCons { public: using ProdOrCons::ProdOrCons; void operator()() override { // TODO : extraire de box nb_messages avec attente aléatoire entre chaque. // Afficher des messages pour suivre l'avancement. // Signaler comme erreur l'extraction d'un nombre négatif. for (int i = 0; i < nb_messages_; i++){ //attente aléatoire Random random(50); using milliseconds = std::chrono::duration< int, std::milli >; std::this_thread::sleep_for( milliseconds( random() )); // sleep(2); //get message int message = box_.get(); //print message if (message < 0){ printf("Consumer %d extract error\n", name_); // cout << "Consumer " << name_ << " extract error" << endl; } else{ printf("Consumer %d receive : %d\n", name_, message); // cout << "Consumer " << name_ << " receive : " << message << endl; } } } }; int main() { // shared_memory_object::remove("shared_memory"); //Create a shared memory object. shared_memory_object shm_obj( open_or_create, //open or create "shared_memory", //name read_write //read-write mode ); //Set size shm_obj.truncate(sizeof(MessageBox)); //Map the whole shared memory in this process mapped_region region (shm_obj, read_write); void * addr = region.get_address(); MessageBox * box = new ( addr ) MessageBox(); cout << "start" << endl; Random random( 50 ); const unsigned nb_messages = 20; int pid = fork(); if (pid < 0) { printf("error in fork!"); exit(EXIT_FAILURE); } else if (pid > 0) { Producer producer( 1, *box, random, nb_messages ); producer(); wait(NULL); exit(0); } else{ Consumer consumer( 1, *box, random, nb_messages ); consumer(); shared_memory_object::remove("shared_memory"); exit(0); } cout << "finish" << endl; return 0; }<file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include <stdlib.h> //EXIT_SUCCESS #include <signal.h> //sigaction() #include <stdbool.h> //bool #include <sys/types.h> // wait() #include <sys/wait.h> // wait() #include <string.h> //strlen() #include <fcntl.h> #include <limits.h> #include <sys/stat.h> //for mkfifo int main() { const char *fifo_name = "myfifo"; int pipe_fd = -1; int data_fd = -1; int res = 0; int open_mode = O_RDONLY; char buffer[PIPE_BUF + 1]; int bytes_read = 0; int bytes_write = 0; memset(buffer, '\0', sizeof(buffer)); printf("Process %d opening FIFO O_RDONLY\n", getpid()); pipe_fd = open(fifo_name, open_mode); data_fd = open("DataFormFIFO.txt", O_WRONLY | O_CREAT, 0644); printf("Process %d result %d\n", getpid(), pipe_fd); if (pipe_fd != -1) { do { // 读取FIFO中的数据,并把它保存在文件DataFormFIFO.txt文件中 res = read(pipe_fd, buffer, PIPE_BUF); bytes_write = write(data_fd, buffer, res); bytes_read += res; } while (res > 0); close(pipe_fd); close(data_fd); } else { exit(EXIT_FAILURE); } printf("Process %d finished, %d bytes read\n", getpid(), bytes_read); exit(EXIT_SUCCESS); }<file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include <stdlib.h> //EXIT_SUCCESS #include <signal.h> //sigaction() #include <stdbool.h> //bool #include <sys/types.h> // wait() #include <sys/wait.h> // wait() #include <string.h> //strlen() #include <fcntl.h> //for open #include <limits.h> #include <sys/stat.h> //for mkfifo #include <time.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> bool running = 1; void stop_handler( int sig ) { printf("\n Signal %d reçu.\n", sig); running = 0; return; } void exit_message() { printf("Exit Message ! \n"); } struct sigaction act; //TCP #define PORT 13 int main() { printf("Avant la boucle...\n"); act.sa_handler = stop_handler; act.sa_flags = 0; sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); sigaction(SIGKILL, &act, NULL); char str[10]; // TCP variable int SocketFD = 0; int bindv = 0; int listenv = 0; int acceptFD = 0; struct sockaddr_in LocalAddr = {0}; struct sockaddr_in RemoteAddr = {0}; //对方地址信息 socklen_t socklen = 0; // create socket SocketFD = socket(AF_INET, SOCK_STREAM, 0); if(SocketFD < 0) { printf("Create socket failed\n"); return 0; } LocalAddr.sin_family = AF_INET; LocalAddr.sin_port = htons(PORT); LocalAddr.sin_addr.s_addr=htonl(INADDR_ANY); //bind bindv = bind(SocketFD, (void *)&LocalAddr, sizeof(LocalAddr)); if(bindv < 0){ printf("Bind failed\n"); return EXIT_FAILURE; } //listen listenv = listen(SocketFD,5); if(listenv < 0) { printf("Listen failed\n"); return EXIT_FAILURE; } //accept acceptFD = accept(SocketFD, (void *)&RemoteAddr, &socklen); if(acceptFD < 0) { printf("Accept failed\n"); return EXIT_FAILURE; } printf("Accept success! Je suis server. mon id est %d\n", getpid()); while(running) { srand(time(NULL)); int a = rand()%100; sprintf(str,"%d",a); printf("Data envoyé : %s\n",str); char * msg = str; write(acceptFD, msg, strlen(msg)); sleep(2); } close(acceptFD); close(SocketFD); printf("Apres la boucle...\n"); atexit(exit_message); return EXIT_SUCCESS; } <file_sep>#include "Expression.hpp" #include <typeinfo> ostream& operator<<( ostream& out, Expression const & e ) { e.affiche(out); return out; } /* ** Constructeurs */ Nombre::Nombre(int n){ valeur = n; // cout << "constructeur Nombre" << endl; // compteur +=1; // compteur2 +=1; } Variable::Variable(string s){ nom = s; // cout << "constructeur Variable" << endl; // compteur +=1; // compteur2 +=1; } Addition::Addition(Expression * a1, Expression * a2){ somme[0] = a1; somme[1] = a2; // cout << "constructeur Addition" << endl; } Multiplication::Multiplication(Expression * a1, Expression * a2){ produit[0] = a1; produit[1] = a2; // cout << "constructeur Multiplication" << endl; } /* ** Destructeurs */ Nombre::~Nombre(){ // cout << "destructeur Nombre" << endl; // compteur -=1; } Variable::~Variable(){ // cout << "destructeur Variable" << endl; // compteur -=1; } Addition::~Addition(){ // cout << "destructeur Addition" << endl; } Multiplication::~Multiplication(){ // cout << "destructeur Multiplication" << endl; } /* ** Affichages */ ostream & Nombre::affiche(ostream & out) const { return out << valeur; } ostream & Variable::affiche(ostream & out) const{ return out << nom; } ostream & Addition::affiche(ostream & out) const{ return out << "(" << *somme[0] << " + " << *somme[1] << ")"; } ostream & Multiplication::affiche(ostream & out) const{ return out << "(" << *produit[0] << " * " << *produit[1] << ")"; } /* ** Derivations */ Nombre * Nombre::derive( string v ) const { return new Nombre(0); } Nombre * Variable::derive( string v ) const { if(nom == v){ return new Nombre(1); } else{ return new Nombre(0); } } Expression * Addition::derive(string v) const{ return new Addition(somme[0]->derive(v) , somme[1]->derive(v)); } Expression * Multiplication::derive(string v) const{ return new Addition(new Multiplication(produit[0]->derive(v), produit[1]), new Multiplication(produit[0], produit[1]->derive(v))); } /* ** Simplifications *** Les possibilités de simplification des expressions : **** Additions et Multiplications des Nombres: ((1 + 1) + (2 * 2)) = 6 **** Additions des Multiplications de meme variable: ((2 * x) + (3 * x)) = (5 * x) ; ((x * y) + (y * x)) = (2 * (x * y)) *** Principe : Appel récursif de la fonction simplifie(), au niveau d'addition et de multiplication, si les deux elements sont nombres, on effectue la simplification. Probleme : J'ai pas trouvé la façon pour l'identification du type nombre */ Nombre * Nombre::simplifie() const{ // cout << typeid(this).name() << endl; // cout << "Nombre::simplifie" << endl; return new Nombre(this->valeur); } Variable * Variable::simplifie() const{ return new Variable(this->nom); } Expression * Addition::simplifie() const{ // cout << typeid(this->somme[0]).name() << endl; if(typeid(this->somme[0]) == typeid(Nombre *) && typeid(this->somme[1]) == typeid(Nombre *)){ // cout << "Addition::simplifie - 2Nombre" << endl; return new Nombre(this->somme[0]->valeur + this->somme[1]->valeur); } else{ // cout << "Addition::simplifie" << endl; return new Addition(this->somme[0]->simplifie(), this->somme[1]->simplifie()); } } Expression * Multiplication::simplifie() const{ // cout << typeid(this->produit[0]).name() << endl; if(typeid(this->produit[0]) == typeid(Nombre *) && typeid(this->produit[1]) == typeid(Nombre *)){ // cout << "Multiplication::simplifie - 2Nombre" << endl; return new Nombre((this->produit[0]->valeur) * (this->produit[1]->valeur)); } else{ // cout << "Multiplication::simplifie" << endl; return new Multiplication(this->produit[0]->simplifie(), this->produit[1]->simplifie()); } }<file_sep>#include <utility> #include <sstream> #include <iostream> #include <string> using namespace std; class Nombre { public: // Constructeur par défaut Nombre(){ *premier_ = 0; } // Constructeur par défaut Nombre( unsigned long n ){ *premier_ = Chiffre(n); } // Constructeur de copie Nombre(const Nombre & n){ premier_ = n.premier_; } // Destructeur ~Nombre(){} void addFront(unsigned long chiffre); // Opérateur d'affectation Nombre & operator=( const Nombre & n ){ premier_ = new Chiffre(*n.premier_); return *this; } friend std::ostream & operator << ( std::ostream & out, const Nombre & n ); friend std::istream & operator >> ( std::istream & in, Nombre & n ); // private: struct Chiffre { unsigned int chiffre_; // entre 0 et 9 Chiffre * suivant_; // chiffre de poids supérieur ou nullptr std::ostream & affiche(std::ostream & out) const; Chiffre( unsigned long n ){ chiffre_ = static_cast< unsigned int >( n % 10 ); suivant_ = ( n > 9 ) ? new Chiffre(n/10) : nullptr ; } Chiffre( const Chiffre & c){ chiffre_ = c.chiffre_ ; suivant_ = c.suivant_ ? new Chiffre(*c.suivant_) : nullptr ; } }; Chiffre * premier_; }; std::ostream & operator << ( std::ostream & out, const Nombre & n ) { if( n.premier_ ) n.premier_ -> affiche(out); return out; } std::ostream & Nombre::Chiffre::affiche( std::ostream & out) const { if( suivant_ ) suivant_ -> affiche(out); return out << chiffre_; } void Nombre::addFront(unsigned long chiffre){ Chiffre * ch = new Chiffre(chiffre); ch->suivant_ = premier_; premier_ = ch; } std::istream & operator >> ( std::istream & in, Nombre & n ) { // in est le flux d'entrée delete n.premier_; n.premier_ = nullptr; while( in.good() ) { int c; c = in.get(); if( std::isdigit( c )) { unsigned long d; d = static_cast<unsigned long>( c - '0' ); // d contient le chiffre entre 0 et 9 qui vient d'être lu n.addFront(d); } else break; } return in; } int main(){ Nombre n(1); std::cin >> n; // std::string big{ "123456789123456789123456789123456789" }; // std::istringstream in{big} ; // in = big ; // Nombre n; // in >> n; return 0; }<file_sep>CC=g++ CFLAGS = -pthread -std=c++17 LDFLAGS = -Igoogletest/googletest/include -Lgtest/lib -lgtest tests: Nombre.o tests.o $(CC) $(CFLAGS) -o tests tests.o Nombre.o $(LDFLAGS) Nombre.o: Nombre.cpp $(CC) $(CFLAGS) -c Nombre.cpp tests.o: tests.cpp Nombre.h $(CC) $(CFLAGS) -c tests.cpp $(LDFLAGS) clean: rm -rf *.o<file_sep>#include "Nombre.h" // #include <istream> // #include <iostream> // #include <string> // #include <cctype> //Pour les fonctions std::ostream & operator << ( std::ostream & out, const Nombre & n ) { if( n.premier_ ) n.premier_ -> affiche(out); return out; } std::ostream & Nombre::Chiffre::affiche( std::ostream & out) const { if( suivant_ ) suivant_ -> affiche(out); return out << chiffre_; } void Nombre::pop(unsigned int d){ Chiffre ch = Chiffre{d}; ch.suivant_ = premier_; premier_ = new Chiffre(ch); } std::istream & operator >> ( std::istream & in, Nombre & n ) { // in est le flux d'entrée n.premier_ = nullptr; while( in.good() ) { int c{ in.get() }; if( std::isdigit( c )) { unsigned int d{ static_cast<unsigned int>( c - '0' )}; // d contient le chiffre entre 0 et 9 qui vient d'être lu n.pop(d); // Nombre::Chiffre chiffre = Nombre::Chiffre{d}; // chiffre.suivant_ = n.premier_; // n.premier_ = new Nombre::Chiffre(chiffre); } else break; } return in; } Nombre & operator +=( Nombre & n, unsigned int i){ n = n + i; return n; } Nombre & operator +=( Nombre & n, Nombre & n2){ n = n + n2; return n; } Nombre Nombre::operator+(unsigned int i){ Chiffre * curr = premier_; unsigned int val = curr->chiffre_; unsigned long sum = 0, carry = i; while (carry>0 && curr->suivant_){ sum = val + carry; curr->chiffre_ = sum % 10; curr = curr->suivant_; val = curr->chiffre_; carry = sum / 10; }; sum = val + carry; curr->chiffre_ = sum % 10; carry = sum / 10; if (carry>0) { curr->suivant_ = new Chiffre(carry); } return * this; } Nombre Nombre::operator+(Nombre & n){ // Nombre somme{ 0 }; Chiffre * curr1 = premier_; Chiffre * curr2 = n.premier_; unsigned int val1 = curr1->chiffre_; unsigned int val2 = curr2->chiffre_; unsigned long sum = 0, carry = 0; while (curr1->suivant_ && curr2->suivant_){ sum = val1 + val2 + carry; curr1->chiffre_ = sum % 10; curr1 = curr1->suivant_; curr2 = curr2->suivant_; val1 = curr1->chiffre_; val2 = curr2->chiffre_; carry = sum / 10; }; sum = val1 + val2 + carry; curr1->chiffre_ = sum % 10; carry = sum / 10; if (carry > 0 && curr1->suivant_){ curr1 = curr1->suivant_; val1 = curr1->chiffre_; while (curr1->suivant_){ sum = val1 + carry; curr1->chiffre_ = sum % 10; curr1 = curr1->suivant_; val1 = curr1->chiffre_; carry = sum / 10; } sum = val1 + carry; curr1->chiffre_ = sum % 10; carry = sum / 10; } if (curr2->suivant_){ curr2 = curr2->suivant_; val2 = curr2->chiffre_; while (curr2->suivant_) { sum = val2 + carry; curr1->suivant_ = new Chiffre(sum % 10); curr1 = curr1->suivant_; curr2 = curr2->suivant_; val2 = curr2->chiffre_; carry = sum / 10; } sum = val2 + carry; curr1->suivant_ = new Chiffre(sum % 10); carry = sum / 10; } if (carry>0) { curr1->suivant_ = new Chiffre(carry); } return * this; } Nombre & operator *=( Nombre & n, unsigned int i){ n = n * i; return n; } Nombre Nombre::operator*(unsigned int i){ Nombre n{0}; for(int k = 0; k<i; k++){ n = n + *this; } return n; } /* Pas d'idée de construire la multiplication sans l'addition de deux nombre, donc j'ai construit l'addition des nombre pour faire la multiplication. */ // Retourne un objet Nombre représentant la factorielle de l'argument n Nombre factorielle( unsigned int n ){ Nombre Nb{n}; for(int i = n-1; i > 0; i--){ Nb *= i; // printf("running boucle %d\n", i); } return Nb; } // int main() // { // return 0; // } // Nombre newNb = Nombre(d); // newNb.premier_->suivant_ = n.premier_; // n.premier_ = newNb.premier_; // unsigned int val1 = curr->chiffre_; // unsigned long sum = 0, carry = i; // sum = val1+ carry; // ch->chiffre_ = sum % 10; // curr = curr->suivant_; // carry = sum / 10; // while (carry>0 && curr->suivant_) // { // val1 = curr->chiffre_; // sum = val1 + carry; // ch->suivant_ = new Chiffre(sum % 10); // ch = ch->suivant_; // curr = curr->suivant_; // carry = sum / 10; // } <file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include <stdlib.h> //EXIT_SUCCESS #include <signal.h> //sigaction() #include <stdbool.h> //bool #include <sys/types.h> // wait() #include <sys/wait.h> // wait() #include <string.h> //strlen() bool running = 1; void stop_handler( int sig ) { printf("\n Signal %d reçu.\n", sig); running = 0; return; } void exit_message() { printf("Exit Message ! \n"); } struct sigaction act; int main() { printf("Avant la boucle...\n"); act.sa_handler = stop_handler; act.sa_flags = 0; sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); sigaction(SIGKILL, &act, NULL); // create pip int fd[2]; pipe(fd); int len; char buf[1024]; if(pipe(fd)<0) { perror("pipe"); exit(0); } int pid=fork(); // creer deux process if (pid < 0) { printf("error in fork!"); exit(EXIT_FAILURE); } else if (pid > 0) { int status = 0; close(fd[0]); while(running) { printf("Je suis le pere. mon id est %d\n", getpid()); printf("nombre aleatoire = %d\n", rand() % 100); char *msg ="let's chat with pipe !\n"; write(fd[1], msg, strlen(msg)); sleep(2); } close(fd[1]); wait(&status); wait(NULL); printf("Apres la boucle...\n"); atexit(exit_message); } else { close(fd[1]); while(running) { printf("nombre aleatoire = %d\n", rand() % 100); printf("Je suis le fils. mon id est %d\n", getpid()); int len = read(fd[0], buf, sizeof(buf)); // write(STDOUT_FILENO, buf, len) if (len == 0) { exit(0); } printf("%s\n", buf); sleep(2); } close(fd[0]); exit(0); } printf("Apres la boucle...\n"); atexit(exit_message); return EXIT_SUCCESS; } //********************************************************* /* Pour faire en sorte que le père affiche aussi ses messages quand on arrête le fils en premier, j'essaie de construire le signal reçu par le père quand le fils exit anormalement (par ex. kill) avec la fonction WIFEXITED(status) qui retourne 0 si le fils exit anormalement. Mais ça n'a pas fonctionné. À étudier après. */ //********************************************************* /*Brouillon while(running) { printf("Je suis le pere. mon id est %d\n", getpid()); printf("Je suis le pere. pere id est %d\n", getppid()); printf("nombre aleatoire = %d\n", rand() % 100); sleep(2); } printf("Je suis le fils. pere id est %d\n", getppid()); */<file_sep>// // test.cpp // 3IF1020 // // Created by 葛钊琦 on 2020/9/28. // #include "test.hpp" #include <iostream> // #include <unistd.h> using namespace std ; //常量 #define d 12 //宏常量 const int c = 15; //const修饰的变量在main里面定义才有效 /* 数据类型: 整型: int 变量名 = 变量; short (2) / int (4) / long (8) / longlong (16) sizeof() 查看占用内存空间 浮点型: float (4) / double (8) 字符型: char 变量名 = 'a'; 一个字符,单引号。 `(数据类型)变量`:强制转换类型 转义字符: 以\开始,\n 换行,\t 水平制表符,\\ 反斜杠 字符串: char 变量名[] = "字符串值"; //c风格 or #include <string> string 变量名 = "变量值"; //c++风格 布尔类型: bool 名 = true/false; 0 - False,1 - True 数据的的输入: cin >> variable; 条件语句: if(conditions){execution} if(condition){execution}elif(condition){execution}else{execution} 三目运算符: 表达式1 ? 表达式2 : 表达式3 若1真则执行2 否则3 switch switch(expression){case...defult...} 循环: while(condition){} ---先判断再执行 do{}while() ---先执行再判断 for(起始表达式;条件表达式;末尾循环体){} 或 || ; 与 && 跳转语句: break; ---退出循环 continue; ---跳过当前循环,执行下一次 goto FLAG; ---跳转到标记位置 数组: 一维数组: 数据类型 数组名[数组长度]; || 数据类型 数组名[] = {值1, 值2, ...} 二维数组: 数据类型 数组名[行数][列数]; || 数据类型 数组名[行数][列数] = {{值1, 值2}, {值3, 值4}}; */ int main() { short a = 9; short c = 97; // int c = 2; std::cout << "Hello world!~\n" ; // std::cout << "a=\n"; printf("a = %d \n", a); cout << "常量" << d << endl; cout << "short内存空间 = " << sizeof(short) << endl; // cout << "请输入整数" << endl; // cin >> c; cout << c << endl; int arr[5]={1, 2, 3 , 4, 5}; cout << (long)arr << endl; cout << (long)&arr[0] << endl; // pause(); return 0; } <file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include <stdlib.h> //EXIT_SUCCESS #include <string.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <fcntl.h> #define PORT 20 //目标地址端口号 #define ADDR "10.57.150.3" //目标地址IP int main() { int iSocketFD = 0; //socket句柄 unsigned int iRemoteAddr = 0; struct sockaddr_in stRemoteAddr = {0}; //对端,即目标地址信息 socklen_t socklen = 0; char buf[4096] = {0}; //存储接收到的数据 iSocketFD = socket(AF_INET, SOCK_STREAM, 0); //建立socket if(0 > iSocketFD) { printf("创建socket失败!\n"); return 0; } stRemoteAddr.sin_family = AF_INET; stRemoteAddr.sin_port = htons(PORT); inet_pton(AF_INET, ADDR, &iRemoteAddr); stRemoteAddr.sin_addr.s_addr=iRemoteAddr; //连接方法: 传入句柄,目标地址,和大小 if(0 > connect(iSocketFD, (void *)&stRemoteAddr, sizeof(stRemoteAddr))) { printf("连接失败!\n"); // printf("connect failed:%d",errno);//失败时也可打印errno }else{ printf("连接成功!\n"); recv(iSocketFD, buf, sizeof(buf), 0); //将接收数据打入buf,参数分别是句柄,储存处,最大长度,其他信息(设为0即可)。 printf("Received:%s\n", buf); } close(iSocketFD);//关闭socket return 0; }<file_sep>// #include "class.h" #include <iostream> #include <sstream> #include <random> #include <thread> #include <mutex> #include <condition_variable> #include <unistd.h> using namespace std; /* * Générateur de nombres aléatoires * Il n'est pas nécessaire de comprendre son fonctionnement * * Exemple d'utilisation pour une attente de durée aléatoire entre 0 et 50 ms * Random random( 50 ); * using milliseconds = std::chrono::duration< int, std::milli >; * std::this_thread::sleep_for( milliseconds( random() )); */ class Random { public: explicit Random( int max ) : dist_( 0, max ) {} int operator()() { return dist_( rd_ ); } private: std::random_device rd_; std::uniform_int_distribution< int > dist_; }; /* * Classe permettant d'assurer la sérialisation des affichages * Version simplifiée de la classe de même nom de C++20 * * Exemple d'utilisation * { osyncstream( std::cout ) << "hellow world"; } */ class osyncstream { public: osyncstream( std::ostream & out ) : out_( out ) {} // L'affichage se fait uniquement à la destruction de l'objet ~osyncstream() { std::lock_guard< std::mutex > l( protect_out_ ); out_ << saved_.str() << std::endl; } // Mémorisation de ce qu'il faut afficher osyncstream & operator<<( const std::string & what ) { saved_ << what; return *this; } osyncstream & operator<<( const char * what ) { saved_ << what; return *this; } osyncstream & operator<<( int what ) { saved_ << what; return *this; } private: static std::mutex protect_out_; std::ostream & out_; std::ostringstream saved_; }; std::mutex osyncstream::protect_out_; /* * FIFO d'echange de messages entre producteurs et consommateurs */ class MessageBox { public: MessageBox( unsigned box_size ) : box_size_( box_size ) , box_( box_size_, -1 ) , put_index_( 0 ) , get_index_( 0 ) {} void put( int message ) { // TODO : ajouter les mecanismes de synchronisation unique_lock< mutex > lock( mutex_ ); // while( nb_messages_ == box_size_) { // box_not_full_.wait( lock ); // } while (box_[put_index_] != -1){ box_not_full_.wait( lock ); } box_[ put_index_ ] = message; put_index_ = ( put_index_ + 1 ) % box_size_; // ++nb_messages_; box_not_empty_.notify_one(); } int get() { // TODO : ajouter les mecanismes de synchronisation unique_lock< mutex > lock( mutex_ ); while( box_[get_index_]==-1){ box_not_empty_.wait( lock ); } int message = box_[get_index_]; // Pour détecter les erreurs box_[get_index_] = -1; get_index_ = ( get_index_ + 1 ) % box_size_; box_not_full_.notify_one(); return message; } private: // FIFO réalisée par un tableau géré en tampon circulaire via 2 indices (dépôt et retrait) const unsigned box_size_; std::vector< int > box_; unsigned put_index_; unsigned get_index_; // TODO : ajouter les objets de synchronisation // unsigned int nb_messages_; condition_variable box_not_empty_; condition_variable box_not_full_; std::mutex mutex_; }; /* * Super-classe pour les producteurs et consommateurs */ class ProdOrCons { public: ProdOrCons( unsigned name, MessageBox & box, Random & random, unsigned nb_messages ) : name_( name ) , box_( box ) , random_( random ) , nb_messages_( nb_messages ) {} virtual ~ProdOrCons() {} virtual void operator()() = 0; // virtual affiche protected: // nom sous la forme d'un entier unsigned name_; // FIFO ou écrire/lire les messages MessageBox & box_; // générateur de nombres aléatoires Random & random_; // nombre de messages à produire ou lire const unsigned nb_messages_; }; /* * Producteur de messages */ class Producer : public ProdOrCons { public: using ProdOrCons::ProdOrCons; void operator()() override { // TODO : déposer dans box nb_messages nombres entiers positifs avec attente // aléatoire entre chaque. Afficher des messages pour suivre l'avancement. for (int i = 0; i < nb_messages_; i++){ //attente aléatoire Random random(50); using milliseconds = std::chrono::duration< int, std::milli >; std::this_thread::sleep_for( milliseconds( random() )); // sleep(2); //put message int message = rand(); box_.put(message); printf("Producer %d send : %d\n", name_, message); // cout << "Producer " << name_ << " send : " << message << endl; } } }; /* * Consommateur de messages */ class Consumer : public ProdOrCons { public: using ProdOrCons::ProdOrCons; void operator()() override { // TODO : extraire de box nb_messages avec attente aléatoire entre chaque. // Afficher des messages pour suivre l'avancement. // Signaler comme erreur l'extraction d'un nombre négatif. for (int i = 0; i < nb_messages_; i++){ //attente aléatoire Random random(50); using milliseconds = std::chrono::duration< int, std::milli >; std::this_thread::sleep_for( milliseconds( random() )); // sleep(2); //get message int message = box_.get(); //print message if (message < 0){ printf("Consumer %d extract error\n", name_); // cout << "Consumer " << name_ << " extract error" << endl; } else{ printf("Consumer %d receive : %d\n", name_, message); // cout << "Consumer " << name_ << " receive : " << message << endl; } } } }; /* * Test avec 1 producteur et 1 consommateur */ // int main() { // const unsigned box_size = 2; // const unsigned nb_messages = 20; // Random random( 50 ); // MessageBox box( box_size ); // Producer producer( 1, box, random, nb_messages ); // Consumer consumer( 1, box, random, nb_messages ); // std::cout << "start" << std::endl; // std::thread producer_thread( producer ); // std::thread consumer_thread( consumer ); // producer_thread.join(); // consumer_thread.join(); // std::cout << "finish" << std::endl; // return 0; // } /* * Test avec plusieurs producteurs et consommateurs */ int main() { const unsigned box_size = 2; const unsigned nb_messages = 10; const unsigned nb_producers = 4; const unsigned nb_consumers = 2; static_assert( nb_producers * nb_messages % nb_consumers == 0, "incorrect values" ); Random random( 50 ); MessageBox box( box_size ); std::cout << "start" << std::endl; std::vector< std::thread > group; for( unsigned i = 0; i < nb_producers; ++i ) { group.push_back( std::thread( Producer( i + 1, box, random, nb_messages ))); } unsigned nb = nb_producers * nb_messages / nb_consumers; for( unsigned i = 0; i < nb_consumers; ++i ) { group.push_back( std::thread( Consumer( i + 1, box, random, nb ))); } for( auto & th : group ) { th.join(); } std::cout << "finish" << std::endl; return 0; }<file_sep>#include <iostream> #include <string> #include <cctype> //Pour les class class Nombre { public: // Constructeur par défaut Nombre(){ premier_ = new Chiffre(0); } // Constructeur par défaut Nombre( unsigned long n ){ premier_ = new Chiffre(n); } // Constructeur de copie Nombre( const Nombre & n ) : premier_{ new Chiffre( *n.premier_ )} {} // Destructeur ~Nombre() { delete premier_; } void pop(unsigned int d); // Opérateur d'affectation Nombre & operator=( const Nombre & n ){ premier_ = new Chiffre(*n.premier_); return *this; } friend std::ostream & operator << ( std::ostream & out, const Nombre & n ); friend std::istream & operator >> ( std::istream & in, Nombre & n ); friend Nombre & operator +=( Nombre & n, unsigned int i); friend Nombre & operator +=( Nombre & n, Nombre & n2); friend Nombre & operator *=( Nombre & n, unsigned int i); Nombre operator+(unsigned int i); Nombre operator+(Nombre & n); Nombre operator*(unsigned int i); friend Nombre factorielle( unsigned int n ); private: struct Chiffre { unsigned int chiffre_; // entre 0 et 9 Chiffre * suivant_; // chiffre de poids supérieur ou nullptr std::ostream & affiche(std::ostream & out) const; Chiffre( unsigned long n ){ chiffre_ = static_cast< unsigned int >( n % 10 ); suivant_ = ( n > 9 ) ? new Chiffre(n/10) : nullptr ; } Chiffre( const Chiffre & c){ chiffre_ = c.chiffre_ ; suivant_ = c.suivant_ ? new Chiffre(*c.suivant_) : nullptr ; } Chiffre operator+(unsigned int i); }; Chiffre * premier_; }; /* Chiffre( unsigned long n ) : chiffre_{static_cast< unsigned int >( n% 10)} , suivant_{( n > 9 ) ? new Chiffre(n/10) : nullptr} {} */ <file_sep>// // main.cpp // Exercise1.1 // // Created by zhaoqi_ge on 2020/9/28. // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //Head #include <iostream> using namespace std ; #include <vector> // for vector<> #include <cstdlib> //for rand() #include <functional> //for function #include <forward_list> //for forward_list #include <limits> // for numeric_limits #include <algorithm> //for min and max //typedef bool (*func) (int,int); //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //Functions //1. Tris //1.1. Tri par ordre croissant void print_tab(vector<int> V) //Afficher le tableau { cout << "[ "; for(int n : V) { cout << n << " "; } cout << "]" << endl; return; } void random_tab(vector<int> &V) { srand((unsigned)time(NULL)); for(int i = 0 ; i < V.size() ; i++) { V[i] = (int)rand()%(100); } return; } void sort_tab_1(vector<int> &V) { int a = (int)V.size(); for(int i = 0; i < a - 1; i++) { for(int j = 0; j < a - 1 - i; j++) { int temp = 0; if(V[j]>V[j+1]){ temp = V[j]; V[j] = V[j+1]; V[j+1] = temp; } } } return; } void test_1() { std::vector<int> tab(10); random_tab(tab); cout << "before sorting: "; print_tab(tab); sort_tab_1(tab); cout << "after sorting: "; print_tab(tab); return; } //1.2. Tri selon un autre critère bool lessfc(int a, int b) { bool x = 0; if(a<b){ x = 1; } return x; } bool greaterfc(int a, int b) { bool x = 0; if(a>b){ x = 1; } return x; } void sort_tab_2(vector<int> &V, std::function<bool(int,int)> pfunc) { int a = (int)V.size(); for(int i = 0; i < a - 1; i++) { for(int j = 0; j < a - 1 - i; j++) { int temp = 0; if(pfunc(V[j],V[j+1])){ temp = V[j]; V[j] = V[j+1]; V[j+1] = temp; } } } } void test_2() { std::vector<int> tab(10); random_tab(tab); std::vector<int> tab2 = tab; cout << "before sorting: "; print_tab(tab); sort_tab_2(tab, [](int a, int b){return a < b;}); sort_tab_2(tab2, [](int a, int b){return a > b;}); cout << "after sorting less: "; print_tab(tab); cout << "after sorting greater: "; print_tab(tab2); } //2. Listes //2.1. Création, affichage std::forward_list<int> random_list(unsigned int a) { std::forward_list< int > L; srand((unsigned)time(NULL)); for(int i=0; i<a; i++) { L.push_front((int)rand()%(100)); } return L; } void print_list(std::forward_list<int> L) { cout << "[ "; for(int l : L) { cout << l << " "; } cout << "]" << endl; return; } //2.2. Application std::forward_list<int> map(std::forward_list<int> L, std::function<int(int)> pfunc) { std::forward_list<int> Lfi; std::forward_list<int> Lf; // Lf.push_front(1); // auto prec = Lf.before_begin(); // auto curr = Lf.begin(); // Lf.pop_front(); // for(int l : L) { // Lfi.push_front(l); // } for(int m : L) { Lf.push_front(pfunc(m)); } return Lf; } //2.3. Filtrage std::forward_list<int> filter(std::forward_list<int> L, std::function<bool(int)> pfunc) { std::forward_list<int> Lp; for(int l : L) { if(pfunc(l)){ Lp.push_front(l); } } return Lp; } void test_3() { //befor mapping std::forward_list<int> L = random_list(10); cout << "before mapping: "; print_list(L); srand((unsigned)time(NULL)); int coef = (int)rand()%(5)+1; cout << "Multiply coeff: " << coef << endl; //after mapping std::forward_list<int> Lf; Lf = map(L, [coef](int a){return a*coef;}); cout << "after mapping: "; print_list(Lf); //after filtering std::forward_list<int> Lfp; Lfp = filter(Lf, [](int a){return a%2==0;}); cout << "after filtering: "; print_list(Lfp); } //2.4. Réduction int reduce(std::forward_list<int> L, int a, std::function<int(int,int)> pfunc) { int curr = a; for(int l : L) { curr = pfunc(curr,l); } return curr; } void test_4() { //befor reducing std::forward_list<int> L = random_list(10); cout << "before reducing: "; print_list(L); //reduce - min int min; min = reduce(L,std::numeric_limits<int>::max(),[](int a, int b){return std::min(a,b);}); cout << "reduce on min: " << min << endl; //reduce - max int max; max = reduce(L,std::numeric_limits<int>::min(),[](int a, int b){return std::max(a,b);}); cout << "reduce on max: " << max << endl;; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //Main int main() { test_4(); return 0; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //Commentaires /* Q: Que constatez-vous en comparant l'ordre des éléments de la liste initiale et celui de la liste résultat ? Pouvez-vous l'expliquer (sous forme de commentaire dans votre fichier source) ? Ne pas essayer d'inverser le résultat, ce point sera repris dans la partie bonus. A: Le résultat est normalement inversé, c'est-à-dire que le dernier élément sort de fonction map est le multiple de celui de le premier élément dans la list initiale. C'est en fait du à la construction de la list chaînée, on parcourt la chaîne avec un pointeur. On connaît que le début de la chaîne mais pas la fin, donc on ne peut faire que push_front mais pas after. Quand je construiais mon code, j'avais pris en compte de ce point et ai inversé la liste une fois plus. Le résultat de mon code est donc dans l'ordre synchronisé. */ //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //Brouillons //std::vector<int> tab = {7, 5, 16, 8}; //cout << "tableau content: " ; //print_tab(tab); //cout << endl; // //random_tab(tab); //print_tab(tab); //std::vector<int> tab(10); // tableau de 10 entiers // //std::vector<int> v = {7, 5, 16, 8}; //tab.push_back(25); //tab.push_back(13); //for(int n : tab) { // cout << n << " "; //} //cout << endl; //int premier = tab[0]; // Accès au premier élément //cout << "premier variable dans le tableau = " << premier << endl; //tab[tab.size() - 1] = 5; // Modification du dernier élément <file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include <stdlib.h> //EXIT_SUCCESS #include <signal.h> //sigaction() #include <stdbool.h> //bool #include <sys/types.h> // wait() #include <sys/wait.h> // wait() #include <string.h> //strlen() #include <fcntl.h> //for open #include <limits.h> #include <sys/stat.h> //for mkfifo #include <time.h> bool running = 1; void stop_handler( int sig ) { printf("\n Signal %d reçu.\n", sig); running = 0; return; } void exit_message() { printf("Exit Message ! \n"); } struct sigaction act; int main() { printf("Avant la boucle...\n"); act.sa_handler = stop_handler; act.sa_flags = 0; sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); sigaction(SIGKILL, &act, NULL); // create FIFO const char * fifo_name = "FIFO_5"; int pipe_fd = -1; int res = 0; char str[10]; // char buffer[10]; if (access(fifo_name, F_OK) == -1) { res = mkfifo(fifo_name, 0777); if (res != 0) { fprintf(stderr, "Could not create fifo %s\n", fifo_name); exit(EXIT_FAILURE); } } pipe_fd = open(fifo_name, O_WRONLY); printf("Je suis server. mon id est %d\n", getpid()); while(running) { srand(time(NULL)); int a = rand()%100; sprintf(str,"%d",a); printf("Data envoyé : %s\n",str); char * msg = str; write(pipe_fd, msg, strlen(msg)); sleep(2); } close(pipe_fd); printf("Apres la boucle...\n"); atexit(exit_message); return EXIT_SUCCESS; } <file_sep>#include <iostream> #include <string> using namespace std; // int compteur = 0; // int compteur2 = 0; class Expression { public: Expression(){ // cout << "constructeur Expression" << endl; } virtual ~Expression(){ // cout << "destructeur Expression" << endl; } friend ostream& operator<<( ostream& out, Expression const & e ); virtual ostream & affiche(ostream & out) const = 0; virtual Expression * derive(string v) const = 0; virtual Expression * simplifie() const = 0; // virtual auto getvalue() const = 0; }; class Nombre : public Expression { public: Nombre(int n); ~Nombre(); ostream & affiche(ostream & out) const; Nombre * derive( string v ) const; Nombre * simplifie() const; private: int valeur; }; class Variable : public Expression { public: Variable(string s); ~Variable(); ostream & affiche(ostream & out) const; Nombre * derive( string v ) const; Variable * simplifie() const; private: string nom; }; class Operation : public Expression { public: Operation(){ // cout << "constructeur Operation" << endl; } virtual ~Operation(){ // cout << "destructeur Operation" << endl; } }; class Addition : public Operation { public: Addition(Expression * a1, Expression * a2); ~Addition(); ostream & affiche(ostream & out) const; Expression * derive(string v) const; Expression * simplifie() const; private: Expression * somme[2]; }; class Multiplication : public Operation { public: Multiplication(Expression * a1, Expression * a2); ~Multiplication(); ostream & affiche(ostream & out) const; Expression * derive(string v) const; Expression * simplifie() const; private: Expression * produit[2]; }; <file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include <stdlib.h> //EXIT_SUCCESS #include <signal.h> //sigaction() #include <stdbool.h> //bool #include <sys/types.h> // wait() #include <sys/wait.h> // wait() #include <string.h> //strlen() #include <fcntl.h> #include <limits.h> #include <sys/stat.h> //for mkfifo #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> bool running = 1; void stop_handler( int sig ) { printf("\n Signal %d reçu.\n", sig); running = 0; return; } void exit_message() { printf("Exit Message ! \n"); } struct sigaction act; //TCP #define PORT 13 int main() { printf("Avant la boucle...\n"); act.sa_handler = stop_handler; act.sa_flags = 0; sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); sigaction(SIGKILL, &act, NULL); //TCP settings int SocketFD = 0; unsigned int remoteaddr = 0; int connectv = 0; struct sockaddr_in RemoteAddr = {0}; socklen_t socklen = 0; char buffer[10]; //create socket SocketFD = socket(AF_INET, SOCK_STREAM, 0); if(SocketFD < 0) { printf("Create socket failed\n"); return 0; } RemoteAddr.sin_family = AF_INET; RemoteAddr.sin_port = htons(PORT); inet_pton(AF_INET, "10.57.150.3", &remoteaddr); RemoteAddr.sin_addr.s_addr=remoteaddr; //connect connectv = connect(SocketFD, (void *)&RemoteAddr, sizeof(RemoteAddr)); if(connectv < 0){ printf("Connection failed\n"); return EXIT_FAILURE; } printf("Connection success! Je suis client. mon id est %d\n", getpid()); while(running) { memset(buffer, '\0', sizeof(buffer)); // printf("nombre aleatoire = %d\n", rand() % 100); int res = read(SocketFD, buffer, sizeof(buffer)); if(res ==0){ close(SocketFD); atexit(exit_message); exit(EXIT_FAILURE); } printf("Data reçu : %s\n", buffer); sleep(2); } close(SocketFD); printf("Apres la boucle...\n"); atexit(exit_message); exit(EXIT_SUCCESS); } <file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include <stdlib.h> //EXIT_SUCCESS #include <signal.h> //sigaction() #include <stdbool.h> //bool #include <sys/types.h> // wait() #include <sys/wait.h> // wait() #include <string.h> //strlen() #include <fcntl.h> #include <limits.h> #include <sys/stat.h> //for mkfifo bool running = 1; void stop_handler( int sig ) { printf("\n Signal %d reçu.\n", sig); running = 0; return; } void exit_message() { printf("Exit Message ! \n"); } struct sigaction act; int main() { printf("Avant la boucle...\n"); act.sa_handler = stop_handler; act.sa_flags = 0; sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); sigaction(SIGKILL, &act, NULL); //FIFO setting const char * fifo_name = "FIFO_5"; int pipe_fd = -1; int res = 0; char buffer[10]; pipe_fd = open(fifo_name, O_RDONLY); printf("Je suis client. mon id est %d\n", getpid()); while(running) { memset(buffer, '\0', sizeof(buffer)); // printf("nombre aleatoire = %d\n", rand() % 100); int res = read(pipe_fd, buffer, sizeof(buffer)); if(res ==0){ close(pipe_fd); atexit(exit_message); exit(EXIT_FAILURE); } printf("Data reçu : %s\n", buffer); sleep(2); } close(pipe_fd); printf("Apres la boucle...\n"); atexit(exit_message); exit(EXIT_SUCCESS); } <file_sep>#include <stdio.h> #include <unistd.h> //sleep() #include<stdlib.h> //EXIT_SUCCESS int main() { printf("Avant la boucle\n"); while(1) { printf("pid = %d\n", getpid()); printf("ppid = %d\n", getppid()); printf("nombre aleatoire = %d\n", rand() % 100); sleep(1); } printf("Apres la boucle\n"); return EXIT_SUCCESS; }
6383180d3e1c795be211657ce4e83d86827adeae
[ "C", "Makefile", "C++" ]
23
C
lucie124/ProgrammationCPP
3bc20dd86c22c8f6468b30ca830e231f960ee556
3b5ef4df8b00536be0e3aa49eedd31e2019e8b2a
refs/heads/master
<file_sep>package main import ( "flag" "fmt" "io" "log" "os" "strconv" "strings" "github.com/cafxx/kafkabalancer/logbuf" "github.com/pkg/profile" ) type BrokerID int type PartitionID int type TopicName string type PartitionList struct { Version int `json:"version"` Partitions []Partition `json:"partitions"` } type Partition struct { Topic TopicName `json:"topic"` Partition PartitionID `json:"partition"` Replicas []BrokerID `json:"replicas"` // extensions Weight float64 `json:"weight,omitempty"` // default: 1.0 NumReplicas int `json:"num_replicas,omitempty"` // default: len(replicas) Brokers []BrokerID `json:"brokers,omitempty"` // default: (auto) NumConsumers int `json:"num_consumers,omitempty"` // default: 1 } func main() { os.Exit(run(os.Stdin, os.Stdout, os.Stderr, os.Args)) } func run(i io.Reader, o io.Writer, e io.Writer, args []string) int { be := logbuf.NewDefaultBufferingWriter(e) defer be.Close() log.SetOutput(be) f := flag.NewFlagSet("kafkabalancer", flag.ContinueOnError) f.SetOutput(be) jsonInput := f.Bool("input-json", false, "Parse the input as JSON") input := f.String("input", "", "Name of the file to read (if no file is specified read from stdin, can not be used with -from-zk)") fromZK := f.String("from-zk", "", "Zookeeper connection string (can not be used with -input)") maxReassign := f.Int("max-reassign", 1, "Maximum number of reassignments to generate") fullOutput := f.Bool("full-output", false, "Output the full partition list: by default only the changes are printed") pprof := f.Bool("pprof", false, "Enable CPU profiling") allowLeader := f.Bool("allow-leader", DefaultRebalanceConfig().AllowLeaderRebalancing, "Consider the partition leader eligible for rebalancing") minReplicas := f.Int("min-replicas", DefaultRebalanceConfig().MinReplicasForRebalancing, "Minimum number of replicas for a partition to be eligible for rebalancing") minUnbalance := f.Float64("min-unbalance", DefaultRebalanceConfig().MinUnbalance, "Minimum unbalance value required to perform rebalancing") brokerIDs := f.String("broker-ids", "auto", "Comma-separated list of broker IDs") help := f.Bool("help", false, "Display usage") f.Usage = func() { fmt.Fprintf(be, "Usage of %s:\n", args[0]) f.PrintDefaults() } f.Parse(args[1:]) if *pprof { defer profile.Start(profile.CPUProfile, profile.ProfilePath(".")).Stop() } if *help { f.Usage() return 0 } var brokers []BrokerID if *brokerIDs != "auto" { for _, broker := range strings.Split(*brokerIDs, ",") { b, cerr := strconv.Atoi(broker) if cerr != nil { log.Printf("failed parsing broker list \"%s\": %s", *brokerIDs, cerr) f.Usage() return 3 } brokers = append(brokers, BrokerID(b)) } } if *maxReassign < 0 { log.Printf("invalid number of max reassignments \"%d\"", *maxReassign) f.Usage() return 3 } if *input != "" && *fromZK != "" { log.Print("can't specify both -input and -from-zk") f.Usage() return 3 } var err error in := i if *input != "" { in, err = os.Open(*input) if err != nil { log.Printf("failed opening file %s: %s", *input, err) return 1 } defer in.(io.Closer).Close() } out := o var pl *PartitionList if *fromZK != "" { pl, err = GetPartitionListFromZookeeper(*fromZK) } else { pl, err = GetPartitionListFromReader(in, *jsonInput) } if err != nil { log.Printf("failed getting partition list: %s", err) return 2 } cfg := RebalanceConfig{ AllowLeaderRebalancing: *allowLeader, MinReplicasForRebalancing: *minReplicas, MinUnbalance: *minUnbalance, Brokers: brokers, } log.Printf("rebalance config: %+v", cfg) opl := emptypl() for i := 0; i < *maxReassign; i++ { ppl, err := Balance(pl, cfg) if err != nil { log.Printf("failed optimizing distribution: %s", err) return 3 } if len(ppl.Partitions) == 0 { break } opl.Partitions = append(opl.Partitions, ppl.Partitions...) } be.Flush(true) if *fullOutput { opl = pl } err = WritePartitionList(out, opl) if err != nil { log.Printf("failed writing partition list: %s", err) return 4 } return 0 } <file_sep># kafkabalancer Rebalance your kafka topics, partitions, replicas across your cluster ## Purpose `kafkabalancer` allows you to compute the set of rebalancing operations yielding a minimally-unbalanced kafka cluster, given a set of constraints: - set of allowed brokers (globally, or per partition) - number of desired replicas (per partition) - current distribution of replicas (per partition) - leader reassignment enabled/disabled (globally) - partition weight (per partition) The goal is to minimize the workload difference between brokers in the cluster, where the workload of a broker is measured by the sum of the weights of each partition having a replica on that broker. Additionally leaders have to do more work (producers and consumers only operate on the leader, followers fetch from the leaders as well) so the weight applied to leader partitions is assumed to be proportional to the sum of the number of replicas and consumer groups. The tool is designed to be used iteratively: at each iteration only a single reassignment operation is returned by kafkabalancer. This is useful in a automated framework like the following: ``` forever: if !kafka_cluster_is_nominal: continue state = get_current_state() change = kafkabalancer(state) if change: apply(change) ``` ## Installation `go get github.com/cafxx/kafkabalancer` ## Usage Run `kafkabalancer -help` for usage instructions. ``` Usage of ./kafkabalancer: -allow-leader Consider the partition leader eligible for rebalancing -broker-ids string Comma-separated list of broker IDs (default "auto") -from-zk string Zookeeper connection string (can not be used with -input) -full-output Output the full partition list: by default only the changes are printed -help Display usage -input string Name of the file to read (if no file is specified read from stdin, can not be used with -from-zk) -input-json Parse the input as JSON -max-reassign int Maximum number of reassignments to generate (default 1) -min-replicas int Minimum number of replicas for a partition to be eligible for rebalancing (default 2) -min-unbalance float Minimum unbalance value required to perform rebalancing (default 1e-05) -pprof Enable CPU profiling ``` ### How to perform rebalancing #### Getting the Kafka cluster state from zookeeper To emit the first suggested rebalancing operation for your Kafka cluster (`$ZK` is the comma-separated list of your zookeeper brokers): ``` kafkabalancer -from-zk $ZK > reassignment.json ``` To perform the suggested change, run the following command: ``` kafka-reassign-partitions.sh --zookeeper $ZK --reassignment-json-file reassignment.json --execute ``` If you want to generate/run more than a single rebalancing operation, specify a value greater than `1` for `-max-reassign`. #### Getting the Kafka cluster state from a dump of the partition list First dump the list of partitions from your Kafka broker (`$ZK` is the comma-separated list of your zookeeper brokers): ``` kafka-topics.sh --zookeeper $ZK --describe > kafka-topics.txt ``` Next run `kafkabalancer` on the list (note: this assumes that all partitions have the same weight and no consumers; this is functionally OK but could lead to suboptimal load distribution). `kafkabalancer` will analyze the list and suggest one or more reassignments: ``` kafkabalancer -input kafka-topics.txt > reassignment.json ``` To perform the suggested change(s), run the following command: ``` kafka-reassign-partitions.sh --zookeeper $ZK --reassignment-json-file reassignment.json --execute ``` If you want to generate/run more than a single rebalancing operation, specify a value greater than `1` for `-max-reassign`. ## Features - parse the output of kafka-topic.sh --describe or the Kafka cluster state in Zookeeper - parse the reassignment JSON format - output the reassignment JSON format - minimize leader unbalance (maximize global throughput) ### Planned - parse the output of kafka-offset.sh to get the per-partiton weights (number of messages) - fetch elsewhere additional metrics to refine the weights (e.g. number of consumers, size of messages) - minimize same-broker colocation of partitions of the same topic (maximize per-topic throughput) - proactively minimize unbalance caused by broker failure (i.e. minimize unbalance caused by one or more brokers failing) keeping into considerations how followers are elected to leaders when the leader fails - consider N-way rebalancing plans (e.g. swap two replicas) to avoid local minima - prefer to relocate "small" partitions to minimize the additional load due to moving data between brokers - use something like <https://github.com/wvanbergen/kazoo-go> to query state directly - use something like <https://github.com/wvanbergen/kazoo-go> to apply changes directly ## Scenarios This section lists some examples of how `kafkabalancer` operates. ### Adding brokers Setting `broker-ids=1,2,3` will move partition 1 from broker 2 to broker 3 to equalize the load: Part | Original | Output ---- | -------- | ------ 1 | 1,2 | 1,3 2 | 2,1 | 2,1 Setting `broker-ids=1,2,3,4` will move partition 1 from brokers 1,2 to brokers 4,3 to equalize the load: Part | Original | Output ---- | -------- | ------ 1 | 1,2 | 4,3 2 | 2,1 | 2,1 ### Removing brokers Setting `broker-ids=1,2` will move partition 3 from broker 3 to broker 2 to equalize the load: Part | Original | Output ---- | -------- | ------ 1 | 1,2 | 1,2 2 | 1 | 1 3 | 3 | 2 Setting `broker-ids=1` will return error because the partition 1 requires 2 replicas. ### Add replicas Setting `NumReplicas=2` for partition 3 will add a replica on broker 2 to equalize the load. Part | Original | Output ---- | -------- | ------ 1 | 1,2 | 1,2 2 | 1,3 | 1,3 3 | 3 | 2,3 ### Remove replicas Setting `NumReplicas=1` for partition 1 will remove the replica from broker 1 to equalize the load. Part | Original | Output ---- | -------- | ------ 1 | 1,2 | 2 2 | 1 | 1 ### Automated rebalancing If no changes need to be made, `kafkabalancer` will simply seek to equalize the load between brokers: Part | Original | Output ---- | -------- | ------ 1 | 1,2,3 | 1,4,3 2 | 1,2,4 | 1,2,4 3 | 1,2,3 | 1,2,3 If leader moving is enabled, also the leaders are eligible for rebalancing: Part | Original | Output ---- | -------- | ------ 1 | 1,2,3 | 4,2,1 2 | 1,2,4 | 3,2,4 3 | 1,2,3 | 1,2,3 ## How is rebalancing done `kafkabalancer` rebalancing capabilities are split in a series of step executed in order. The order of steps is chosen to prioritize constraints application first and then performance optimization. The steps are defined in `steps.go` and the ordering of the steps in `balancer.go`. When the steps need to identify the relative load of the cluster nodes, they use each partition weight as a relative measure of the workload the cluster has to sustain for that particular partition. The partition weight is then scaled by a multiplier and added to the total load of each node; the multiplier depends on the role of the node for that partition and is defined as: Leader | Follower ------------------------ | -------- `(Replicas)+(Consumers)` | `1` Where `(Replicas)` and `(Consumers)` are, respectively, the number of replicas and consumers of the partition. ### `ValidateWeights`, `ValidateReplicas` and `FillDefaults` These steps simply validate that the input data is consistent and they fill in any default value that is not explicitely defined. ### `RemoveExtraReplicas` and `AddMissingReplicas` These steps deal with any changes in the desired number of replicas by either removing replicas from the highest-loaded cluster nodes or by adding replicas to the lowest-loaded cluster nodes. ### `MoveDisallowedReplicas` This step detects if any replica is currently on a broker that is not in the list of allowed brokers and, if so, it moves those replicas to the lowest-loaded allowed brokers. ### `MoveLeaders` and `MoveNonLeaders` These steps attempt to redistribute replicas to minimize the load difference between brokers (see the section above to understand the metric used to measure load on each broker). `MoveLeaders` is a no-op if you don't specify `-allow-leader`. Leaders are moved before followers because the weight of leader partitions is normally greater than the one of follower partitions. ## Author <NAME> ([@cafxx](https://twitter.com/cafxx)) ## License [MIT](LICENSE) <file_sep>package main import "fmt" // ValidateWeights make sure that either all partitions have an explicit, // strictly positive weight or that all partitions have no weight func ValidateWeights(pl *PartitionList, _ RebalanceConfig) (*PartitionList, error) { hasWeights := pl.Partitions[0].Weight != 0 for _, p := range pl.Partitions { if hasWeights && p.Weight == 0 { return nil, fmt.Errorf("partition %v has no weight", p) } if !hasWeights && p.Weight != 0 { return nil, fmt.Errorf("partition %v has no weight", pl.Partitions[0]) } if p.Weight < 0 { return nil, fmt.Errorf("partition %v has negative weight", p) } } return nil, nil } // ValidateReplicas checks that partitions don't have more than one replica per // broker func ValidateReplicas(pl *PartitionList, _ RebalanceConfig) (*PartitionList, error) { for _, p := range pl.Partitions { replicaset := toBrokerSet(p.Replicas) if len(replicaset) != len(p.Replicas) { return nil, fmt.Errorf("partition %v has duplicated replicas", p) } } return nil, nil } // FillDefaults fills in default values for Weight, Brokers and NumReplicas func FillDefaults(pl *PartitionList, cfg RebalanceConfig) (*PartitionList, error) { // if the weights are 0, set them to 1 if pl.Partitions[0].Weight == 0 { for idx := range pl.Partitions { pl.Partitions[idx].Weight = 1.0 } } // if the set of candidate brokers is empty, fill it with the default set brokers := cfg.Brokers if brokers == nil { brokers = getBrokerList(pl) } for idx := range pl.Partitions { if pl.Partitions[idx].Brokers == nil { pl.Partitions[idx].Brokers = brokers } } // if the desired number of replicas is 0, fill it with the current number for idx := range pl.Partitions { if pl.Partitions[idx].NumReplicas == 0 { pl.Partitions[idx].NumReplicas = len(pl.Partitions[idx].Replicas) } } return nil, nil } // RemoveExtraReplicas removes replicas from partitions having lower NumReplicas // than the current number of replicas func RemoveExtraReplicas(pl *PartitionList, _ RebalanceConfig) (*PartitionList, error) { loads := getBrokerLoad(pl) for _, p := range pl.Partitions { if p.NumReplicas >= len(p.Replicas) { continue } brokersByLoad := getBrokerListByLoad(loads, p.Brokers) for _, b := range brokersByLoad { if inBrokerList(p.Replicas, b) { return replacepl(p, b, -1), nil } } return nil, fmt.Errorf("partition %v unable to pick replica to remove", p) } return nil, nil } // AddMissingReplicas adds replicas to partitions having NumReplicas greater // than the current number of replicas func AddMissingReplicas(pl *PartitionList, _ RebalanceConfig) (*PartitionList, error) { loads := getBrokerLoad(pl) // add missing replicas for _, p := range pl.Partitions { if p.NumReplicas <= len(p.Replicas) { continue } brokersByLoad := getBrokerListByLoad(loads, p.Brokers) for idx := len(brokersByLoad) - 1; idx >= 0; idx-- { b := brokersByLoad[idx] if !inBrokerList(p.Replicas, b) { return addpl(p, b), nil } } return nil, fmt.Errorf("partition %v unable to pick replica to add", p) } return nil, nil } // MoveDisallowedReplicas moves replicas from non-allowed brokers to the least // loaded ones func MoveDisallowedReplicas(pl *PartitionList, cfg RebalanceConfig) (*PartitionList, error) { loads := getBrokerLoad(pl) bl := getBL(loads) for _, p := range pl.Partitions { brokersByLoad := getBrokerListByLoadBL(bl, p.Brokers) for _, id := range p.Replicas { if inBrokerList(brokersByLoad, id) { continue } for _, b := range brokersByLoad { if inBrokerList(p.Replicas, b) { continue } return replacepl(p, id, b), nil } return nil, fmt.Errorf("partition %v unable to pick replica to replace broker %d", p, id) } } return nil, nil } func move(pl *PartitionList, cfg RebalanceConfig, leaders bool) (*PartitionList, error) { var cp Partition var cr, cb BrokerID loads := getBrokerLoad(pl) for _, id := range cfg.Brokers { if _, found := loads[id]; !found { loads[id] = 0 } } bl := getBL(loads) su := getUnbalanceBL(bl) cu := su for _, p := range pl.Partitions { if p.NumReplicas < cfg.MinReplicasForRebalancing { continue } replicas := p.Replicas[1:] if leaders { replicas = p.Replicas[0:1] } for _, r := range replicas { ridx := -1 var rload float64 for idx, b := range bl { if b.ID == r { ridx = idx rload = b.Load bl[idx].Load -= p.Weight } } if ridx == -1 { return nil, fmt.Errorf("assertion failed: replica %d not in broker loads %v", r, bl) } for idx, b := range bl { if !inBrokerList(p.Brokers, b.ID) { continue } if inBrokerList(p.Replicas, b.ID) { continue } bload := bl[idx].Load bl[idx].Load += p.Weight u := getUnbalanceBL(bl) if u < cu { cu, cp, cr, cb = u, p, r, b.ID } bl[idx].Load = bload } bl[ridx].Load = rload } } if cu < su-cfg.MinUnbalance { return replacepl(cp, cr, cb), nil } return nil, nil } // MoveNonLeaders moves non-leader replicas from overloaded brokers to // underloaded brokers func MoveNonLeaders(pl *PartitionList, cfg RebalanceConfig) (*PartitionList, error) { return move(pl, cfg, false) } // MoveLeaders moves leader replicas from overloaded brokers to underloaded // brokers func MoveLeaders(pl *PartitionList, cfg RebalanceConfig) (*PartitionList, error) { if !cfg.AllowLeaderRebalancing { return nil, nil } return move(pl, cfg, true) }
7ad59fb073d56ea92333c71be9ce5d5f7a6cd096
[ "Markdown", "Go" ]
3
Go
akthodu/kafkabalancer
917a869323dd461539f90faa6a8606a8616d995c
7250a59cb95d046e38055fccf8a824b6027f6602
refs/heads/main
<repo_name>freedomtowin/udac-data-eng-final-project-airflow-redshift-etl<file_sep>/airflow/plugins/operators/__init__.py from operators.stage_redshift import StageToRedshiftOperator from operators.load_fact import LoadFactOperator from operators.load_dimension import LoadDimensionOperator from operators.data_quality import RowCountOperator, NullPercentOperator from operators.postgres_operator import PostGresOperator __all__ = [ 'StageToRedshiftOperator', 'LoadFactOperator', 'LoadDimensionOperator', 'RowCountOperator', 'PostGresOperator' ] <file_sep>/airflow/dags/udac_example_dag.py from datetime import datetime, timedelta import os from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.hooks.postgres_hook import PostgresHook from operators import (StageToRedshiftOperator, LoadFactOperator, LoadDimensionOperator, RowCountOperator, NullPercentOperator, PostGresOperator) from helpers import SqlQueries #AWS_KEY = os.environ.get('AWS_KEY') #AWS_SECRET = os.environ.get('AWS_SECRET') default_args = { 'owner': 'rohan', 'start_date': datetime(2020, 1, 1), 'end_date': datetime(2020, 2, 1), 'depends_on_past': False, 'retries': 3, 'retry_delay': timedelta(minutes=2), 'catchup': True, 'email_on_retry': False } dag = DAG('udac_example_dag', default_args=default_args, description='Load and transform data in Redshift with Airflow', schedule_interval='@daily', max_active_runs=1 ) start_operator = DummyOperator(task_id='Begin_execution', dag=dag) stage_blocks_to_redshift = StageToRedshiftOperator( task_id='Stage_blocks', dag=dag, table='staging_blocks', redshift_conn_id="redshift_id", aws_credentials_id="aws_credentials", s3_bucket="rk-blockchain-db", s3_key="block", ftype='CSV', region='us-east-1', backfill_execution_date=True ) stage_transaction_to_redshift = StageToRedshiftOperator( task_id='Stage_transactions', dag=dag, table='staging_transactions', redshift_conn_id="redshift_id", aws_credentials_id="aws_credentials", s3_bucket="rk-blockchain-db", s3_key="transaction", ftype='CSV', region='us-east-1', backfill_execution_date=True ) stage_prices_to_redshift = StageToRedshiftOperator( task_id='Stage_prices', dag=dag, table='staging_prices', redshift_conn_id="redshift_id", aws_credentials_id="aws_credentials", s3_bucket="rk-blockchain-db", s3_key="price", ftype='JSON', ignore_headers=0, region='us-east-1', backfill_execution_date=True ) load_block_transaction_table = LoadFactOperator( task_id='Load_block_transaction_fact_table', dag=dag, redshift_conn_id='redshift_id', sql_query=SqlQueries.block_transaction_table_insert ) load_block_dimension_table = LoadDimensionOperator( task_id='Load_block_dim_table', dag=dag, redshift_conn_id='redshift_id', table="block", sql_query=SqlQueries.block_table_insert ) load_transaction_dimension_table = LoadDimensionOperator( task_id='Load_transaction_dim_table', dag=dag, redshift_conn_id='redshift_id', table="transactions", sql_query=SqlQueries.transaction_table_insert ) load_price_dimension_table = LoadDimensionOperator( task_id='Load_price_dim_table', dag=dag, redshift_conn_id='redshift_id', table="price", sql_query=SqlQueries.price_table_insert ) run_quality_checks_row_count = RowCountOperator( task_id='Run_data_quality_checks_row_cnt', dag=dag, redshift_conn_id='redshift_id', tables=["transactions", "block", "block_transaction", "price"] ) run_quality_checks_null_per = NullPercentOperator( task_id='Run_data_quality_checks_null_per', dag=dag, redshift_conn_id='redshift_id', tables=[ "block_transaction"] ) end_operator = DummyOperator(task_id='Stop_execution', dag=dag) start_operator>> stage_blocks_to_redshift start_operator>> stage_transaction_to_redshift start_operator>> stage_prices_to_redshift [stage_blocks_to_redshift, stage_transaction_to_redshift, stage_prices_to_redshift] >> load_block_transaction_table load_block_transaction_table >> load_transaction_dimension_table load_block_transaction_table >> load_block_dimension_table load_block_transaction_table >> load_price_dimension_table load_transaction_dimension_table >> run_quality_checks_row_count load_block_dimension_table >> run_quality_checks_row_count load_price_dimension_table >> run_quality_checks_row_count run_quality_checks_row_count >> run_quality_checks_null_per >> end_operator <file_sep>/airflow/plugins/operators/stage_redshift.py from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class StageToRedshiftOperator(BaseOperator): ui_color = '#358140' template_fields = ("s3_key",) copy_sql = """ COPY {} FROM '{}' ACCESS_KEY_ID '{}' SECRET_ACCESS_KEY '{}' IGNOREHEADER {} {} """ @apply_defaults def __init__(self, redshift_conn_id="", aws_credentials_id="", table="", s3_bucket="", s3_key="", # renders this value from context variables (reason: see line 8) ftype="JSON", ignore_headers=1, region='us-west-2', backfill_execution_date=False, *args, **kwargs): super(StageToRedshiftOperator, self).__init__(*args, **kwargs) # Map params here # Example: # self.conn_id = conn_id self.table = table self.redshift_conn_id = redshift_conn_id self.s3_bucket = s3_bucket self.s3_key = s3_key self.ignore_headers = ignore_headers self.aws_credentials_id = aws_credentials_id self.region = region self.ftype = ftype self.backfill_execution_date=backfill_execution_date def execute(self, context): self.log.info('StageToRedshiftOperator not implemented yet') aws_hook = AwsBaseHook(self.aws_credentials_id, client_type="s3") credentials = aws_hook.get_credentials() redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id) execution_date = context["execution_date"] self.log.info("Clearing data from destination Redshift table") redshift.run("DELETE FROM {}".format(self.table)) if self.ftype=='JSON': formatting = "format as json 'auto' compupdate off" elif self.ftype=='PARQUET': formatting = "format as parquet compupdate off" elif self.ftype=='CSV': formatting="removequotes delimiter '|' emptyasnull blanksasnull maxerror 5" s3_key = self.s3_key if self.backfill_execution_date==True: s3_key = '/'.join([s3_key, str(execution_date.year), str(execution_date.month)]) self.log.info("Copying data from S3 to Redshift") rendered_key = self.s3_key.format(**context) s3_path = "s3://{}/{}".format(self.s3_bucket, s3_key) formatted_sql = StageToRedshiftOperator.copy_sql.format( self.table, s3_path, credentials.access_key, credentials.secret_key, self.ignore_headers, formatting ) redshift.run(formatted_sql) self.log.info(f"Finished copying {self.table} from S3 to Redshift") <file_sep>/airflow/plugins/operators/postgres_operator.py from airflow.hooks.postgres_hook import PostgresHook from airflow.contrib.hooks.aws_hook import AwsHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class PostGresOperator(BaseOperator): ui_color = '#358140' @apply_defaults def __init__(self, redshift_conn_id="", sql_list="", *args, **kwargs): super(PostGresOperator, self).__init__(*args, **kwargs) self.redshift_conn_id = redshift_conn_id self.sql_list=sql_list def execute(self, context): redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id) self.log.info("Creating Redshift tables ") for command in self.sql_list: redshift.run(command)<file_sep>/airflow/plugins/helpers/sql_queries.py class SqlQueries: block_transaction_table_insert = (""" insert into block_transaction (transaction_hash, transaction_index, sender_address,receiver_address, miner_address, wei_value_x9, price, price_timestamp, block_timestamp, block_number, block_hash) SELECT t.hash, t.transaction_index, t.sender_address, t.receiver_address, b.miner miner_address, case when length(t.value)<=9 and length(value)>0 then cast(t.value as NUMERIC)/1000000 when length(t.value)>9 then cast(SUBSTRING(t.value, 0, length(t.value)-8)/10 as NUMERIC) else null end wei_value_x9, p.price, TO_TIMESTAMP(p.timestamp, 'YYYY-MM-DD HH24:MI:ss') price_timestamp, TO_TIMESTAMP(t.block_timestamp, 'YYYY-MM-DD HH24:MI:ss+00:00') block_timestamp, t.block_number, t.block_hash from ( select hash, nonce sender_trans_cnt, transaction_index, from_address sender_address, to_address receiver_address, REGEXP_REPLACE(value, '[^0-9]+','') value, gas, gas_price, receipt_cumulative_gas_used, receipt_gas_used, block_timestamp, block_number, block_hash from public.staging_transactions) t LEFT JOIN (select "timestamp", number, hash, miner from staging_blocks) b ON t.block_timestamp = b.timestamp AND t.block_number = b.number AND t.block_hash = b.hash LEFT JOIN (select "timestamp", close price from staging_prices) p ON TO_CHAR(TO_TIMESTAMP(t.block_timestamp, 'YYYY-MM-DD HH24:MI:ss+00:00'),'YYYY-MM-DD HH24')=TO_CHAR(TO_TIMESTAMP(p.timestamp, 'YYYY-MM-DD HH24:MI:ss'),'YYYY-MM-DD HH24') """) transaction_table_insert = (""" insert into transactions (hash, sender_trans_cnt, transaction_index, sender_address,reciever_address, wei_value_x9, gas, gas_price, receipt_cumulative_gas_used, receipt_gas_used, block_timestamp, block_number, block_hash) select hash, sender_trans_cnt, transaction_index, sender_address, reciever_address, case when length(value)<=9 and length(value)>0 then cast(value as NUMERIC)/1000000 when length(value)>9 then cast(SUBSTRING(value, 0, length(value)-8)/10 as NUMERIC) else null end wei_value_x9, gas, gas_price, receipt_cumulative_gas_used, receipt_gas_used, TO_TIMESTAMP("block_timestamp", 'YYYY-MM-DD HH24:MI:ss+00:00') block_timestamp, block_number, block_hash from ( select hash, nonce sender_trans_cnt, transaction_index, from_address sender_address, to_address reciever_address, REGEXP_REPLACE(value, '[^0-9]+','') value, gas, gas_price, receipt_cumulative_gas_used, receipt_gas_used, block_timestamp, block_number, block_hash from public.staging_transactions) """) block_table_insert = (""" insert into block (timestamp,block_number,hash,parent_hash, miner,difficulty,total_difficulty_x9,size_bytes,gas_limit,gas_used,transaction_count) select TO_TIMESTAMP("timestamp", 'YYYY-MM-DD HH24:MI:ss+00:00') as timestamp, number, hash, parent_hash, miner, difficulty, CAST(SUBSTRING(total_difficulty, 0, length(total_difficulty)-9) as BIGINT) total_difficulty_x9, size, gas_limit, gas_used, transaction_count from staging_blocks; """) price_table_insert = (""" insert into price ("timestamp","open",high,low,close, volume) SELECT TO_TIMESTAMP("timestamp", 'YYYY-MM-DD HH24:MI:ss') "timestamp", "open", high, low,close, volume FROM staging_prices """) <file_sep>/red_shift_create_tables.sql drop table public.staging_prices; CREATE TABLE if not exists public.staging_prices ( timestamp VARCHAR(100) NOT NULL, symbol VARCHAR(100), "open" NUMERIC, high NUMERIC, low NUMERIC, close NUMERIC, volume NUMERIC ); drop table public.staging_blocks; CREATE TABLE if not exists public.staging_blocks ( timestamp VARCHAR(400) NOT NULL, number BIGINT NOT NULL, hash VARCHAR(8000) NOT NULL, parent_hash VARCHAR(8000), nonce VARCHAR(8000) NOT NULL, sha3_uncles VARCHAR(8000), logs_bloom VARCHAR(8000), transactions_root VARCHAR(8000), state_root VARCHAR(8000), receipts_root VARCHAR(8000), miner VARCHAR(8000), difficulty BIGINT, total_difficulty VARCHAR(8000), size NUMERIC, extra_data VARCHAR(8000), gas_limit NUMERIC, gas_used NUMERIC, transaction_count NUMERIC ); drop table public.staging_transactions; CREATE TABLE if not exists public.staging_transactions ( hash VARCHAR(8000) NOT NULL, nonce INTEGER NOT NULL, transaction_index BIGINT NOT NULL, from_address VARCHAR(8000) NOT NULL, to_address VARCHAR(8000), value VARCHAR(8000), gas NUMERIC, gas_price NUMERIC, input VARCHAR(26000), receipt_cumulative_gas_used INTEGER, receipt_gas_used INTEGER, receipt_contract_address VARCHAR(8000), receipt_root VARCHAR(8000), receipt_status INTEGER, block_timestamp VARCHAR(400) NOT NULL, block_number INTEGER NOT NULL, block_hash VARCHAR(8000) NOT NULL ); drop table block_transaction; CREATE TABLE if not exists public.block_transaction ( transaction_hash VARCHAR(512) NOT NULL, transaction_index INTEGER NOT NULL, sender_address VARCHAR(512) NOT NULL, receiver_address VARCHAR(512), miner_address VARCHAR(512), wei_value_x9 NUMERIC, price NUMERIC, price_timestamp TIMESTAMP, block_timestamp TIMESTAMP NOT NULL, block_number BIGINT NOT NULL, block_hash VARCHAR(512) NOT NULL ); CREATE TABLE if not exists public.transactions ( hash VARCHAR(8000) NOT NULL, sender_trans_cnt INTEGER NOT NULL, transaction_index BIGINT NOT NULL, sender_address VARCHAR(512) NOT NULL, reciever_address VARCHAR(512), wei_value_x9 NUMERIC, gas NUMERIC, gas_price NUMERIC, receipt_cumulative_gas_used INTEGER, receipt_gas_used INTEGER, block_timestamp VARCHAR(512) NOT NULL, block_number INTEGER NOT NULL, block_hash VARCHAR(512) NOT NULL, CONSTRAINT transaction_hash_pkey PRIMARY KEY (hash) ); drop table block; CREATE TABLE if not exists public.block ( timestamp TIMESTAMP NOT NULL, block_number BIGINT NOT NULL, hash VARCHAR(512) NOT NULL, parent_hash VARCHAR(512), miner VARCHAR(512), difficulty NUMERIC, total_difficulty_x9 NUMERIC, size_bytes NUMERIC, gas_limit NUMERIC, gas_used NUMERIC, transaction_count NUMERIC, CONSTRAINT block_hash_pkey PRIMARY KEY (hash) ); drop table price; CREATE TABLE if not exists public.price ( timestamp TIMESTAMP NOT NULL, "open" NUMERIC, high NUMERIC, low NUMERIC, close NUMERIC, volume NUMERIC ); <file_sep>/push_json_to_s3.py import pandas as pd df = pd.read_csv('ETH_1H.csv') import re import numpy as np import pandas as pd import pyarrow as pa import pyarrow.parquet as pq from s3fs import S3FileSystem import datetime import requests import os import gc import io import json import boto3 class BlockChainDB(): def __init__(self): self.s3_filesystem = S3FileSystem() self.bucket = 'rk-blockchain-db' self.s3 = boto3.resource('s3') def partition_time(self,df,time_var,time_format): if self.process_time==True: df[time_var] = df[time_var].apply(lambda x: datetime.datetime.strptime(x,time_format)) df.sort_values(by=[time_var],inplace=True) dates = df[time_var].dt.date for t in sorted(np.unique(dates.values)): yield df[dates==t].copy() def push_data_s3(self,df,stream_name,time_var): df[time_var] = df[time_var].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")) dates = df[time_var].dt.date for t in sorted(np.unique(dates.values)): df_p = df[dates==t].copy() df_p['year'] = df_p[time_var].dt.year df_p['month'] = df_p[time_var].dt.month df_p['day'] = df_p[time_var].dt.day print(t) if df_p['year'].values[0]!=2020: continue write_path = "{STREAM_NAME}/{YEAR}/{MONTH}/{DAY}_data.json".format(STREAM_NAME=stream_name, YEAR=df_p['year'].values[0], MONTH=df_p['month'].values[0], DAY=df_p['day'].values[0]) df_p[time_var] = df_p[time_var].apply(lambda x: datetime.datetime.strftime(x, "%Y-%m-%d %H:%M:%S")) json_buffer = io.StringIO() df_p.to_json(json_buffer,orient='records') output = "" for record in json.loads(json_buffer.getvalue()): output+=json.dumps(record)+'\n' output.strip() s3_object = self.s3.Object(self.bucket, write_path) s3_object.put(Body=output) db = BlockChainDB() df = df[['Date','Symbol','Open','High','Low', 'Close', 'Volume']] df.columns = df.columns.map(lambda x: x.lower()) df = df.rename(columns={'date':'timestamp'})<file_sep>/airflow/plugins/operators/data_quality.py from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class RowCountOperator(BaseOperator): ui_color = '#89DA59' @apply_defaults def __init__(self, redshift_conn_id="", tables=[], *args, **kwargs): super(RowCountOperator, self).__init__(*args, **kwargs) self.redshift_conn_id = redshift_conn_id self.tables = tables def execute(self, context): redshift_hook = PostgresHook(self.redshift_conn_id) for table in self.tables: records = redshift_hook.get_records(f"SELECT COUNT(*) FROM {table}") if len(records) < 1 or len(records[0]) < 1 or records[0][0] < 1: self.log.error(f"Data quality check failed. {table} returned no results") raise ValueError(f"Data quality check failed. {table} returned no results") self.log.info(f"Data quality on table {table} check passed with {records[0][0]} records") class NullPercentOperator(BaseOperator): ui_color = '#89DA59' copy_sql = """ select column_name from information_schema.columns where table_name = '{TABLE}' order by ordinal_position; """ @apply_defaults def __init__(self, redshift_conn_id="", tables=[], *args, **kwargs): super(NullPercentOperator, self).__init__(*args, **kwargs) self.redshift_conn_id = redshift_conn_id self.tables = tables def execute(self, context): redshift_hook_1 = PostgresHook(self.redshift_conn_id) redshift_hook_2 = PostgresHook(self.redshift_conn_id) for table in self.tables: columns = redshift_hook_1.get_records(NullPercentOperator.copy_sql.format(**{"TABLE":table})) for col in columns: col = col[0] records = redshift_hook_2.get_records(f"SELECT SUM(CASE WHEN {col} IS NULL THEN 1 ELSE 0 END)/COUNT(*) FROM {table}") if len(records) < 1 or len(records[0]) < 1 or records[0][0] > 0.9: self.log.error(f"Data quality check failed. {table} {col} has >90% nulls,{records[0][0]}") raise ValueError(f"Data quality check failed. {table} {col} has >90% nulls, {records[0][0]}") self.log.info(f"Data quality on table {table} {col} check passed with {records[0][0]} %null values")<file_sep>/airflow/Dockerfile FROM apache/airflow:2.1.4 USER root RUN apt-get update \ && apt-get install -y --no-install-recommends \ vim \ && apt-get autoremove -yqq --purge \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* USER airflow<file_sep>/README.md # Capstone Project for Udacity's Data Engineering Nanodegree ## About The data sources, for this project, were collected from Google Cloud Platform with BigQuery. A data pipeline, two data sources, was create for the Ethereum classic blockchain, i.e., blocks and transactions. All blocks and transactions in 2020 were collected. Blocks are batches of transactions with a hash of the previous block in the chain. ... This prevents fraud, because one change in any block in history would invalidate all the following blocks as all subsequent hashes would change and everyone running the blockchain would notice. An Ethereum transaction refers to an action initiated by an externally-owned account, in other words an account managed by a human, not a contract. ... If a contract account, the transaction will execute the contract code) signature – the identifier of the sender. ## File Directory Description airflow/: ETL push_data_s3.py: Upload to S3 red_shift_create_tables.sql: Redshift create table statements bigquery_data_collection.py: BigQuery data collection ## Purpose The purpose of this data pipeline is to create a dashboard. Dashboard Elements: 1. Number of Large Transactions 2. Daily Active Addresses 3. Total Addresses 4. Ownership by Time Held 5. Transactions Made by Miners This dashboard could be helpful to someone looking to invest in crypto currency. The number of large transactions can be a useful to find large investments in the crypto currency. Similarly, the number of active addresses can be used to determined how the crypto currency is growing in popularity. It might also be interesting to see the transactions that crypto miners make. ## Data Model A star-schema data warehouse was used represent the historical blocks and transactions. The fact table has all transactions and important block-level information, such as, miner address. This fact table allows for quick analytical drill downs, and it is useful for creating dashboards. I collected ethereum prices from here: https://www.kaggle.com/prasoonkottarathil/ethereum-historical-dataset because I could not find an api that generated hourly historical prices for 2020. The daily raw data was stored in S3 in CSV format and partitioned on date: block data: s3://rk-blockchain-db/block/YEAR/MONTH/DAY.csv transaction data: s3://rk-blockchain-db/transaction/YEAR/MONTH/DAY.csv price data: s3://rk-blockchain-db/price/YEAR/MONTH/DAY.json ![](./images/UDAC_ERD.PNG) ** Note: Both data formats are CSVs, the data was initially collected via an API with BigQuery. With more time, I could add this to the data pipeline. ## Block Data Dictionary | Field name | Type | Mode | Description | | |-------------------|-----------|----------|----------------------------------------------------------------------|:-:| | timestamp | TIMESTAMP | REQUIRED | The timestamp for when the block was collated | | | number | INTEGER | REQUIRED | The block number | | | hash | STRING | REQUIRED | Hash of the block | | | parent_hash | STRING | NULLABLE | Hash of the parent block | | | nonce | STRING | REQUIRED | Hash of the generated proof-of-work | | | sha3_uncles | STRING | NULLABLE | SHA3 of the uncles data in the block | | | logs_bloom | STRING | NULLABLE | The bloom filter for the logs of the block | | | transactions_root | STRING | NULLABLE | The root of the transaction trie of the block | | | state_root | STRING | NULLABLE | The root of the final state trie of the block | | | receipts_root | STRING | NULLABLE | The root of the receipts trie of the block | | | miner | STRING | NULLABLE | The address of the beneficiary to whom the mining rewards were given | | | difficulty | NUMERIC | NULLABLE | Integer of the difficulty for this block | | | total_difficulty | NUMERIC | NULLABLE | Integer of the total difficulty of the chain until this block | | | size | INTEGER | NULLABLE | The size of this block in bytes | | | extra_data | STRING | NULLABLE | The extra data field of this block | | | gas_limit | INTEGER | NULLABLE | The maximum gas allowed in this block | | | gas_used | INTEGER | NULLABLE | The total used gas by all transactions in this block | | | transaction_count | INTEGER | NULLABLE | The number of transactions in the block | | ## Transaction Data Dictionary | Field name | Type | Mode | Description | | |-----------------------------|-----------|----------|------------------------------------------------------------------------------------------|:-:| | hash | STRING | REQUIRED | Hash of the transaction | | | nonce | INTEGER | REQUIRED | The number of transactions made by the sender prior to this one | | | transaction_index | INTEGER | REQUIRED | Integer of the transactions index position in the block | | | from_address | STRING | REQUIRED | Address of the sender | | | to_address | STRING | NULLABLE | Address of the receiver. null when its a contract creation transaction | | | value | NUMERIC | NULLABLE | Value transferred in Wei | | | gas | INTEGER | NULLABLE | Gas provided by the sender | | | gas_price | INTEGER | NULLABLE | Gas price provided by the sender in Wei | | | input | STRING | NULLABLE | The data sent along with the transaction | | | receipt_cumulative_gas_used | INTEGER | NULLABLE | The total amount of gas used when this transaction was executed in the block | | | receipt_gas_used | INTEGER | NULLABLE | The amount of gas used by this specific transaction alone | | | receipt_contract_address | STRING | NULLABLE | The contract address created, if the transaction was a contract creation, otherwise null | | | receipt_root | STRING | NULLABLE | 32 bytes of post-transaction stateroot (pre Byzantium) | | | receipt_status | INTEGER | NULLABLE | Either 1 (success) or 0 (failure) (post Byzantium) | | | block_timestamp | TIMESTAMP | REQUIRED | Timestamp of the block where this transaction was in | | | block_number | INTEGER | REQUIRED | Block number where this transaction was in | | | block_hash | STRING | REQUIRED | Hash of the block where this transaction was in | | ## Price Data Dictionary | Field name | Type | Mode | Description | | |------------|------------|----------|-----------------------------------------------|:-:| | timestamp | TIMESTAMP | REQUIRED | The timestamp for when the block was collated | | | open | NUMERIC | NULLABLE | The block number | | | high | NUMERIC | NULLABLE | Hash of the block | | | low | NUMERIC | NULLABLE | Hash of the parent block | | | close | NUMERIC | NULLABLE | Hash of the generated proof-of-work | | | volume | NUMERIC | NULLABLE | SHA3 of the uncles data in the block | | ## Data Pipeline Airflow was used to schdule an ETL from S3 into Redshift. The data was first copied to staging tables, and the post-processing was done in Redshift during the transform phase. Data quality checks were performed after the ETL. Backfilling was enabled in the DAG with catchup=True. The data was copied to redshift by month using the backfilling process. AWS and Redshift hooks configured in Airflow as well. A maximum of 3 "retries" were performed during the execution. ![](./images/UDAC_DATA_PIPELINE.PNG) ## Data Quality Checks I included two data quality checks: 1) ensure that there are records present in all fact and dimension tables and 2) ensure that there are <90% null values for each column in the fact table. ## Data Cleaning The dates needed to be converted to TIMESTAMP because the CSV files only have text data. The next issue was the length of some of the numeric fields. The value was represent in WEI which could have more than 25 digits, and this is larger than the maximum size for redshift. I needed to load these fields as text and then used custom post-processing to convert them to numeric. I used a X 9 multipler to represent this data. Some of the data elements, such as INPUT in the transaction table, had over 10,000 bytes. I excluded this field to save space. ## Hypothetical Scenarios ### Data increased by 100 x The data is partitioned by year and month. If the data was increased by x 100, the current data pipeline would be able to adequently handle it. The storage in the AWS Redshift cluster can also be scaled-up. The S3 data can be accessed and processed by multiple users without incurring much cost. The data could be replicated across regions for availability. ### The pipelines would be run on a daily basis by 7 am every day. Airflow has a scheduler that allows for job to be scheduled with CRON style commands. ### The database needed to be accessed by 100+ people If multiple users need to access the databse at once, the number of cores/compute, in the AWS Redshift cluster, can also be scaled-up. <file_sep>/bigquery_data_collection.py # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the read-only "../input/" directory # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import os print (os.listdir("../input")) # You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" # You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session # With the help of https://www.kaggle.com/yazanator/analyzing-ethereum-classic-via-google-bigquery from google.cloud import bigquery !pip install plotly from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode(connected=True) client = bigquery.Client() ethereum_classic_dataset_ref = client.dataset('crypto_ethereum_classic', project='bigquery-public-data') query = """ SELECT * FROM `bigquery-public-data.crypto_ethereum_classic.blocks` AS blocks WHERE timestamp>{} AND timestamp<="2021-01-02 00:00:00+00:00" ORDER BY timestamp LIMIT 100000 """ start_time='2020-01-01 00:00:00+00:00' end_time='2021-01-01 00:00:00+00:00' import datetime datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S+00:00")<datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S+00:00") result = [] start_time_format = '"{}"'.format(start_time) end_time_format = '"{}"'.format(end_time) while datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S+00:00")<datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S+00:00"): query_job = client.query(query.format(start_time_format,end_time_format)) iterator = query_job.result() rows = list(iterator) # Transform the rows into a nice pandas dataframe df = pd.DataFrame(data=[list(x.values()) for x in rows], columns=list(rows[0].keys())) start_time=str(df.timestamp.max()) start_time_format = '"{}"'.format(start_time) print('start time',start_time) result.append(df) block_df=pd.concat(result,axis=0) block_df.to_csv('blocks.csv',index=False) del result del block_df query = """ SELECT * FROM `bigquery-public-data.crypto_ethereum_classic.transactions` AS transactions WHERE block_timestamp>{} AND block_timestamp<="2021-01-02 00:00:00+00:00" ORDER BY block_timestamp LIMIT 100000 """ start_time='2020-01-01 00:00:00+00:00' end_time='2021-01-01 00:00:00+00:00' import datetime datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S+00:00")<datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S+00:00") import gc gc.collect() result = [] start_time_format = '"{}"'.format(start_time) end_time_format = '"{}"'.format(end_time) while datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S+00:00")<datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S+00:00"): query_job = client.query(query.format(start_time_format,end_time_format)) iterator = query_job.result() rows = list(iterator) # Transform the rows into a nice pandas dataframe df = pd.DataFrame(data=[list(x.values()) for x in rows], columns=list(rows[0].keys())) start_time=str(df.block_timestamp.max()) start_time_format = '"{}"'.format(start_time) print('start time',start_time) print('size',df.shape[0]) result.append(df) transactions_df=pd.concat(result,axis=0) transactions_df.to_csv('transactions.csv',index=False) <file_sep>/push_csv_s3.py import re import numpy as np import pandas as pd import pyarrow as pa import pyarrow.parquet as pq from s3fs import S3FileSystem import datetime import requests import os import gc class BlockChainDB(): def __init__(self): self.s3_filesystem = S3FileSystem() self.bucket = 'rk-blockchain-db' def partition_time(self,df,time_var,time_format): if self.process_time==True: df[time_var] = df[time_var].apply(lambda x: datetime.datetime.strptime(x,time_format)) df.sort_values(by=[time_var],inplace=True) dates = df[time_var].dt.date for t in sorted(np.unique(dates.values)): yield df[dates==t].copy() def push_data_s3(self,df,stream_name,time_var): df[time_var] = df[time_var].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S+00:00")) dates = df[time_var].dt.date for t in sorted(np.unique(dates.values)): df_p = df[dates==t].copy() df_p['year'] = df_p[time_var].dt.year df_p['month'] = df_p[time_var].dt.month df_p['day'] = df_p[time_var].dt.day print(t) write_path = "s3://{BUCKET_NAME}/{STREAM_NAME}/{YEAR}/{MONTH}/{DAY}_data.csv".format(BUCKET_NAME=self.bucket,STREAM_NAME=stream_name, YEAR=df_p['year'].values[0], MONTH=df_p['month'].values[0], DAY=df_p['day'].values[0]) df_p.to_csv(write_path,index=False,sep = '|') db = BlockChainDB() blocks = pd.read_csv('blocks.csv') db.push_data_s3(blocks,'block','timestamp') del blocks gc.collect() transactions = pd.read_csv('transactions.csv') db.push_data_s3(transactions,'transaction','block_timestamp')
253f9994de3d2c46398853b9e4c4e42a54e377c7
[ "Markdown", "SQL", "Python", "Dockerfile" ]
12
Python
freedomtowin/udac-data-eng-final-project-airflow-redshift-etl
bf4c2fd8d4cbc8a8e86379c761aac3b8dc320ea2
66ac39a03f0a117aa7f24d9fb5f8b4195c462753
refs/heads/master
<repo_name>i618/LambdaOptimization<file_sep>/LambdaFuncOptimization/LambdaFuncOptimizer.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace LambdaFuncOptimization { internal class LambdaFuncOptimizer : ExpressionVisitor { private readonly List<ParameterExpression> vars = new List<ParameterExpression>(); private readonly List<Expression> exprs = new List<Expression>(); public Expression<T> Run<T>(Expression<T> expr) where T : Delegate { Expression<T> changedExpr = (Expression<T>)Visit(expr); exprs.Add(changedExpr.Body); return Expression.Lambda<T>( Expression.Block(vars, exprs), changedExpr.Parameters); } protected override Expression VisitMethodCall(MethodCallExpression node) { if (node.Method.IsDefined(typeof(LambdaFuncOptimizationAttribute)) && node.Method.ReturnType != typeof(void)) { string varName = node.ToString().Replace("(", "").Replace(")", "").ToLower(); ParameterExpression funcVar = vars.Find((x) => varName == x.Name); if (funcVar == null) { funcVar = Expression.Variable(node.Method.ReturnType, varName); vars.Add(funcVar); BinaryExpression assignExpr = Expression.Assign(funcVar, node); exprs.Add(assignExpr); } return funcVar; } return base.VisitMethodCall(node); } } } <file_sep>/LambdaFuncOptimization/LambdaFuncOptimization.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace LambdaFuncOptimization { public static class Optimization { public static T Run<T>(Expression<T> expr) where T : Delegate { LambdaFuncOptimizer opt = new LambdaFuncOptimizer(); return opt.Run<T>(expr).Compile(); } } } <file_sep>/Test/main.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Runtime; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Threading; using LambdaFuncOptimization; namespace Test { class Program { static void Main(string[] args) { Func<int, int, int> someDelegate = (int x, int y) => SomeFunc(x) > SomeFunc(y) ? SomeFunc(x) : SomeFunc(y); someDelegate(1000, 1500); Console.WriteLine("--------"); someDelegate = Optimization.Run<Func<int, int, int>>( (int x, int y) => SomeFunc(x) > SomeFunc(y) ? SomeFunc(x) : SomeFunc(y) ); someDelegate(1000, 1500); Action someDelegate1 = Optimization.Run<Action>( () => SomeFunc1() ); Console.ReadLine(); } [LambdaFuncOptimization] private static int SomeFunc(int param) { Console.WriteLine(String.Format("Ждем {0} мс", param)); Thread.Sleep(param); return param; } [LambdaFuncOptimization] private static void SomeFunc1() { // ; } } } <file_sep>/LambdaFuncOptimization/LambdaFuncOptimizationAttribute.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaFuncOptimization { [AttributeUsage(AttributeTargets.Method)] public class LambdaFuncOptimizationAttribute : Attribute { } }
3097cf454f5f847ae0e68f1dde1f516941d072b7
[ "C#" ]
4
C#
i618/LambdaOptimization
5b8e52dda06688ebd0e4b7998a9b08ee034edf4b
376d663f892d55b6fdb1cc5e0ae611da7bb975f1
refs/heads/master
<repo_name>cv-bit/CameronV-Projects-Algorithms<file_sep>/Arrays/ToDo1.js //push front function pushFront(arr, value) { for(let i = arr.length; i > 0; i--) arr[i] = arr[i-1] arr[0] = value; } //pop front function popFront(arr) { const val = arr[0]; for(let i = 0; i < arr.length; i++) arr[i] = arr[i + 1]; arr.length = arr.length - 1; return val; } //insert at function insertAt(arr, idx, val) { for(let i = arr.length; i > idx; i--) arr[i] = arr[i-1] arr[idx] = val; } //remove at function removeAt(arr, idx) { toRemove = arr[idx]; for(let i = idx; i < arr.length-1; i++) { arr[i] = arr[i+1]; } arr.length = arr.length-1; return toRemove; } //swap pairs function swapPairs(arr) { for(let i = 0; i < arr.length - 1; i = i + 2) { let temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } } //remove duplicates function removeDupesUnnested(arr) { let newArr = []; for(let i = 0; i < arr.length; i++) { if(arr[i] !== arr[i+1]) newArr.push(arr[i]) } return newArr; }<file_sep>/Arrays/min_to_front.js var arr=[4,2,1,3,5]; var min=arr[0] var temp; for(let i=0;i<arr.length;i++){ if(arr[i]<min){ temp=arr[0]; min=arr[i]; arr[0]=min arr[i]=temp } }
1a80d161512a129cd4465710f355453f99f03e30
[ "JavaScript" ]
2
JavaScript
cv-bit/CameronV-Projects-Algorithms
d29c5b76e82f44d2e518ebfab9ed8a191b5216ea
4408d567da671837c2cb49dcc6570256c8c5ebd5
refs/heads/master
<file_sep>import java.util.HashMap; public class Number { private int total; private int[] array; private static int[] totalToArray(int t) { int[] out = new int[10]; String s = Integer.toString(t); for (int i=0; i<s.length(); i++) { int digit = Character.getNumericValue(s.charAt(i)); out[digit]++; } return out; } private static int arrayToTotal(int[] a) { assert a.length == 10; String out = ""; for (int i=0; i<a.length; i++) { out += new String(new char[a[i]]).replace("\0", Integer.toString(i)); } return Integer.parseInt(out); } Number(int t) { total = t; array = totalToArray(t); } Number(int[] a) { total = arrayToTotal(a); array = a; } public int getMultiplicitivePersistence() { int next = 1; String s = Integer.toString(total); for (int i=0; i<s.length(); i++) { int digit = Character.getNumericValue(s.charAt(i)); next *= digit; } if (next == total) { return 0; } else { return 1 + new Number(next).getMultiplicitivePersistence(); } } public static int getWithMemoisation(HashMap<Integer, Integer> mem, Integer num) { if (mem.keySet().contains(num)) { return mem.get(num); } else { int next = 1; String s = Integer.toString(num); for (int i=0; i<s.length(); i++) { int digit = Character.getNumericValue(s.charAt(i)); next *= digit; } if (next == num) { mem.put(num, 0); return 0; } else { Integer result = 1 + getWithMemoisation(mem, next); mem.put(num, result); return result; } } } }
74a53cf64112e425d0eaeb9f34d32999bc1ad247
[ "Java" ]
1
Java
Djhopper/Multiplicative-Persistence
e0564ddc83905e197cef528f82667f7e34f1a1e9
52898dadeb92d6f4736bd9d8ee4141e3f9c76420
refs/heads/master
<repo_name>hozmaster/earthquake-map<file_sep>/server.js const r = require("rethinkdb"); const express = require("express"); const bluebird = require("bluebird"); const cors = require("cors"); const config = require("./config"); const server = express(); // server.use (cors); // server.use(express.static(__dirname + "/public")); const feedUrl = "earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.geojson"; // Fetch data from the USGS earthquake feed and transform all // the locations into point objects. Insert the data into the // `quakes` table. This query is assigned to a variable so it // can easily be reused in two different parts of the program. const refresh = r.table("quakes").insert( r.http(feedUrl)("features").merge(function (item) { return { geometry: r.point( item("geometry")("coordinates")(0), item("geometry")("coordinates")(1)) } }), {conflict: "replace"}); // Perform initial setup, creating the database and table // It also creates a geospatial index on the `geometry` property // and performs the query above in order to populate the data let conn; r.connect(config.database).then(function (c) { conn = c; return r.dbCreate(config.database.db).run(conn); }) .then(function () { return r.tableCreate("quakes").run(conn); }) .then(function () { return r.table("quakes").indexCreate( "geometry", {geo: true}).run(conn); }) .then(function () { return refresh.run(conn); }) .error(function (err) { if (err.msg.indexOf("already exists") == -1) console.log(err); }) .finally(function () { if (conn) conn.close(); }); // Use the refresh query above to automatically update the the // earthquake database with new data at 30 minute intervals and // delete the records that are older than 30 days setInterval(function () { let conn; r.connect(config.database).then(function (c) { conn = c; return bluebird.join(refresh.run(conn), r.table("quakes") .filter(r.epochTime(r.row("properties")("time").div(1000)).lt( r.now().sub(60 * 60 * 24 * 30))).delete().run(conn)); }) .error(function (err) { console.log("Failed to refresh:", err); }) .finally(function () { if (conn) conn.close(); }); }, 30 * 1000 * 60); // Define the `/quakes` endpoint for the backend API. It queries // the database and retrieves the earthquakes ordered by magnitude // and then returns the output as a JSON array server.get("/quakes", function (req, res) { console.log ("conencted"); let conn; r.connect(config.database).then(function (c) { conn = c; return r.table("quakes").orderBy( r.desc(r.row("properties")("mag"))).run(conn); }) .then(function (cursor) { return cursor.toArray(); }) .then(function (result) { console.log(result); res.json(result); }) .error(function (err) { console.log("Error handling /quakes request:", err); res.status(500).json({success: false, err: err}); }) .finally(function () { if (conn) conn.close(); }); }); // Define the `/nearest` endpoint for the backend API. It takes // two URL query parameters, representing the latitude and longitude // of a point. It will query the `quakes` table to find the closest // earthquake, which is returned as a JSON object server.get("/nearest", function (req, res) { const latitude = req.param("latitude"); const longitude = req.param("longitude"); console.log (latitude); if (!latitude || !longitude) return res.status(500).json({err: "Invalid Point"}); let conn; r.connect(config.database).then(function (c) { conn = c; return r.table("quakes").getNearest( r.point(parseFloat(longitude), parseFloat(latitude)), {index: "geometry", maxDist: 1000, unit: "mi"}).run(conn); }) .then(function (result) { res.json(result); }) .error(function (err) { console.log("Error handling /nearest request:", err); res.status(500).json({err: err}); }) .finally(function () { if (conn) conn.close(); }); }); server.listen(config.port); console.log("Server started on port", config.port); <file_sep>/app/src/Components/TileLayer.js /* * Copyright (c) 2019. <NAME> All rights reserved */ import 'leaflet/dist/leaflet.css'; import * as L from "leaflet"; import {TileLayer} from "leaflet/dist/leaflet-src.esm"; let tileMapLayer = {}; tileMapLayer.OSM = L.TileLayer.extend({ options: { minZoom: 2, maxZoom: 19, }, initialize: function initialize(options) { options = L.setOptions(this, options); options.tileSize = 256; const path = "/{z}/{x}/{y}.png"; const tileServer = "{s}.tile.openstreetmap.org"; const tileUrl = "https://" + tileServer + path; L.TileLayer.prototype.initialize.call(this, tileUrl, options); this._attributionText = ""; }, // appendMarker: function appnedMarker(quake) { // // let marker = L.circleMarker(quake.point, { // radius: quake.properties.mag * 2, // fillColor: "#616161", color: "#616161" // }); // // this.addLayer(marker); // // }, // // addMarkers: function addmarkers(quakes) { // this.clearLayers(); // this.map_markers = []; // quakes.forEach(quake => { // this.appendMarker(quake); // }); // }, onClick: function onClick (event) { console.log (event); }, onAdd: function onAdd(map) { L.TileLayer.prototype.onAdd.call(this, map); const attributions = [ '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>' ]; const attributionText = "© " + attributions.join(", ") + ". "; if (attributionText !== this._attributionText) { map.attributionControl.removeAttribution(this._attributionText); map.attributionControl.addAttribution( (this._attributionText = attributionText) ); } map.on('click', this.onClick); }, onRemove: function onRemove(map) { L.TileLayer.prototype.onRemove.call(this, map); L.TileLayer.prototype.onRemove.call(this, map); this._map.attributionControl.removeAttribution(this._attributionText); this._map.off("moveend zoomend resetview", this._findCopyrightBBox, this); } }); TileLayer.osm = function (opts) { return new tileMapLayer.OSM(opts); }; export default TileLayer;<file_sep>/app/src/actions/index.js /* * Copyright (c) 2019. <NAME> All rights reserved */ let nextTodoId = 0 export const getQuakes= text => ({ type: 'GET_QUAKES', id: nextTodoId++, text }) <file_sep>/app/src/Components/QuakeLayer.js /* * Copyright (c) 2019. <NAME> All rights reserved */ import * as L from "leaflet"; import {marker} from "leaflet/dist/leaflet-src.esm"; let quakeMarkerLayer = {}; quakeMarkerLayer.OSM = L.LayerGroup.extend({ options: {}, markers: [], initialize: function initialize(options) { const t_options = L.setOptions(this, options); L.LayerGroup.prototype.initialize.call(this, t_options); }, onAdd: function onAdd(map) { L.LayerGroup.prototype.onAdd.call(this, map); }, onRemove: function onRemove(map) { L.LayerGroup.prototype.onRemove.call(this, map); }, insertMarker: function insertMarker(quake) { quake.point = L.latLng( quake.geometry.coordinates[1], quake.geometry.coordinates[0]); let marker = L.circleMarker(quake.point, { radius: quake.properties.mag * 2, fillColor: "#616161", color: "#616161" }); this.addLayer(marker); quake.marker_id = this.getLayerId(marker); this.markers.push(quake); } }); quakeMarkerLayer.osm = function (opts) { return new quakeMarkerLayer.OSM(opts); }; export default quakeMarkerLayer;<file_sep>/README.md ## RethinkDB Earthquake Map This application uses [data from the USGS](http://earthquake.usgs.gov/earthquakes/feed/v1.0/) to display earthquakes detected over the last 30 days. The earthquakes are displayed in a list view and an interactive map. The backend is written with node.js and [RethinkDB](http://rethinkdb.com/), taking advantage of the new GeoJSON functionality introduced in RethinkDB 1.15. The frontend is built with AngularJS and the Leaflet mapping library, with map tiles provided by [OpenStreetMap project](http://www.openstreetmap.org/). ![Earthquake Map](/screenshots/earthquake-map.png?raw=true) <file_sep>/config.js module.exports = { database: { db: "quake", host: process.env.RDB_HOST || "localhost", port: process.env.RDB_PORT || 32769 }, port: 8090 }; <file_sep>/app/src/actions/actions.js /* * Copyright (c) 2019. <NAME> All rights reserved */ export const GET_QUAKES = 'GET_QUAKES' export const ADD_NOTE = 'ADD_NOTE' export function getQuakes(text) { return { type: GET_QUAKES, text } } export function addNote(text) { return { type: ADD_NOTE, text } } <file_sep>/app/src/reducers/reducers.js /* * Copyright (c) 2019. <NAME> All rights reserved */ import { combineReducers } from 'redux' import { GET_QUAKES, ADD_NOTE } from '../actions/actions' function quakesOps(state = [], action) { switch (action.type) { case GET_QUAKES: return [ ...state, { text: action.text, completed: false } ] case ADD_NOTE: return [ ...state, { text: action.text, completed: false } ] default: return state } } const quakesApp = combineReducers({ quakesOps }); export default quakesApp<file_sep>/app/src/reducers/places.js /* * Copyright (c) 2019. <NAME> All rights reserved */ const places = (state = [], action) => { switch (action.type) { case 'GET_QUAKES': return [ ...state, { id: action.id, text: action.text, completed: false } ] default: return state } } export default places<file_sep>/app/src/Components/Map.jsx /* * Copyright (c) 2019. <NAME> All rights reserved */ import React from 'react'; import 'leaflet/dist/leaflet.css'; import L from 'leaflet'; import TileLayer from "./TileLayer"; import quakeMarkerLayer from "./QuakeLayer" import quakesData from '../assets/quakes' import {Container} from "semantic-ui-react"; const style = { width: '100%', height: '100vh' }; const baseMapLayer = TileLayer.osm ({ }); const quakeLayer = quakeMarkerLayer.osm({}); const mapParams = { center : [0.00, 0.00], zoomControl: false, zoom: 7, layers: [baseMapLayer, quakeLayer] }; class Map extends React.Component { constructor(props) { super(props); this.state = {quakes: []}; } componentDidMount() { // fetch('http://localhost:3007/quakes') // .then(data => data.json()) // .then((data) => { this.setState({ quakes: data }) }); // create map this.map = L.map('map', mapParams); // to be ability disable/enable control const baseMaps = { 'map': baseMapLayer }; const overlayMaps = { "Quakes 4+": quakeLayer }; // L.control.layers(baseMaps,overlayMaps).addTo(this.map); // we do want a zoom control L.control .zoom({ position: 'topright' }) .addTo(this.map); quakeLayer.insertMarker(quakesData[0]); } render() { return( <div> <div id="map" style={style}> </div> </div> ) } } export default Map;<file_sep>/server/routes/quakes.js const r = require("rethinkdb"); const express = require('express'); const router = express.Router(); const bluebird = require("bluebird"); const config = require("./../data/config"); const feedUrl = "earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.geojson"; // Fetch data from the USGS earthquake feed and transform all // the locations into point objects. Insert the data into the // `quakes` table. This query is assigned to a variable so it // can easily be reused in two different parts of the program. const refresh = r.table("quakes").insert( r.http(feedUrl)("features").merge(function (item) { return { geometry: r.point( item("geometry")("coordinates")(0), item("geometry")("coordinates")(1)) } }), {conflict: "replace"}); // Use the refresh query above to automatically update the the // earthquake database with new data at 30 minute intervals and // delete the records that are older than 30 days setInterval(function () { let conn; r.connect(config.database).then(function (c) { conn = c; console.log("Refresh data"); return bluebird.join(refresh.run(conn), r.table("quakes") .filter(r.epochTime(r.row("properties")("time").div(1000)).lt( r.now().sub(60 * 60 * 24 * 30))).delete().run(conn)); }) .error(function (err) { console.log("Failed to refresh:", err); }) .finally(function () { if (conn) conn.close(); }); }, 10 * 1000 * 60); let conn; r.connect(config.database).then(function (c) { conn = c; return r.dbCreate(config.database.db).run(conn); }) .then(function () { return r.tableCreate("quakes").run(conn); }) .then(function () { return r.table("quakes").indexCreate( "geometry", {geo: true}).run(conn); }) .then(function () { return refresh.run(conn); }) .error(function (err) { if (err.msg.indexOf("already exists") == -1) console.log(err); }) .finally(function () { if (conn) conn.close(); }); router.get("/", function (req, res, next) { let conn; r.connect(config.database).then(function (c) { conn = c; return r.table("quakes").orderBy( r.desc(r.row("properties")("mag"))).run(conn); }) .then(function (cursor) { return cursor.toArray(); }) .then(function (result) { res.json(result); }) .error(function (err) { console.log("Error handling /quakes request:", err); res.status(500).json({success: false, err: err}); }) .finally(function () { if (conn) conn.close(); }); }); module.exports = router; <file_sep>/app/src/Components/Control.jsx /* * Copyright (c) 2019. <NAME> All rights reserved */ import React from "react" import { Segment, Item, ItemImage, Divider, } from "semantic-ui-react" // some inline styles (we should move these to our index.css at one stage) const segmentStyle = { zIndex: 999, position: "absolute", width: "400px", top: "10px", left: "10px", maxHeight: "calc(100vh - 5vw)", overflow: "auto", padding: "20px" }; class Control extends React.Component { constructor(props) { super(props); this.state = { quakes: props.quakes, }; } render() { return ( <div> <Segment floated='left' style={segmentStyle} > <div> <span> <strong> Quakes Monitor </strong> </span> <Divider/> </div> <Item.Group divided={true}> { this.state.quakes.map((quake,key) => <Item key={quake.id}> <Item.Content> <Item.Header >{quake.properties.title}</Item.Header> <Item.Meta>Type : {quake.properties.type}</Item.Meta> <Item.Meta>Magnitude : {quake.properties.mag}</Item.Meta> <Item.Extra as='a' onClick={(quake.properties.details)}> Link</Item.Extra> </Item.Content> </Item>) } </Item.Group> </Segment> </div> ) } } export default Control;<file_sep>/app/src/App.jsx /* * Copyright (c) 2019. <NAME> All rights reserved */ import React, {Component} from 'react'; import Map from './Components/Map'; import './App.css'; import Control from "./Components/Control"; import quakesData from './assets/quakes'; class App extends React.Component { constructor(props) { super(props); this.state = { quakes: quakesData }; } render () { return ( <div> <Map/> <Control quakes = {this.state.quakes}/> </div> ); } } export default App; <file_sep>/public/app.js var app = angular.module("quakes", []); app.controller("MainController", [ "$rootScope", "$scope", "$http", function ($rootScope, $scope, $http) { // When the user's location changes, remove any existing user // markers and create a new one at the user's coordinates $scope.$watch("userLocation", function (newVal, oldVal) { if (!newVal) return; if ($scope.userMarker) $scope.map.removeLayer($scope.userMarker); var point = L.latLng(newVal.latitude, newVal.longitude); $scope.userMarker = L.marker(point, { icon: L.icon({iconUrl: "mark.png"}) }); $scope.map.addLayer($scope.userMarker); }); // When earthquakes are added or removed from the filtered array // Add or remove the corresponding markers so that the map is // consistent with the earthquake list $scope.$watchCollection("filteredQuakes", function (addItems, removeItems) { if (removeItems && removeItems.length) for (var i in removeItems) $scope.map.removeLayer(removeItems[i].marker); if (addItems && addItems.length) for (var i in addItems) $scope.map.addLayer(addItems[i].marker); }); // When this custom filter is applied to the quake array, it will // will include only the earthquakes that occurred on the day that // the user specifies in the date control $scope.isSameDay = function (item) { if (!$scope.date) return true; var date = new Date(item.properties.time); var targetDate = new Date($scope.date + " "); return date.getYear() === targetDate.getYear() && date.getMonth() === targetDate.getMonth() && date.getDate() === targetDate.getDate(); }; // This function uses the browser geolocation APIs to fetch the user's // location. The coordinates are passed to the backend's `/nearest` // endpoint as URL query parameters. The `/nearest` endpoint returns // the closest earthquake and its distance, which are assigned to // variables within the current scope $scope.updateUserLocation = function () { navigator.geolocation.getCurrentPosition(function (position) { $scope.userLocation = position.coords; $http.get("/nearest", {params: position.coords}) .success(function (output) { if (!output.length) return; $scope.nearest = output[0].doc.id; $scope.nearestDistance = output[0].dist; }).error(function (err) { console.log("Failed to retrieve nearest quake:", err); }); }); }; // This function fetches the list of earthquakes from the backend's // `/quakes` endpoint. After fetching the quakes, it extracts the // coordinates and creates a place marker which is stored in a // property of the quake object. The actual place markers are applied // in the `$watchCollection` statement above $scope.fetchQuakes = function () { $http.get("/quakes").success(function (quakes) { for (var i in quakes) { quakes[i].point = L.latLng( quakes[i].geometry.coordinates[1], quakes[i].geometry.coordinates[0]); quakes[i].marker = L.circleMarker(quakes[i].point, { radius: quakes[i].properties.mag * 2, fillColor: "#616161", color: "#616161" }); } $scope.quakes = quakes; }).error(function (err) { console.log("Failed to retrieve quakes:", err); }); }; // This function is called when the user clicks on an earthquake // in the earthquake list. It assigns the selected earthquake to // the `selectedQuake` variable in the current scope and then // adjusts the map to bring the quake into focus. $scope.selectQuake = function (quake) { $scope.selectedQuake = quake; $scope.map.setView(quake.point, 5, {animate: true}); }; // Instantiate the map and configure the tile layer // The map uses tiles provided by the OpenStreetMap project $scope.map = L.map("map").setView([0, 0], 2); $scope.map.addLayer(L.tileLayer( "http://{s}.tile.osm.org/{z}/{x}/{y}.png", {attribution: "<a href=\"http://osm.org/copyright\">OpenStreetMap</a>"} )); $scope.fetchQuakes(); $scope.updateUserLocation(); } ]); <file_sep>/server/data/config.js /* * Copyright (c) 2019. <NAME> All rights reserved */ const fs = require('fs'); let service = {}; try { const raw_data = fs.readFileSync(__dirname + '/config.json'); service = JSON.parse(raw_data); } catch (e) { throw "Required config.json not found from the installation."; } module.exports = { database: { db: service.rdb.database, host: process.env.RDB_HOST || service.rdb.host, port: process.env.RDB_PORT || service.rdb.port } };
7de9bc6307ff0d9a18b5a9c25391c21cf3ddf6d6
[ "JavaScript", "Markdown" ]
15
JavaScript
hozmaster/earthquake-map
f3ffeb0d56fb0538137de39f7c21c12101d08379
79a2fecdf6a20af6b458877044385fa4008b6b01
refs/heads/master
<file_sep>from pympler import asizeof import sys def generator_function(num): for i in range(num): yield (i**3) gen_list = [x**3 for x in range(1000)] gen = generator_function(1000000000000) print(sys.getsizeof(gen)) print(sys.getsizeof(gen_list)) print(asizeof.asizeof(gen)) print(asizeof.asizeof(gen_list)) print(next(gen)) print(next(gen)) print(next(gen)) print(next(gen)) <file_sep># интернирование строк a = 'abcdefg' b = 'abcdefg' print(a is b) print(id(a), id(b)) print(a == b)<file_sep># Найти площадь и периметр прямоугольного треугольника по двум заданным катетам. class Triangle: __slots__ = ('x', 'y') # два катета def __init__(self, x, y): self.x = x self.y = y # Площадь треугольника равна половине площади прямоуглоьника, сторонами которого являются катеты. def square(self): return self.x * self.y / 2 # Периметр - сложение всех сторон треугольника. def perimeter(self): # Найдем гипотенузу. c = (self.x**2 + self.y**2)**0.5 return c + self.x + self.y if __name__ == '__main__': triangle = Triangle(1,2) print(triangle.square()) print(round(triangle.perimeter(),2)) <file_sep>''' Пользователь вводит трехзначное число. Программа должна сложить цифры, из которых состоит это число. ''' input_number = int(input('Введите трехзначное число')) sum_of_digits = 0 for i in range(3): last_digit = input_number%10 sum_of_digits += last_digit input_number //= 10 print(sum_of_digits) <file_sep>'''Вводятся два числа в двоичной системе счисления. Требуется выполнить над ними побитовые операции И, ИЛИ и исключающее ИЛИ. Вывести результат операций в двоичном представлении.''' n1 = input('Введите первое число в двоичной системе:') n2 = input('Введите второе число в двоичной системе:') # int('...', 2) преобразует строку с числом в число с базой 2 n1 = int(n1, 2) n2 = int(n2, 2) n_and = n1 & n2 n_or = n1 | n2 n_xor = n1 ^ n2 n_not_n1 = ~ n1 n_not_n2 = ~ n2 slide = n1 << 2 print(bin(n_and)) print(bin(n_or)) print(bin(n_xor)) print(bin(n_not_n1)) print(bin(n_not_n2)) print(bin(slide)) # Логическое И # n1 = 2 # print(bin(n1)) # # # help(int) # print(int('10', base=2))<file_sep>class SlotsClass: __slots__ = ('a', 'b', 'foo', 'bar') def __init__(self): self.foo = 10 # def __del__(self): # print(f'{self} is deleted') def __str__(self): return f'{self.foo}' class NotSlotsClass(SlotsClass): def __init__(self): super().__init__() self.a = 1234 obj = SlotsClass() obj.foo = 5 print(obj.foo) obj.foo = 101 print(obj.foo) obj2 = NotSlotsClass() obj2.c = 3 print(obj2.c, obj2.foo, obj2.a) # print(obj.__dict__) print(obj.__slots__) print(obj2.__dict__) print(NotSlotsClass.__dict__) <file_sep>import math class SqFigures: def __init__(self): pass def triangle_sq(self, a, b, c): # S = (p(p-a)(p-b)(p-c))**0.5 # где p - полупериметр p = (a + b + c)/2 s = math.sqrt(p*((p - a)*(p - b)*(p - c))) return s def circle_sq(self, r): s = math.pi * r**2 return s def square_sq(self, a, b): s = a*b return s if __name__ == '__main__': s = SqFigures() print(s.circle_sq(2)) print(s.square_sq(2,8)) print(s.triangle_sq(4.5,2.8,6.1))<file_sep># get, set, delete # bad example ''' class Order: # __slots__ = ('name', 'price','quantity') def __init__(self, name, price, quantity): self.name = name self.price = price self.quantity = quantity def sum(self): return self.price * self.quantity ''' # better ''' class Order: def __init__(self, name, price, quantity): self.name = name self._price = price self.__quantity = quantity @property def price(self): return self._price @price.setter def price(self, value): if value<0: raise ValueError('Цена не должна быть отрицательной!') @property def quanitity(self): return self.__quantity @quanitity.setter def quantity(self, value): if value<0: raise ValueError('Количество не может быть отрицательным') def sum(self): return self._price * self.__quantity ''' # the best # Использование дескриптора # класс дексриптора class NonNegative: def __init__(self, value=0): self._value = 0 # Метод __get__ срабатывает по запросу данного атрибута def __get__(self, instance, owner): return self._value # Метод __set__ отвечает за настройку (как @property) def __set__(self, instance, value): if value < 0: raise ValueError('Отрицательное число! Ошибка') self._value = value # Класс class Order: # Определяем правило доступа к атрибутам price = NonNegative() quantity = NonNegative() def __init__(self, name, price, quantity): self.name = name self.price = price self.quantity = quantity def sum(self): return self.price * self.quantity if __name__ == '__main__': apple_order = Order('apple', 90, 2) print(apple_order.sum()) apple_order.price = -100 print(apple_order.sum()) <file_sep>a = 12 def test_func( c, d,b=3): global a a = 1 return a + b + c + d print(test_func(1,1)) print(a)<file_sep>import sys from pympler import asizeof from pympler import muppy, summary all_objects_1 = muppy.get_objects() # Shallow size (например, размер листа, но не объектов, которые в нем есть) print(sys.getsizeof(1)) # 28 print(sys.getsizeof(54234.000342314000)) # 24 print(sys.getsizeof(None)) # 16 print(sys.getsizeof([])) # 72 print(sys.getsizeof([1,2,3,4, ['s','l', ['a',1]]])) # 112 print(sys.getsizeof({})) # 248 print(sys.getsizeof(tuple())) # 56 print() # Deep size (идет по иерархии объектов вглубь, суммирует) print(asizeof.asizeof(1)) # 32 print(asizeof.asizeof(54234.000342314000)) # 24 print(asizeof.asizeof(None)) # 16 print(asizeof.asizeof([])) # 72 print(asizeof.asizeof([1,2,3,4, ['s','l', ['a',1]]])) # 592 print(asizeof.asizeof([1,2,3,4, ['s','l', ['a',1, [None, 1, {'a': 1, 'b': 'a'}]]]])) # 1016 print(asizeof.asizeof({})) # 248 print(asizeof.asizeof(tuple())) # 56 print(asizeof.asizeof(set())) # 232 all_objects_2 = muppy.get_objects() sum_1 = summary.summarize(all_objects_1) sum_2 = summary.summarize(all_objects_2) summary.print_(summary.get_diff(sum_1, sum_2)) <file_sep># Найти корни квадратного уравнения # a*x^2 + b*x + c = 0 # D = b**2 - 4*a*c # D>0 - два корня, D=0 - один корень, D<0 - нет корней # x_1, x_2 = (-b +- D ** 0.5)/2*a import math a = float(input('a = ')) b = float(input('b = ')) c = float(input('c = ')) D = b**2 - 4*a*c print(D) if D > 0: x_1 = (-b + math.sqrt(D))/(2*a) x_2 = (-b - math.sqrt(D))/(2*a) print(f'{x_1}, {x_2}') elif D == 0: x_1 = -b / (2 * a) print(f'{x_1}') else: print('Нет корней')<file_sep>def list_trick(a, list_test = []): list_test.append(a) return list_test def list_trick_2(a=[], list_test = []): list_test.append(a) return list_test if __name__ == '__main__': a = 1 func_result = list_trick(a) print(func_result) func_result_1 = list_trick(a) print(func_result_1) print(func_result is func_result_1) func_result = list_trick(a, [500,600,700]) print(func_result) func_result_1 = list_trick(a, [500,600,700]) print(func_result) print(func_result is func_result_1) a = [1,2,3] func_result = list_trick(a) print(func_result) func_result_1 = list_trick(a) print(func_result_1) print(func_result is func_result_1) func_result = list_trick(a, [500,600,700]) print(func_result) func_result_1 = list_trick(a, [500,600,700]) print(func_result) print(func_result is func_result_1)
1e01ac93207f052afcde8d20b32acd0cd1567530
[ "Python" ]
12
Python
tahoeivanova/excersices_and_memory_examples
e9e72ff0850dbd4e0877aca71698911f9d29681a
8d2820c927950e6d051bfaa57e72d77f6a2b1c53
refs/heads/master
<repo_name>richdy/react-slingshot-test<file_sep>/src/containers/RichTestPage.js import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; // import * as actions from '../actions/richTestActions'; import * as sagaActions from '../actions/richTestSagaActions'; import RichTestForm from '../components/RichTestForm'; export const RichTestPage = (props) => { return ( <RichTestForm richTest={props.richTest} generateNewAccountWithSagas={props.sagaActions.generateNewAccount} generateNewAddressWithSagas={props.sagaActions.generateNewAddress} /> ); }; RichTestPage.propTypes = { sagaActions: PropTypes.object.isRequired, richTest: PropTypes.object.isRequired }; function mapStateToProps(state) { return { richTest : state.richTest }; } function mapDispatchToProps(dispatch) { return { sagaActions: bindActionCreators(sagaActions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(RichTestPage); <file_sep>/src/containers/BitcoinJSHowToPage.js import React from 'react'; class BitcoinJSHowToPage extends React.Component { constructor(props, context) { super(props, context); } render() { return ( <div> <h1>BitcoinJS BIP44 HowTo</h1> <div><pre>{` testBitcoinJs(){ var _TestMnemonic = 'maple acquire need weather sleep patient domain oak dust real weird dizzy column any goose curious flee drink retire imitate antenna idea couple attitude'; var _TestSeed = bip39.mnemonicToSeed(_TestMnemonic); console.log(\`BIP39 Seed: $\{_TestSeed.toString('hex')}\`); var _TestHDNode = btc.HDNode.fromSeedBuffer(_TestSeed); console.log(\`BIP32 Root Key: $\{_TestHDNode.toBase58()}\`); var _AccountHDNode = _TestHDNode.deriveHardened(44).deriveHardened(0).deriveHardened(0); var Bip32ExtendedPrivate = _AccountHDNode.derive(0); console.log(\`Bip32 Extended Private Key: $\{Bip32ExtendedPrivate.toBase58()}\`); console.log(\`Bip32 Extended Public Key: $\{Bip32ExtendedPrivate.neutered().toBase58()}\`); console.log(\`Account extended private key: $\{_AccountHDNode.toBase58()}\`); var _AccountHDNodeXPub = _AccountHDNode.neutered(); console.log(\`Account extended public key: $\{_AccountHDNodeXPub.toBase58()}\`); for(var i = 0; i< 5; i++){ console.log(\`Address $\{i}: $\{_AccountHDNodeXPub.derive(0).derive(i).getAddress()}\`); } }`}</pre><pre style={{backgroundColor: "black", color: "chartreuse"}}> {` BIP39 Seed: 2f1c2aa72b5eb37192223da088f0f9a4eb692a7472cad320587e3e38fd7aa4b8235d87c6dbd97ae5c60187eccdb217ade2ee5996b39cef8a7c0a680877bb22b2 BIP32 Root Key: <KEY> Bip32 Extended Private Key: <KEY> Bip32 Extended Public Key: <KEY> Account extended private key: <KEY> Account extended public key: <KEY> Address 0: 1HGArs3D1wnf3p56WquroaA5stJ1Ne44LV Address 1: 12hSgVVVz7CAmQwZG6oKNydLqMeGbThhdu Address 2: 1E19tfgu6rGP7QPHZRhSohntbmo8r42kgA Address 3: 1NwDGRwiRbDcwk9FgUxvdxBovJvqt47pc5 Address 4: 1Fd1jxfprJuww6ZEfXY9RH1LaqVJxcWoSB`} </pre></div> {/*{getCodeString()}*/} </div> ); } } export default BitcoinJSHowToPage; <file_sep>/src/reducers/initialState.js export default { fuelSavings: { newMpg: '', tradeMpg: '', newPpg: '', tradePpg: '', milesDriven: '', milesDrivenTimeframe: 'week', displayResults: false, dateModified: null, necessaryDataIsProvidedToCalculateSavings: false, savings: { monthly: 0, annual: 0, threeYear: 0 } }, richTest: { mnemonic: '', xpub: '', internalAddresses: [], externalAddresses: [] } }; <file_sep>/src/sagas/sagas.js import * as btcApi from '../api/btcApi'; import * as types from '../actions/actionTypes'; import { take, call, put } from 'redux-saga/effects'; /* eslint-disable */ export function* helloSaga() { console.log('Hello Sagas!'); } export function* generateBtcAccount() { while(true) { yield take(types.SAGA_GENERATE_BTC_ACCOUNT_BEGIN); let account = yield call(btcApi.generateBtcAccount); yield put({type: types.SAGA_GENERATE_BTC_ACCOUNT_SUCCESS, ...account}); for(let i = 0; i<3; i++){ let address = yield call(btcApi.getAddressAt, account.xpub, i, false); yield put({type: types.SAGA_GENERATE_BTC_ADDRESS_SUCCESS, address}) } } } export function* generateNewAddressWithCall() { while(true){ const action = yield take(types.SAGA_GENERATE_BTC_ADDRESS_BEGIN); const address = yield call(btcApi.getAddressAt, action.xpub, action.addressIndex); yield put({type: types.SAGA_GENERATE_BTC_ADDRESS_SUCCESS, address}) } } <file_sep>/src/reducers/index.js import { combineReducers } from 'redux'; import fuelSavings from './fuelSavingsReducer'; import richTest from './richTestReducer'; import { routerReducer } from 'react-router-redux'; const rootReducer = combineReducers({ fuelSavings, richTest, routing: routerReducer }); export default rootReducer; <file_sep>/src/containers/HomePage.js import React from 'react'; import { NavLink, Switch, Route } from 'react-router-dom'; import Bip44Demo from './RichTestPage'; import BitcoinJSHowToPage from './BitcoinJSHowToPage'; import FuelSavings from './FuelSavingsPage'; const HomePage = () => { return ( <div> <h1>HomePage</h1> <p>Just a sandbox for Rich</p> <p><div className="row"> <div className="col-md-3"><b><NavLink to="/bip44-demo">BIP44 Account Generator:</NavLink></b></div> <div className="col-md-9">Utilizes Redux Sagas with mocked async calls to generate BIP44 Bitcoin accounts and derive external addresses</div> </div> </p> <p><div className="row"> <div className="col-md-3"><b><NavLink exact to="bip44-howto">BIP 44 HowTo</NavLink></b></div> <div className="col-md-9">Just a simple code memo on BIP44</div> </div> </p> <p><div className="row"> <div className="col-md-3"><b><NavLink to="fuel-savings">Fuel Savings Calculator</NavLink></b></div> <div className="col-md-9">Cory House's original raw Redux demo</div> </div> </p> <Switch> <Route exact path="/bip44-demo" component={Bip44Demo} /> <Route exact path="/bip44-howto" component={BitcoinJSHowToPage} /> <Route exact path="/fuel-savings" component={FuelSavings} /> </Switch> </div> ); }; export default HomePage; <file_sep>/src/actions/richTestActions.js // import * as types from './actionTypes'; // import btc from 'bitcoinjs-lib'; // import bip39 from 'bip39'; // import { getFormattedDateTime } from '../utils/dateHelper'; // const numberOfAddressesToPopulate = 3; // example of a thunk using the redux-thunk middleware // function deriveAddressFromPath(root, addressType, addressIndex){ // const path = `m/44'/0'/0'/${addressType}/${addressIndex}`; // return root.derivePath(path).getAddress(); // } // // function deriveAddressFromPathAsync(root, addressType, addressIndex) { // return new Promise((resolve) => { // setTimeout( () => { // const path = `m/44'/0'/0'/${addressType}/${addressIndex}`; // resolve({ path, address: deriveAddressFromPath(root, addressType, addressIndex) }); // }, 50); // }); // } // // export function saveRichTest(settings) { // return function (dispatch) { // // thunks allow for pre-processing actions, calling apis, and dispatching multiple actions // // in this case at this point we could call a service that would persist the fuel savings // return dispatch({ // type: types.SAVE_RICH_TEST, // dateModified: getFormattedDateTime(), // settings // }); // }; // } // export function handleRichTestFormInputUpdate(richTestSettings, fieldName, value) { // return { // type: types.UPDATE_RICH_TEST_PROPS, // dateModified: getFormattedDateTime(), // richTestSettings, // fieldName, // value // }; // } // export function generateBtcAddress() { // return function(dispatch){ // const mnemonic = bip39.generateMnemonic(256); // const publicSeedRoot = btc.HDNode.fromSeedBuffer(bip39.mnemonicToSeed(mnemonic)); // const extendedPublicKey = publicSeedRoot.neutered().toBase58(); // const extendedPrivateKey = publicSeedRoot.toBase58(); // // let addressPromises = []; // // for (let addressIndex = 0; addressIndex < numberOfAddressesToPopulate; addressIndex++) { // addressPromises.push(deriveAddressFromPathAsync(publicSeedRoot, 0, addressIndex)); // } // Promise.all(addressPromises).then( (addresses) => { // dispatch( // { // type: types.GENERATE_BTC_ADDRESS_SUCCESS, // extendedPublicKey, // extendedPrivateKey, // addresses, // mnemonic // } // ); // }); // }; // } // // export function addNewAddress(mnemonic, index) { // return (dispatch) => { // deriveAddressFromPathAsync(btc.HDNode.fromSeedBuffer(bip39.mnemonicToSeed(mnemonic)), 0, index) // .then(result => { // dispatch( {type: types.ADD_NEW_ADDRESS_SUCCESS, address: result } ); // }); // }; // } <file_sep>/src/components/PathAndAddressTable.js import React, { PropTypes } from 'react'; import PathAndAddress from './RichTestBtcPathAndAddress'; const PathAndAddressTable = ({addresses}) => { return ( <table className="table"> <tbody> <tr> <th>Path</th> <th>Address</th> </tr> { addresses.map((pa, i) => { return <PathAndAddress key={i} path={pa.path} address={pa.address}/>; }) } </tbody> </table> ); }; PathAndAddressTable.propTypes = { addresses: PropTypes.array.isRequired //addresses: arrayOf(pathAndAddressItem).required //addresses: PropTypes.array.required }; export default PathAndAddressTable;
7572c9b6d87ede7edfa19b97804eeb6767421ae6
[ "JavaScript" ]
8
JavaScript
richdy/react-slingshot-test
92657d88ceb55613d0f8644fcbcac92b62eae0b0
e2c14d7b7c4004dce9fc8208b9fb65ba3284bd26
refs/heads/master
<file_sep>use_frameworks! pod "SwiftyJSON", ">= 2.2" pod 'Alamofire', '~> 1.2' <file_sep>// // SongListTable.swift // // // Created by <NAME> on 25.05.15. // // import UIKit import SwiftyJSON import Alamofire import CoreData class SongListTable: UITableViewController, NSFetchedResultsControllerDelegate { //MARK: Properties private var fetchController:NSFetchedResultsController! private var managedContext:NSManagedObjectContext? //MARK: TableViewController methods override func viewDidLoad() { super.viewDidLoad() self.managedContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let fetch = NSFetchRequest(entityName: "SongList") let sortDesc = NSSortDescriptor(key: "id", ascending: true) fetch.sortDescriptors = [sortDesc] self.fetchController = NSFetchedResultsController(fetchRequest: fetch, managedObjectContext: self.managedContext!, sectionNameKeyPath: nil, cacheName: nil) self.fetchController.delegate = self self.fetchController?.performFetch(nil) var refresh:UIRefreshControl! = UIRefreshControl() refresh.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) refreshControl = refresh downloadList() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.fetchController.sections![section].numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("songCell") as! UITableViewCell let song: AnyObject = self.fetchController.objectAtIndexPath(indexPath) cell.textLabel?.text = song.valueForKey("label") as? String cell.detailTextLabel?.text = song.valueForKey("author") as? String return cell } //MARK: Update data methods func refresh(sender:AnyObject) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { self.downloadList() dispatch_async(dispatch_get_main_queue()) { self.refreshControl!.endRefreshing() } } } func downloadList() { Alamofire.request(.GET, "http://kilograpp.com:8080/songs/api/songs").responseJSON{ _, _, json, error in if (error != nil) { println("ERROR : \(error)") } else { var jsonArray = JSON(json!).array! let count = self.fetchController.sections![0].numberOfObjects //если Core Data пустая, то if count == 0 { for jsonItem in jsonArray { self.addList(jsonItem) } } else { // иначе перебираем каждый элемент CoreData for i in 0..<count { let indexPath = NSIndexPath(forRow: i, inSection: 0) var coreObject: AnyObject = self.fetchController.objectAtIndexPath(indexPath) //получаем индексы существующих, а также новых, объектов, и ... let existsItems = self.changeList(coreObject as! NSManagedObject, jsonArray: jsonArray) //...удаляем их из массива JSON, чтобы дальнейший перебор был короче for index in existsItems { jsonArray.removeAtIndex(index) } } } if (self.managedContext!.hasChanges && !self.managedContext!.save(nil)) { println("Unrosolve error") abort() } } } } //MARK: Work with indexes func changeList(item: NSManagedObject, jsonArray:[JSON]) -> [Int] { var existsItems:[Int] = [] //флаг существования объекта в CoreData var isExist = false let count = self.fetchController.sections![0].numberOfObjects let lastObject: AnyObject = self.fetchController.objectAtIndexPath(NSIndexPath(forRow: count - 1, inSection: 0)) //получаем индекс последнего элемента CoreData, тк все объекты отсортированы, то новые объекты имеют индекс выше последнего let lastIndex = lastObject.valueForKey("id")!.integerValue for index in 0..<jsonArray.count { let jsonIndex = jsonArray[index]["id"].int //если объект существует, то флаг выставляется на true и добавляется в массив чисел для удаления из json if (jsonIndex <= lastIndex) && (item.valueForKey("id")?.integerValue == jsonIndex) { isExist = true existsItems += [index] continue } //тк объект новый, то сохраняется в CoreData else if jsonIndex > lastIndex { var jsonItem = jsonArray[index] self.addList(jsonItem) //аналогично добавляем в массив existsItems += [index] } } //тк объект уже не существует в сети, то его удаляем if (!isExist) { self.managedContext?.deleteObject(item) } return existsItems.sorted({ (firstNum:Int, secondNum:Int) -> Bool in return firstNum > secondNum }) } //добавить в Core Data func addList(jsonItem:JSON) { var dataSong:NSManagedObject! = NSEntityDescription.insertNewObjectForEntityForName("SongList", inManagedObjectContext: self.managedContext!) as! NSManagedObject dataSong.setValue(jsonItem["id"].int, forKey: "id") dataSong.setValue(jsonItem["author"].stringValue, forKey: "author") dataSong.setValue(jsonItem["label"].stringValue, forKey: "label") } //MARK: NSFetchedResultControllerDelegate func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade) case .Delete: self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) default: break } } }
d0cda70597af1c73110a68420a6af006499fc1d9
[ "Swift", "Ruby" ]
2
Ruby
Ar4eBaT/TestKillograpp
bc5deffc312cc73dbf1a0a1ef717ddb88e37aa52
f71e18d1f611cb49e2e246a68e72018852a81bda
refs/heads/master
<repo_name>kumochan/laravel-bc-php-wbdl<file_sep>/laravel-repository/app/Http/Controllers/Backend/CategoryController.php <?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use App\Http\Requests\CategoryRequest; use App\Models\Category; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Session; /** * @property mixed post */ class CategoryController extends Controller { public function index() { //$categories = DB::table('categories')->orderByDesc('id')->get(); $categories = Category::orderByDesc('id')->paginate(5); return view('backend.category.index', compact('categories')); } /* * Edit category */ public function showEdit($id) { $category = DB::table('categories')->find($id); return view('backend.category.edit',compact('category')); } public function edit(Request $request,$id) { $category = Category::find($id); $category->name = $request->name; $category->category_slug = $request->category_slug; $category->save(); return redirect()->route('category.show-index'); } /* * Create category */ public function showCreate() { return view('backend.category.create'); } public function create(CategoryRequest $request) { // $this->validate($request, [ // 'name' => 'required|unique:categories|max:255', // 'category_slug' => 'required', // ]); $category = new Category(); $category->name = $request->name; $category->category_slug = $request->category_slug; $category->save(); Session::flash('success', 'Add category success!'); return redirect()->route('category.show-index'); } } <file_sep>/lession-12-authorization/README.md ## About Laravel composer require laravel/ui php artisan ui:auth php artisan migrate php artisan route:list<file_sep>/laravel-repository/routes/web.php <?php use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); })->name('welcome'); Route::prefix('users')->group(function (){ Route::get('/', 'UserController@showUsers')->name('get.users')->middleware('check.user'); Route::get('{id}', 'UserController@showUserId')->name('show.user'); Route::post('/delete/{id}', 'UserController@delete')->name('delete.user'); Route::get('/update/{id}', 'UserController@showUpdate')->name('show-update.user'); Route::post('/update/{id}', 'UserController@update')->name('update.user'); }); // lession-05 Route::get('component', 'ComponentController@index')->name('component.example'); Route::get('viewtemplate', 'ComponentController@viewtemplate')->name('component.viewtemplate'); Route::get('createtemplate','ComponentController@createtemplate')->name('component.create'); Route::get('testshow','ComponentController@testshow')->name('testshow'); /* ** lession 11: locale */ Route::group(['middleware' => 'locale'], function () { Route::get('change-language/{language}', 'Controller@changeLanguage')->name('change-language'); /* * * categories */ Route::prefix('backend/category')->group(function (){ Route::get('/','Backend\CategoryController@index')->name('category.show-index')->middleware('check.user'); Route::get('/edit/{id}','Backend\CategoryController@showEdit')->name('category.show-edit'); Route::post('edit/{id}','Backend\CategoryController@edit')->name('category.edit'); Route::get('/create','Backend\CategoryController@showCreate')->name('category.show-create'); Route::post('/create','Backend\CategoryController@create')->name('category.create'); }); /* * * Post */ Route::prefix('backend/post/{cate_id}')->group(function(){ Route::get('/','Backend\PostController@showByCategory')->name('post.show-index'); }); }); /* * lession-08 */ Route::get('backend/login', 'LoginController@showLogin')->name('show.login'); Route::post('backend/login', 'LoginController@login')->name('user.login'); // lession-12 Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::get('/page-guest', 'HomeController@showPageGuest'); Route::get('/page-admin', 'HomeController@showPageAdmin'); <file_sep>/laravel-repository/app/Http/Controllers/ComponentController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ComponentController extends Controller { // public function index() { return view('component.index'); } public function viewtemplate() { return view('index'); } public function createtemplate() { return view('create'); } public function testshow() { return view('extend-showlayout'); } } <file_sep>/README.md # laravel-bc-php-wbdl<file_sep>/laravel-repository/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use App\Models\User; //use App\Services\UserService; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class UserController extends Controller { // public $userService; // // // public function __construct(UserService $user_service) // { // $this->userService = $user_service; // } // // // public function showUpdate($id = 0) // { // $user = DB::table('users')->find($id); // return view('user.update', compact('user')); // } // // // demo lession 03 // public function update(Request $request) // { // $user = new User(); // $user->name = $request->name; // $id = $request->id; // // $this->userService->update($user, $id); // // $users = DB::table('users')->get(); // return view('user.index', compact('users')); // } // // // // Demo lession-02 // function showUsers() // { // $users = DB::table('users')->get(); // return view('user.index', compact('users')); // } // // function showUserId($id = 0) // { // $user = DB::table('users')->find($id); // return view('user.details', compact('user')); // } // // function delete($id) // { // DB::table('users')->where('id','=',$id)->delete(); // return redirect()->route('get.users'); // } } <file_sep>/laravel-repository/app/Http/Controllers/Backend/PostController.php <?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use App\Models\Post; use http\Exception; use Illuminate\Http\Request; class PostController extends Controller { public function index(){ } public function showByCategory($cate_id){ try { $posts = Post::where('category_id','=',$cate_id)->get(); //$category_id = $posts->id; return view('backend.post.index', compact('posts')); } catch (\Exception $ex) { $error_message = $ex->getMessage(); return view('welcome', compact('error_message')); } } } <file_sep>/laravel-repository/README.md Thực hành xây dựng ứng dụng Laravel có sử dụng Repository Design pattern tại Codegym ## lession-12: authenticate composer require laravel/ui php artisan ui:auth php artisan migrate php artisan route:list
662b8d1a6d2b9d5891e7a6d7b670367447bec53d
[ "Markdown", "PHP" ]
8
PHP
kumochan/laravel-bc-php-wbdl
a923ecac2b615d91daf1b109983cc455ad3424d4
7579af1ff8e86f47c9c3d9c0e8e9fac642274e73
refs/heads/master
<repo_name>pbblreact/ezbuy.github.io<file_sep>/js/components/app.jsx import React from 'react'; import { Link } from 'react-router'; import SearchByUrl from './search_by_url'; import Results from './results'; const App = ({ children }) => ( <div> <header> </header> <main> <div className="container"> <div className="row"> <div className="col-md-6"> <SearchByUrl /> </div> <div className="col-md-6"> <Results /> </div> {children} </div> </div> </main> </div> ); export default App; <file_sep>/js/components/search_by_url.jsx import React from 'react'; import { Link, hashHistory, withRouter } from 'react-router'; import { connect } from 'react-redux'; import { getLabels, clearError } from '../actions/item_actions'; class SearchByUrl extends React.Component { constructor(props){ super(props) this.state={ picture_url: "" } this.handleSubmit = this.handleSubmit.bind(this); } update(field) { return (e) => this.setState({[field]: e.target.value}) } handleSubmit(e) { e.preventDefault(); this.props.clearError(); this.props.getLabels(this.state.picture_url); } render () { return ( <div className="container left"> <div className="prompt">Please enter the url of an image:</div> <div> <input type="text" required onChange={this.update('picture_url')} /> </div> <div className="btn btn-primary btn-block submit-btn" onClick={this.handleSubmit}>Submit</div> <div className="row search-image"> {this.state.picture_url === "" ? "" : <img src={this.state.picture_url} />} {this.props.loading ? <div className="loader image-loader"></div> : ""} </div> </div> ); } } const mapStateToProps = (state) => ({ loading: state.loading.loadingImage }); const mapDispatchToProps = dispatch => ({ getLabels: (picture_url) => dispatch(getLabels(picture_url)), clearError: () => dispatch(clearError()) }); export default connect( mapStateToProps, mapDispatchToProps )(SearchByUrl); <file_sep>/js/components/ebay_items_container.js import React from 'react'; import { connect } from 'react-redux'; import EbayItems from './ebay_items'; import {getEbayItems} from '../actions/item_actions'; const mapStateToProps = state => { let ebayUrl; let totalResults; let items; if (jQuery.isEmptyObject(state.items.ebayItems)) { ebayUrl = ""; totalResults = 0; items = []; } else { ebayUrl = state.items.ebayItems.itemSearchURL[0]; totalResults = parseInt(state.items.ebayItems.paginationOutput[0].totalEntries[0]); items = state.items.ebayItems.searchResult[0].item; } return { loading: state.loading.loadingEbay, ebayUrl, totalResults, items, keywords: state.items.labels[0].description + (state.items.labels[1] ? " "+state.items.labels[1].description : "") } }; const mapDispatchToProps = dispatch => ({ getEbayItems: (keywords) => dispatch(getEbayItems(keywords)) }); export default connect( mapStateToProps, mapDispatchToProps )(EbayItems); <file_sep>/js/components/labels_container.js import React from 'react'; import { connect } from 'react-redux'; import Labels from './labels'; const mapStateToProps = state => { return { loading: state.loading.loadingImage, labels: state.items.labels } }; export default connect( mapStateToProps, null )(Labels); <file_sep>/js/components/youtube_items.jsx import React from 'react'; class YoutubeItems extends React.Component { constructor(props){ super(props); } componentDidMount(){ this.props.getYoutubeItems(this.props.keywords); } componentDidUpdate(prevProps, prevState){ if (prevProps.keywords !== this.props.keywords) { this.props.getYoutubeItems(this.props.keywords); } } render () { if (this.props.loading) { return <div className="loader">Loading...</div> } if (this.props.totalResults === 0) { return <div>Sorry! No results found.</div>; } return( <div className="ebay-items"> <div className="total-results"> <span>Results found: {this.props.totalResults}</span> <a className="btn btn-danger btn-sm" target="_blank" href={"https://www.youtube.com/results?search_query=" + this.props.keywords}>Browse {this.props.keywords} on Youtube</a> </div> <div className="card-columns"> {this.props.items.map((item, idx)=>{ let title = item.snippet.title.length > 20 ? item.snippet.title.slice(0, 20) + "..." : item.snippet.title; return <div className="card" key={idx}> <img className="card-img-top" src={item.snippet.thumbnails.default.url} /> <div className="card-block"> <div className="card-title">{title}</div> <div className="item-location"><span>Channel: </span>{item.snippet.channelTitle}</div> <a className="btn btn-danger btn-block view-on-ebay" target="_blank" href={"https://www.youtube.com/watch?v=" + item.id.videoId}>View</a> </div> </div> })} </div> </div> ); } } export default YoutubeItems; <file_sep>/js/components/youtube_container.js import React from 'react'; import { connect } from 'react-redux'; import YoutubeItems from './youtube_items'; import {getYoutubeItems} from '../actions/item_actions'; const mapStateToProps = state => { let items; let totalResults; if (jQuery.isEmptyObject(state.items.youtubeItems)) { items = []; } else { items = state.items.youtubeItems.items; totalResults = state.items.youtubeItems.pageInfo.totalResults; } return { loading: state.loading.loadingYoutube, items, totalResults, keywords: state.items.labels[0].description + (state.items.labels[1] ? " "+state.items.labels[1].description : "") } }; const mapDispatchToProps = dispatch => ({ getYoutubeItems: (keywords) => dispatch(getYoutubeItems(keywords)) }); export default connect( mapStateToProps, mapDispatchToProps )(YoutubeItems); <file_sep>/js/components/ebay_items.jsx import React from 'react'; class EbayItems extends React.Component { constructor(props){ super(props); } componentDidMount(){ this.props.getEbayItems(this.props.keywords); } componentDidUpdate(prevProps, prevState){ if (prevProps.keywords !== this.props.keywords) { this.props.getEbayItems(this.props.keywords); } } render () { if (this.props.loading) { return <div className="loader">Loading...</div> } if (this.props.totalResults === 0) { return <div>Sorry! No results found.</div>; } return( <div className="ebay-items"> <div className="total-results"> <span>Results found: {this.props.totalResults}</span> <a className="btn btn-primary btn-sm" target="_blank" href={this.props.ebayUrl}>Browse {this.props.keywords} on Ebay</a> </div> <div className="card-columns"> {this.props.items.map((item, idx)=>{ let title = item.title[0].length > 20 ? item.title[0].slice(0, 20) + "..." : item.title[0]; let condition = item.condition ? item.condition[0].conditionDisplayName[0] : "Unknown"; return <div className="card" key={idx}> <img className="card-img-top" src={item.galleryURL[0]} /> <div className="card-block"> <div className="card-title">{title}</div> <div className="item-location"><span>Location: </span>{item.location[0]}</div> <div className="item-condition"><span>Condition: </span>{condition}</div> <a className="btn btn-primary btn-block view-on-ebay" target="_blank" href={item.viewItemURL[0]}>View</a> </div> </div> })} </div> </div> ); } } export default EbayItems; <file_sep>/README.md # EaziBuy ![screen-shot] Utilizing machine learning API to recognize image and connect to popular third party services. [SEE IT IN ACTION LIVE HERE!][eazibuy] #### Libraries This project uses: - [React.js][React] - [Redux][Redux] [React]:https://facebook.github.io/react/ [Redux]:http://redux.js.org/ [eazibuy]:https://lijiahao008.github.io/EaziBuy [screen-shot]: ./images/screen-shot.png <file_sep>/js/components/labels.jsx import React from 'react'; import { Line, Circle } from 'rc-progress'; import LabelItem from './label_item'; const Labels = ({ labels, loading }) => { if (loading) { return <div className="loader">Loading...</div> } return( <div className="labels"> {labels.map((label, idx)=>(<div className="label-item" key={idx}><LabelItem label={label} /></div>))} </div> ); }; export default Labels; <file_sep>/js/reducers/root_reducer.js import {combineReducers} from 'redux'; import ItemsReducer from './items_reducer'; import LoadingReducer from './loading_reducer'; const RootReducer = combineReducers({ items: ItemsReducer, loading: LoadingReducer }); export default RootReducer; <file_sep>/js/actions/item_actions.js import * as APIUtil from '../util/item_api_util' export const RECEIVE_EBAY_ITEMS = "RECEIVE_EBAY_ITEMS"; export const RECEIVE_YOUTUBE_ITEMS = "RECEIVE_YOUTUBE_ITEMS"; export const RECEIVE_AMAZON_ITEMS = "RECEIVE_AMAZON_ITEMS"; export const RECEIVE_IMAGE_LABELS = "RECEIVE_IMAGE_LABELS"; export const RECEIVE_IMAGE_ERROR = "RECEIVE_IMAGE_ERROR"; export const START_LOADING_EBAY = "START_LOADING_EBAY"; export const START_LOADING_IMAGE = "START_LOADING_IMAGE"; export const START_LOADING_YOUTUBE = "START_LOADING_YOUTUBE"; export const receiveEbayItems = items => ({ type: RECEIVE_EBAY_ITEMS, items }); export const receiveYoutubeItems = items => ({ type: RECEIVE_YOUTUBE_ITEMS, items }); export const receiveAmazonItems = items => ({ type: RECEIVE_AMAZON_ITEMS, items }); export const receiveImageLabels = labels => ({ type: RECEIVE_IMAGE_LABELS, labels }); export const receiveImageError = error => ({ type: RECEIVE_IMAGE_ERROR, error }); export const startLoadingEbay = () => ({ type: START_LOADING_EBAY }); export const startLoadingYoutube = () => ({ type: START_LOADING_YOUTUBE }); export const startLoadingImage = () => ({ type: START_LOADING_IMAGE }); export const getLabels = (picture_url) => dispatch => { dispatch(startLoadingImage()); return APIUtil.fetchLabel(picture_url).then((res) => { if (res.responses[0].labelAnnotations) { return dispatch(receiveImageLabels(res.responses[0].labelAnnotations)) } else { let error = res.responses[0].error.message; return dispatch(receiveImageError(error)) } }) } export const getEbayItems = (keywords) => dispatch => { dispatch(startLoadingEbay()); return APIUtil.fetchEbayItems(keywords).then((items) => { return dispatch(receiveEbayItems(items)) }) } export const getYoutubeItems = (keywords) => dispatch => { dispatch(startLoadingYoutube()); return APIUtil.fetchYoutubeItems(keywords).then((items) => { return dispatch(receiveYoutubeItems(items)) }) } export const getAmazonItems = (keywords) => dispatch => { return APIUtil.fetchAmazonItems(keywords).then((items) => { return dispatch(receiveAmazonItems(items)) }) } export const clearError = () => dispatch => { return dispatch(receiveImageError("")); } <file_sep>/js/reducers/items_reducer.js import { RECEIVE_EBAY_ITEMS, RECEIVE_IMAGE_ERROR, RECEIVE_IMAGE_LABELS, RECEIVE_YOUTUBE_ITEMS, RECEIVE_AMAZON_ITEMS } from '../actions/item_actions'; import merge from 'lodash/merge'; const initialState ={ labels: {}, ebayItems: {}, youtubeItems: {}, error: "" } const ItemsReducer = (oldState = initialState, action) => { Object.freeze(oldState); let newState = merge({}, oldState); switch (action.type) { case RECEIVE_IMAGE_LABELS: newState.labels = action.labels; return Object.assign({}, newState); case RECEIVE_IMAGE_ERROR: newState.error = action.error; return Object.assign({}, newState); case RECEIVE_EBAY_ITEMS: newState.ebayItems = action.items.findItemsByKeywordsResponse[0]; return Object.assign({}, newState); case RECEIVE_AMAZON_ITEMS: debugger return Object.assign({}, newState); case RECEIVE_YOUTUBE_ITEMS: newState.youtubeItems = action.items; return Object.assign({}, newState); default: return oldState; } }; export default ItemsReducer; <file_sep>/js/components/label_item.jsx import React from 'react'; import 'rc-progress/assets/index.css'; import { Circle } from 'rc-progress'; class Labels extends React.Component { constructor(props){ super(props); this.state = { percent: 0 }; this.increase = this.increase.bind(this); } componentDidMount() { this.increase(); } increase() { const percent = this.state.percent + 1; if (percent >= this.props.label.score * 100) { clearTimeout(this.tm); return; } this.setState({ percent }); this.tm = setTimeout(this.increase, 10); } render () { return( <div> <div className="label-detail"> <div className="label-description">{this.props.label.description}</div> <div className="label-score">{(this.props.label.score * 100 + "").slice(0, 5) + "%"}</div> </div> <Circle strokeWidth="6" percent={this.state.percent} /> </div> ); } }; export default Labels; <file_sep>/js/components/results.jsx import React from 'react'; import LabelsContainer from './labels_container'; import EbayItemsContainer from './ebay_items_container'; import YoutubeItemsContainer from './youtube_container'; import AmazonItemsContainer from './amazon_container'; import { connect } from 'react-redux'; class Results extends React.Component { constructor(props){ super(props) this.state ={ labels: true, ebay: false, youtube: false } this.openTab = this.openTab.bind(this); } openTab(field){ this.setState({labels: false, ebay: false, youtube: false, amazon: false}); this.setState({[field]: true}); } render () { if (this.props.initialPage && this.props.error === "") { return <div className="initial-result">Select an image to show results.</div>; } if (this.props.error !== "") { return <div className="label-error-container"><div className="label-error">{this.props.error}</div></div> } let labelsTab = "tab-items", ebayTab = "tab-items", youtubeTab = "tab-items"; if (this.state.labels) { labelsTab += " selected"; } else if (this.state.ebay) { ebayTab += " selected"; } else if (this.state.youtube) { youtubeTab += " selected"; } return ( <div> <div className="tabs"> <div className={labelsTab} onClick={()=>this.openTab("labels")}>labels</div> <div className={ebayTab} onClick={()=>this.openTab("ebay")}>ebay</div> <div className={youtubeTab} onClick={()=>this.openTab("youtube")}>Youtube</div> </div> {this.state.labels ? <LabelsContainer /> : ""} {this.state.ebay ? <EbayItemsContainer /> : ""} {this.state.youtube ? <YoutubeItemsContainer /> : ""} </div> ); } } const mapStateToProps = (state) => ({ initialPage: jQuery.isEmptyObject(state.items.labels), error: state.items.error }); export default connect( mapStateToProps, null )(Results);
5f85cd027287c86b36b71720941c9504df8fdc76
[ "JavaScript", "Markdown" ]
14
JavaScript
pbblreact/ezbuy.github.io
06413a0ab0ee3144a4d63b0954eaa2a193e2aeb5
56abb8289521b9127408d1d10c9586818a1fd639
refs/heads/main
<repo_name>kevinmichaelchen/next-chakra-starter<file_sep>/pages/index.js import Layout from "../src/components/Layout"; import Home from "../src/pages/Home"; export default function HomePage({ ...props }) { return ( <Layout {...props}> <Home /> </Layout> ); } // re-export the reusable `getServerSideProps` function export { getServerSideProps } from "../src/Chakra";
592cd3e932ad4fdfcb809343c40bad2c6baa589d
[ "JavaScript" ]
1
JavaScript
kevinmichaelchen/next-chakra-starter
7f8374ccc71a61f46f1f7bea3ec3ef820fb0b300
eb1fcac4dc37c2c31488575c6403c30b2d514220
refs/heads/master
<repo_name>xuanthu01/MoneyMon<file_sep>/frontend/src/actions/index.js export * from './auth.action'; export * from './registration.action'; export * from './alert.action'; export * from './transaction.action';<file_sep>/frontend/src/components/shared/GoogleLogin.jsx import React from 'react'; import GoogleLogin from 'react-google-login'; export default function GoogleLoginComponent(props) { return ( <GoogleLogin {...props} clientId="474894401938-hib8j06eov4t7fu3mpt9a7cc6if0bf8h.apps.googleusercontent.com" cookiePolicy={'single_host_origin'} /> ) }<file_sep>/frontend/src/actions/registration.action.js import * as types from '../constants/ActionsTypes'; import * as httpService from '../api'; import { success, error } from './alert.action'; const requestRegisterStart = () => ({ type: types.REGISTER_START }); const requestRegisterSuccess = user => ({ type: types.REGISTER_SUCCESS, payload: user }); const requestRegisterFailure = () => ({ type: types.REGISTER_FAILURE }); export const registerUser = registrationData => async (dispatch) => { dispatch(requestRegisterStart()); try { const user = await httpService.requestRegistration(registrationData); console.log("user", user); if (user) { dispatch(success(`Register completed with username: ${user.username}`)); dispatch(requestRegisterSuccess(user)); } } catch (err) { dispatch(error(err.detail||JSON.stringify(err))); dispatch(requestRegisterFailure()); } }<file_sep>/frontend/src/pages/Dashboard/index.jsx import React from 'react'; import { Row } from 'antd'; import PieChart from '../../components/Chart/Pie'; import BarChart from '../../components/Chart/Bar'; const Dashboard = props => { return ( <div> <Row justify="start" align='top' style={{ height: 'calc(100vh - 146.1px)' }}> <PieChart/> <BarChart/> </Row> </div> ) } export default Dashboard<file_sep>/frontend/src/components/Register/index.js import React from 'react'; import RegistrationForm from './RegistrationForm'; import { Row, Divider, Spin } from 'antd'; import { useSelector } from 'react-redux'; import { Redirect } from 'react-router'; import { enquireScreen } from 'enquire-js'; const rowStyle = { height: '100vh', backgroundImage: 'url("https://zos.alipayobjects.com/rmsportal/gGlUMYGEIvjDOOw.jpg")', backgroundSize: 'cover', backgroundAttachment: 'fixed', backgroundPosition: 'center' } let isMobile; enquireScreen((b) => { isMobile = b; }); const divStyle = { width: isMobile ? '95%' : '30%', padding: '40px', position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', background: 'none', textAlign: 'center', borderRadius: '20px', border: '1.5px solid #4caf50', overflow: 'hidden' } export default function Register(props) { const registrationData = useSelector(state => state.registrationReducer); if (registrationData.user) return <Redirect to="/login"></Redirect> return ( <Row justify="center" align='middle' style={rowStyle}> <div style={divStyle}> <Spin spinning={registrationData.registering} tip="Registering..."> <Divider orientation="center" style={{ color: 'white' }}>Welcome to MoneyMon!</Divider> <hr /> <RegistrationForm {...props} /> </Spin> </div> </Row> ) }<file_sep>/backend/moneymon/Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] djangorestframework-simplejwt = "*" djoser = "*" djangorestframework = "*" djongo = "*" psycopg2 = "*" django = "*" django-cors-headers = "*" django-sslserver = "*" django-money = "*" social-auth-app-django = "*" django-rest-framework-social-oauth2 = "*" drf-renderer-xlsx = "*" django-environ = "*" django-seed = "*" django-data-seeder = "*" [requires] python_version = "3.8" <file_sep>/backend/moneymon/wallet/migrations/0002_auto_20200506_1025.py # Generated by Django 3.0.4 on 2020-05-06 03:25 from django.db import migrations import djmoney.models.fields class Migration(migrations.Migration): dependencies = [ ('wallet', '0001_initial'), ] operations = [ migrations.RenameField( model_name='wallet', old_name='init_balance_currency', new_name='balance_currency', ), migrations.RemoveField( model_name='wallet', name='currency', ), migrations.RemoveField( model_name='wallet', name='init_balance', ), migrations.AddField( model_name='wallet', name='balance', field=djmoney.models.fields.MoneyField(decimal_places=2, default_currency='VND', max_digits=10, null=True, verbose_name='balance'), ), ] <file_sep>/frontend/src/components/Login/index.js import React from 'react'; import LoginForm from './LoginForm'; import { Row, Divider, Spin, Alert } from 'antd'; import { withGetScreen } from 'react-getscreen'; import { useSelector } from 'react-redux'; import { enquireScreen } from 'enquire-js'; const rowStyle = { height: '100vh', backgroundImage: 'url("https://zos.alipayobjects.com/rmsportal/gGlUMYGEIvjDOOw.jpg")', backgroundSize: 'cover', backgroundAttachment: 'fixed', backgroundPosition: 'center', overflow: 'hidden' } let isMobile; enquireScreen((b) => { isMobile = b; }); const divStyle = { width: isMobile ? '95%' : '30%', padding: '40px', position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', background: 'none', textAlign: 'center', borderRadius: '20px', border: '1.5px solid #4caf50', overflow: 'hidden' } const Login = props => { const authData = useSelector(state => state.authReducer); return ( <Row justify="center" align='middle' style={rowStyle}> <div style={divStyle}> <Spin spinning={authData.loading} tip="Loading..."> <Divider orientation="center" style={{ color: 'white' }}>Welcome to MoneyMon!</Divider> <hr /> <LoginForm {...props} /> </Spin> </div> </Row> ) } export default withGetScreen(Login);<file_sep>/backend/moneymon/wallet/migrations/0009_auto_20200506_1550.py # Generated by Django 3.0.4 on 2020-05-06 08:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wallet', '0008_auto_20200506_1548'), ] operations = [ migrations.RemoveField( model_name='categories', name='cat_types', ), migrations.AlterField( model_name='categories', name='cat_parent', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='children', to='wallet.Categories'), ), ] <file_sep>/frontend/src/components/Chart/Bar.js import React from 'react'; import 'antd/dist/antd.css'; import 'ant-design-pro/dist/ant-design-pro.css'; import { Card } from 'antd'; import { Bar } from 'ant-design-pro/lib/Charts'; const salesData = []; for (let i = 0; i < 12; i += 1) { salesData.push({ x: `T${i + 1}`, y: Math.floor(Math.random() * 1000000) + 200, }); } const BarChart = props => { return ( <Card.Grid style={{ width: "70%", height: "100%" }} > <Bar height={300} title="Chart test" data={salesData} /> </Card.Grid> ) } export default BarChart;<file_sep>/frontend/src/reducers/transaction.reducer.js import * as types from '../constants/ActionsTypes'; const initialState = { loading: false, transactions: [], error: null } const transactionsReducer = (state = initialState, action) => { switch (action.type) { case types.REQUEST_STARTED: return { ...state, loading: true }; case types.REQUEST_SUCCESS: return { ...state, loading: false, error: null, transactions: action.payload } case types.REQUEST_FAILURE: return { ...state, loading: false, transactions: [], error: action.payload } case types.ADD_TRANSACTION: const cloneState = { ...state } cloneState.transactions.push(action.payload); cloneState.loading = false; cloneState.error = null; return cloneState; default: return state; } } export default transactionsReducer;<file_sep>/frontend/src/components/Transaction/CreateTransactionModal.jsx import React, { useState, useEffect } from 'react'; import { Modal, Button, Input, Select } from 'antd'; import MoneyInput from './MoneyInput'; import { getAllCategories, getAllUserWallets } from '../../api'; const CreateTransactionModal = props => { const [categories, setCategories] = useState([]); const [wallet, setWallet] = useState([]); const [selectedCategory, setSelectedCategory] = useState(''); const [selectedWallet, setSelectedWallet] = useState(''); const [selectedAction, setSelectedAction] = useState(''); const [amount, setAmount] = useState(''); const [name, setName] = useState(''); useEffect(() => { const fetchCategories = async () => { const cats = await getAllCategories(); setCategories(cats); } const fetchWallets = async () => { const wallets = await getAllUserWallets(); setWallet(wallets); } fetchWallets(); fetchCategories(); }, []) return ( <Modal visible={props.visible} title="Create new transaction" onOk={() => props.handleOk({ category: selectedCategory, from_wallet: selectedWallet, action: selectedAction, amount, name })} onCancel={() => props.handleCancel(false)} footer={[ <Button key="back" onClick={() => props.handleCancel(false)}> Cancel </Button>, <Button key="create" type="primary" loading={props.loading} onClick={() => props.handleOk({ category: selectedCategory, from_wallet: selectedWallet, action: selectedAction, amount, name })}> Create </Button>, ]} > <Input.Group > <Input addonBefore="Name" type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter transaction name" /> <Select placeholder="Transaction action" style={{ width: '100%' }} onChange={value => setSelectedAction(value)} > <Select.Option value="IN">Cộng vào tài khoản</Select.Option> <Select.Option value="OUT">Rút ra tài khoản</Select.Option> </Select> <MoneyInput addonBefore="Amount" value={amount} onChange={setAmount} /> <Select placeholder="Category" style={{ width: '100%' }} onChange={value => setSelectedCategory(value)} > {categories.length > 0 && categories.map(category => { return ( <Select.Option value={category.id} key={category.id} > {category.cat_name} </Select.Option> ) })} </Select> <Select placeholder="Wallet" style={{ width: '100%' }} onChange={value => setSelectedWallet(value)} > {wallet.length > 0 && wallet.map(w => { return ( <Select.Option value={w.id} key={w.id} > <div style={{float: 'left'}}> <div style={{color: '#000'}}>{w.wallet_name}</div> <div style={{fontSize: '14'}} >Balance: {w.balance} {w.balance_currency}</div> </div> </Select.Option> ) })} </Select> </Input.Group> </Modal>) } export default CreateTransactionModal;<file_sep>/backend/moneymon/requirements.txt asgiref==3.2.7 bson==0.5.8 certifi==2020.6.20 cffi==1.14.0 chardet==3.0.4 cryptography==2.9.2 dataclasses==0.6 defusedxml==0.6.0 Django==2.2.13 django-braces==1.14.0 django-cors-headers==3.4.0 django-environ==0.4.5 django-money==1.1 django-oauth-toolkit==1.3.2 django-rest-framework-social-oauth2==1.1.0 django-sslserver==0.22 django-templated-mail==1.1.1 djangorestframework==3.11.0 djangorestframework-simplejwt==4.4.0 djongo==1.3.2 djoser==2.0.3 drf-renderer-xlsx==0.3.7 ecdsa==0.15 et-xmlfile==1.0.1 fido2==0.7.2 idna==2.9 jdcal==1.4.1 jsonfield==3.1.0 jsonLookup==0.7.5 oauthlib==3.1.0 openpyxl==3.0.3 psycopg2==2.8.5 py-moneyed==0.8.0 pyasn1==0.4.8 pycparser==2.20 PyJWT==1.7.1 pymongo==3.10.1 pyotp==2.3.0 python-dateutil==2.8.1 python-jose==3.1.0 python-u2flib-server==5.0.0 python3-openid==3.1.0 pytz==2020.1 requests==2.24.0 requests-oauthlib==1.3.0 rsa==4.0 simplejson==3.17.0 six==1.15.0 social-auth-app-django==4.0.0 social-auth-core==3.3.3 sqlparse==0.2.4 ua-parser==0.10.0 urllib3==1.25.9 user-agents==2.1 <file_sep>/backend/moneymon/wallet/views.py from rest_framework.generics import ( ListCreateAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView) from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets, status from rest_framework.response import Response from .models import Wallet, Categories from .permissions import IsOwnerWalletOrReadOnly from .serializers import WalletSerializer, CategoriesSerializer class WalletCreateView(viewsets.ModelViewSet): serializer_class = WalletSerializer permission_classes = [IsAuthenticated, IsOwnerWalletOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) def get_queryset(self): qs = Wallet.objects.filter(user=self.request.user) return qs def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_200_OK) def perform_destroy(self, instance): instance.delete() class CategoryView(viewsets.ModelViewSet): serializer_class = CategoriesSerializer def get_queryset(self): qs = Categories.objects.all() return qs <file_sep>/backend/moneymon/wallet/migrations/0006_categories_is_parent.py # Generated by Django 3.0.4 on 2020-05-06 08:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wallet', '0005_auto_20200506_1510'), ] operations = [ migrations.AddField( model_name='categories', name='is_parent', field=models.BooleanField(default=False), ), ] <file_sep>/frontend/src/components/Test/index.js import React, {Component} from 'react'; import 'antd/dist/antd.css'; import './index.css'; import { Card, Row } from 'antd'; class Tests extends Component { state = { key: 'app', }; onTabChange = (key, type) => { console.log(key, type); this.setState({ [type]: key }); }; render(){ const tabList = [ { key: '1', tab: '1', }, { key: '2', tab: '2', }, { key: '3', tab: '3', }, { key: '4', tab: '4', }, { key: '5', tab: '5', }, { key: '6', tab: '6', }, { key: '7', tab: '7', }, { key: '8', tab: '8', }, { key: '9', tab: '9', } ]; const contentList = { article: <p>article content</p>, app: <p>app content</p>, project: <p>project content</p>, }; return ( <Row justify="start" align='top' style={{ height: 'calc(100vh - 146.1px)' }}> <Card style={{ width: '100%' }} tabList={tabList} activeTabkey={this.state.key} onTabChange={key => { this.onTabChange(key, 'key'); }} > {contentList[this.state.key]} </Card> </Row> ); } } export default Tests;<file_sep>/frontend/src/pages/Transactions/index.jsx import React from 'react'; import Transactions from '../../components/Transaction'; import { Row } from 'antd'; const TransactionsPage = props => { return ( <Row justify="center" align='top' style={{ height: 'calc(100vh - 146.1px)' }}> <Transactions></Transactions> </Row> ) } export default TransactionsPage;<file_sep>/frontend/src/routes/index.js import React from "react"; import Home from "../pages/Home"; import { Switch } from "react-router"; import Login from "../components/Login"; import App from "../App"; import Register from "../components/Register"; import DashboardPage from "../pages/Dashboard"; import Transactions from "../components/Transaction"; import PublicRoute from "./PublicRoute"; import PrivateRoute from "./PrivateRoute"; import CategoryPage from "../pages/Categories"; import WalletPage from "../pages/Wallet"; import ReportPage from "../pages/Report"; import StatisticPage from "../pages/Statistic"; const routes = ( <Switch> <PublicRoute component={Home} path="/" exact /> <PublicRoute restricted={true} path="/login" component={Login} /> <PublicRoute path="/about" component={App} /> <PublicRoute restricted={true} path="/register" component={Register} /> <PrivateRoute path="/dashboard" component={DashboardPage} /> <PrivateRoute path="/transaction" component={Transactions} /> <PrivateRoute path="/category" component={CategoryPage} /> <PrivateRoute path="/wallet" component={WalletPage} /> <PrivateRoute path="/report" component={ReportPage} /> <PrivateRoute path="/statistic" component={StatisticPage} /> </Switch> ); export default routes; <file_sep>/frontend/src/containers/LoggedLayout.jsx import React, { useState } from 'react'; import { Layout, Menu } from 'antd'; import { HeartTwoTone, PieChartOutlined, ContainerOutlined, TransactionOutlined, BarChartOutlined, } from '@ant-design/icons'; import routes from '../routes'; import { Link, useHistory } from 'react-router-dom'; import { logout } from '../utils/auth.util'; const { SubMenu } = Menu; const { Header, Content, Footer, Sider } = Layout; const logoStyle = { display: 'flex', justifyContent: 'center', width: "148px", height: "60px", float: "left", cursor: 'pointer' } const LoggedLayout = props => { const [collapsed, setCollapsed] = useState(false); const onCollapse = collapsed => { setCollapsed(collapsed); }; const onLogout = () => { logout(); window.location.reload() } const history = useHistory(); return ( <Layout> <Header className="header"> <div className="logo" onClick={() => history.push('/dashboard')} style={logoStyle} > <img width="64px" height="64px" src="https://i.ibb.co/dfx6G33/logo.png" alt="img" /> </div> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']}> <Menu.Item key="1">My Account</Menu.Item> <Menu.Item key="2" onClick={() => history.push('/wallet')}>My Wallet</Menu.Item> <Menu.Item key="3" onClick={() => history.push('/category')}>Categories</Menu.Item> <Menu.Item key="4" onClick={() => onLogout()} style={{ float: 'right' }}>Logout</Menu.Item> </Menu> </Header> <Content style={{ padding: '1px 0' }}> <Layout className="site-layout-background" style={{ padding: '0 0' }}> <Sider collapsible collapsed={collapsed} onCollapse={onCollapse} className="site-layout-background" breakpoint="xs" > <Menu defaultSelectedKeys={['1']} defaultOpenKeys={['sub1']} mode="inline" theme="dark" > <Menu.Item key="1"> <TransactionOutlined /> <span><Link to="/transaction" style={{ color: 'white' }}>Transactions</Link></span> </Menu.Item> <Menu.Item key="2"> <PieChartOutlined /> <span><Link to="/report" style={{ color: 'white' }}>Reports</Link></span> </Menu.Item> {/* <Divider /> */} <Menu.Item key="3"> <ContainerOutlined /> <span>Help</span> </Menu.Item> <SubMenu key="sub1" title={ <span> <BarChartOutlined /> <span>Statistic</span> </span> } > <Menu.Item key="day">Day</Menu.Item> <Menu.Item key="week"><Link to="/statistic">Week</Link></Menu.Item> <Menu.Item key="month">Month</Menu.Item> </SubMenu> </Menu> </Sider> <Content style={{ padding: '0 24px', minHeight: 280 }}>{routes}</Content> </Layout> </Content> <Footer style={footerStyle}><span> Make by <b>MoneyMon</b> with <HeartTwoTone twoToneColor="#eb2f96" /> </span> <span>A product from <a rel="noopener noreferrer" href="http://dungtran.top" target="_blank">Dungtran.top</a></span> </Footer> </Layout> ) } const footerStyle = { width: "100%", padding: "0 24px", lineHeight: "80px", textAlign: "center", position: "fixed", bottom: 0, left: 0, } export default LoggedLayout;<file_sep>/frontend/src/components/Categories/ListCat.jsx import React, { useEffect, useState } from 'react'; import { getAllCategories, createCategory } from '../../api'; import { Row, Col, Table, Button, Tooltip, Modal, Input, Select, Checkbox, notification, message } from 'antd'; import { PlusCircleOutlined } from '@ant-design/icons'; const ListCategory = props => { const [categories, setCategories] = useState([]); const [visible, setVisible] = useState(false); const [catName, setCatName] = useState(''); const [catParent, setCatParent] = useState(''); const [isParent, setIsParent] = useState(false); useEffect(() => { const fetchCategories = async () => { let cats = await getAllCategories(); cats = cats.map(category => ({ ...category, key: category.id })); setCategories(cats); }; fetchCategories(); }, []); const columns = [ { title: 'Category', dataIndex: 'cat_name', key: 'id', }, { title: 'Parent', dataIndex: 'cat_parent', key: 'cat_parent', render: (text, row) => { const parent = row.cat_parent ? categories.filter(cat => cat.id === row.cat_parent) : []; return parent.length > 0 && parent[0].cat_name; } }, ]; const handleCancel = (event) => { setVisible(false); }; const reset = () => { setCatName(""); setIsParent(false); setCatParent(""); setVisible(false); } const handleOk = async (event) => { if (catName.length === 0) { message.error("Please enter a category name"); return; } const payload = { cat_name: catName, is_parent: isParent, cat_parent: catParent } try { const createdCat = await createCategory(payload); if (createdCat.id) { notification["success"]({ message: "Create Category success with name: " + createdCat.cat_name, title: "Created" }); const newCats = [...categories, { ...createdCat, key: createdCat.id }]; setCategories(newCats); reset(); } } catch (error) { console.log("handleOk -> error", error) notification["error"]({ message: error.message, title: "Error while creating category" }); reset(); } } return ( <Row style={{ height: 'calc(100vh - 140px)' }}> <Col> <Table bordered={true} dataSource={categories} columns={columns} tableLayout='auto' /> </Col> <Col> <Tooltip title="New Category"> <Button icon={<PlusCircleOutlined />} type="primary" shape="circle" onClick={() => setVisible(true)} ></Button> </Tooltip> </Col> <Modal visible={visible} title="New Category" onOk={(e) => handleOk(e)} onCancel={handleCancel} > <Input.Group > <Input addonBefore="Name" type="text" value={catName} onChange={(e) => setCatName(e.target.value)} placeholder="Enter category name" /> <Select allowClear placeholder="Select category parent" style={{ width: '100%' }} onChange={value => setCatParent(value)} > {categories.length > 0 && categories.map(cat => (<Select.Option value={cat.id} key={cat.id}>{cat.cat_name}</Select.Option>))} </Select> <Checkbox onChange={(e) => setIsParent(!isParent)}>Is category parent?</Checkbox> </Input.Group> </Modal> </Row> ) } export default ListCategory;<file_sep>/backend/moneymon/wallet/admin.py from django.contrib import admin from .models import Wallet, Categories from data_seeder.admin import DataGeneratorAdmin class WalletAdmin(admin.ModelAdmin): pass models = [Wallet, Categories] admin.site.register(models, DataGeneratorAdmin) <file_sep>/frontend/src/containers/DefaultLayout.jsx import React from 'react'; import { ConnectedRouter } from 'connected-react-router'; import routes from '../routes'; import { Layout } from 'antd'; import { HeartTwoTone } from '@ant-design/icons'; import NavBar from '../components/NavBar'; import Footer from '../components/Footer'; import { withGetScreen } from 'react-getscreen'; import { useSelector } from 'react-redux'; import LoggedLayout from './LoggedLayout'; const { Content } = Layout; const NavDataSource = { wrapper: { className: 'header home-page-wrapper' }, page: { className: 'home-page' }, logo: { className: 'header-logo', children: 'https://i.ibb.co/dfx6G33/logo.png', }, Menu: { className: 'header-menu', }, mobileMenu: { className: 'header-mobile-menu' }, }; const FooterDataSource = { wrapper: { className: 'home-page-wrapper footer-wrapper' }, OverPack: { className: 'home-page footer', playScale: 0.05 }, copyright: { className: 'copyright', children: ( <span> Make by <b>MoneyMon</b> with <HeartTwoTone twoToneColor="#eb2f96" /> <span>A product from <a rel="noopener noreferrer" href="http://dungtran.top" target="_blank">Dungtran.top</a></span> </span> ), }, }; const DefaultLayout = props => { const authData = useSelector(state => state.authReducer); if (authData.token) return ( <ConnectedRouter history={props.history}> <LoggedLayout /> </ConnectedRouter>) const isMobile = props.isMobile(); return ( <ConnectedRouter history={props.history}> <Layout> <NavBar id="Nav0_0" key="Nav0_0" dataSource={{ ...NavDataSource }} isMobile={isMobile} /> <Content> <div className="content"> {routes} </div> </Content> <Footer id="Footer_0" key="Footer_0" dataSource={{ ...FooterDataSource }} isMobile={isMobile} /> </Layout> </ConnectedRouter> ) } export default withGetScreen(DefaultLayout);<file_sep>/frontend/src/reducers/auth.reducer.js import * as types from '../constants/ActionsTypes'; const initialState = { loading: false, token: localStorage.getItem('token'), error: null } const authReducer = (state = initialState, action) => { switch (action.type) { case types.REQUEST_STARTED: console.log("REQUEST_STARTED"); return { ...state, loading: true }; case types.REQUEST_SUCCESS: console.log("REQUEST_SUCCESS with payload:", action.payload); return { ...state, loading: false, error: null, token: action.payload } case types.REQUEST_FAILURE: console.log("REQUEST_FAILURE with error", action.payload); return { ...state, loading: false, token: null, error: action.payload } default: return state; } } export default authReducer;<file_sep>/frontend/src/pages/Home/index.js import React from 'react'; import { enquireScreen } from 'enquire-js'; import Banner0 from '../../components/Banner'; import Content0 from '../../components/Contents/Content0'; import Content7 from '../../components/Contents/Content7'; import Content13 from '../../components/Contents/Content13'; import { BannerDataSource, ContentDataSource, Content70DataSource, Content130DataSource, } from './data.source.js'; import '../../less/main.less'; let isMobile; enquireScreen((b) => { isMobile = b; }); const location = window.location; export default class Home extends React.Component { constructor(props) { super(props); this.state = { isMobile, show: !location.port, }; } componentDidMount() { enquireScreen((b) => { this.setState({ isMobile: !!b }); }); if (location.port) { setTimeout(() => { this.setState({ show: true, }); }, 500); } } render() { const children = [ <Banner0 id="Banner0_0" key="Banner0_0" dataSource={BannerDataSource} isMobile={this.state.isMobile} />, <Content0 id="Content0_0" key="Content0_0" dataSource={ContentDataSource} isMobile={this.state.isMobile} />, <Content7 id="Content7_0" key="Content7_0" dataSource={Content70DataSource} isMobile={this.state.isMobile} />, <Content13 id="Content13_0" key="Content13_0" dataSource={Content130DataSource} isMobile={this.state.isMobile} /> ]; return ( <div className="templates-wrapper" ref={(d) => { this.dom = d; }} > {this.state.show && children} </div> ); } } <file_sep>/backend/moneymon/wallet/serializers.py from rest_framework import serializers from .models import Wallet, Categories class WalletSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( default=serializers.CurrentUserDefault(), read_only=True) wallet_type = serializers.ChoiceField(choices=Wallet.WALLET_TYPES) wallet_type_name = serializers.SerializerMethodField() class Meta: model = Wallet fields = '__all__' def get_wallet_type_name(self, obj): return obj.get_wallet_type_display() class CategoriesSerializer(serializers.ModelSerializer): # cat_types = serializers.ChoiceField(choices=Categories.CATEGORIES_TYPES) # cat_types_name = serializers.SerializerMethodField() class Meta: model = Categories fields = '__all__' # def get_cat_types_name(self, obj): # return obj.get_cat_types_display() <file_sep>/backend/moneymon/wallet/migrations/0004_wallet_updated_at.py # Generated by Django 3.0.4 on 2020-05-06 03:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wallet', '0003_auto_20200506_1050'), ] operations = [ migrations.AddField( model_name='wallet', name='updated_at', field=models.DateTimeField(auto_now=True, verbose_name='Updated at'), ), ] <file_sep>/backend/moneymon/wallet/migrations/0011_auto_20200506_1602.py # Generated by Django 3.0.4 on 2020-05-06 09:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wallet', '0010_auto_20200506_1556'), ] operations = [ migrations.AlterField( model_name='wallet', name='wallet_type', field=models.CharField(choices=[('BASIC', 'Tiền mặt'), ('DIGITAL', 'Ví điện tử'), ('CARD', 'Thẻ ngân hàng'), ('CREDIT', 'Thẻ ghi nợ')], default='BASIC', max_length=255), ), ] <file_sep>/frontend/src/utils/transaction.util.js import * as _ from 'lodash'; export const formatNumberToMoney = value => value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); /** * * @param {Array} transactions list transactions * @param {Array} duplicated_lst contain transaction id which have multi transaction from one category * @description If transaction is duplicated, it will be merged with total amount of all transactions * @return {Object} new object * @example { label: 'category_name', y: 'amount_total' } */ export const mergeDupTransactionByCategory = (transactions, duplicated_lst) => { return duplicated_lst.map(tran_cat => { const transactions_by_cat = transactions.filter(tran => tran.category === tran_cat); const amount_total = transactions_by_cat .map(tran => tran.action === "IN" ? parseFloat(tran.amount) : -parseFloat(tran.amount)) .reduce((prev, curr) => prev + curr, 0); console.log("amount: " + amount_total); return { label: transactions_by_cat[0].category_name, y: `${amount_total}` }; }) }<file_sep>/backend/moneymon/wallet/models.py from django.db import models from django.utils import timezone from django.conf import settings from djmoney.models.fields import MoneyField from djmoney.money import Money class Wallet(models.Model): WALLET_TYPES = ( ("BASIC", "Tiền mặt"), ("DIGITAL", "Ví điện tử"), ("CARD", "Thẻ ngân hàng"), ("CREDIT", "Thẻ ghi nợ"), ) wallet_type = models.CharField( choices=WALLET_TYPES, default=WALLET_TYPES[0][0], max_length=255) balance = MoneyField( 'balance', default_currency='VND', max_digits=15, default=Money(0, 'VND')) wallet_name = models.CharField(max_length=255) description = models.CharField(max_length=512) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, to_field='username') created_at = models.DateTimeField('Created at', auto_now=True) updated_at = models.DateTimeField('Updated at', auto_now=True) def save_model(self, request, obj, form, change): if not obj.pk: obj.user = request.user super().save_model(request, obj, form, change) def __str__(self): return self.wallet_name class Categories(models.Model): CATEGORIES_TYPES = ( ('bill_utils', 'Bills & Utilities'), ('families', 'Families'), ('education', 'Education'), ('entertainment', 'Entertainment'), ('health', 'Health') ) cat_name = models.CharField(max_length=255, unique=True) # cat_types = models.CharField(max_length=255, choices=CATEGORIES_TYPES) cat_parent = models.ForeignKey( 'self', null=True, blank=True, related_name="childs", on_delete=models.CASCADE) is_parent = models.BooleanField(default=False) def __str__(self): return self.cat_name <file_sep>/backend/moneymon/moneymon/settings.py """ Django settings for moneymon project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os from datetime import timedelta import environ env = environ.Env() env.read_env(env.str('ENV_PATH', './.env.dev')) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run with debug turned on in production! DEBUG = int(os.environ.get("DEBUG", default=1)) # ALLOWED_HOSTS = [] ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djoser', 'corsheaders', 'djmoney', 'users', 'wallet', 'transactions', 'sslserver', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', 'django_seed', 'data_seeder' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework_simplejwt.authentication.JWTAuthentication', # django-oauth-toolkit >= 1.0.0 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', ), 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.ModelSerializer', } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ "http://localhost:3001", "http://localhost:3000", "http://localhost:8080", "http://127.0.0.1:9000" ] ROOT_URLCONF = 'moneymon.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'moneymon.wsgi.application' AUTH_USER_MODEL = 'users.User' AUTHENTICATION_BACKENDS = ( 'rest_framework_social_oauth2.backends.DjangoOAuth2', # Google OAuth2 'social_core.backends.google.GoogleOAuth2', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.postgresql"), "NAME": os.environ.get("SQL_DATABASE", 'moneymon_db'), "USER": os.environ.get("SQL_USER", "postgres"), "PASSWORD": os.environ.get("SQL_PASSWORD", "<PASSWORD>"), "HOST": os.environ.get("SQL_HOST", "127.0.0.1"), "PORT": os.environ.get("SQL_PORT", "5432"), } # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': 'moneymon_db', # } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(weeks=4), } # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ PROJECT_DIR = os.path.dirname(os.path.realpath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') SOCIAL_AUTH_POSTGRES_JSONFIELD = True # Facebook configuration SOCIAL_AUTH_FACEBOOK_KEY = '861282047725896' SOCIAL_AUTH_FACEBOOK_SECRET = '<KEY>' # Define SOCIAL_AUTH_FACEBOOK_SCOPE to get extra permissions from Facebook. # Email is not sent by default, to get it, you must request the email permission. SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } # Google configuration SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '474894401938-hib8j06eov4t7fu3mpt9a7cc6if0bf8h.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '<KEY>' # Define SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE to get extra permissions from Google. SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] <file_sep>/frontend/src/pages/Home/data.source.js import React from 'react'; export const BannerDataSource = { wrapper: { className: 'banner' }, textWrapper: { className: 'banner-text-wrapper' }, title: { className: 'banner-title', children: 'https://i.ibb.co/dfx6G33/logo.png', }, content: { className: 'banner-content', children: ( <span> <p>Lorem me ipsum dolor sit amet, consectet.</p> <p>Lorem ips ipsum dolor sit amet, consectet. Cur </p> </span> ), }, button: { className: 'banner-button', children: 'Learn More' }, }; export const ContentDataSource = { wrapper: { className: 'home-page-wrapper content0-wrapper' }, page: { className: 'home-page content0' }, OverPack: { playScale: 0.3, className: '' }, titleWrapper: { className: 'title-wrapper', children: [{ name: 'title', children: 'Lorem ipsum' }], }, block: { className: 'block-wrapper', children: [ { name: 'block0', className: 'block', md: 8, xs: 24, children: { icon: { className: 'icon', children: 'https://zos.alipayobjects.com/rmsportal/WBnVOjtIlGWbzyQivuyq.png', }, title: { children: 'Lorem ipsum dolor sit amet' }, content: { children: 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...' }, }, }, { name: 'block1', className: 'block', md: 8, xs: 24, children: { icon: { className: 'icon', children: 'https://zos.alipayobjects.com/rmsportal/YPMsLQuCEXtuEkmXTTdk.png', }, title: { children: 'lorem ipsum dolor sit amet' }, content: { children: 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...' }, }, }, { name: 'block2', className: 'block', md: 8, xs: 24, children: { icon: { className: 'icon', children: 'https://zos.alipayobjects.com/rmsportal/EkXWVvAaFJKCzhMmQYiX.png', }, title: { children: 'lorem ipsum dolor sit amet' }, content: { children: 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...' }, }, }, ], }, }; export const Content70DataSource = { wrapper: { className: 'home-page-wrapper content7-wrapper' }, page: { className: 'home-page content7' }, OverPack: {}, titleWrapper: { className: 'title-wrapper', children: [ { name: 'title', children: 'lorem ipsum dolor sit amet', className: 'title-h1', }, { name: 'content', children: 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...' }, ], }, tabsWrapper: { className: 'content7-tabs-wrapper' }, block: { children: [ { name: 'block0', tag: { className: 'content7-tag', text: { children: 'PHONE', className: 'content7-tag-name' }, icon: { children: 'mobile' }, }, content: { className: 'content7-content', text: { className: 'content7-text', md: 14, xs: 24, children: ( <span> <h3>lorem</h3> <p> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... </p> <br /> <h3>Lorem me ipsum</h3> <p> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... </p> <br /> <h3> lorem </h3> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... </span> ), }, img: { className: 'content7-img', children: 'https://zos.alipayobjects.com/rmsportal/xBrUaDROgtFBRRL.png', md: 10, xs: 24, }, }, }, { name: 'block1', tag: { className: 'content7-tag', icon: { children: 'tablet' }, text: { className: 'content7-tag-name', children: 'TABLET' }, }, content: { className: 'content7-content', text: { className: 'content7-text', md: 14, xs: 24, children: ( <span> <h3>lorem</h3> <p> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... </p> <br /> <h3>lorem</h3> <p> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... </p> <br /> <h3> Lorem </h3> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... </span> ), }, img: { className: 'content7-img', md: 10, xs: 24, children: 'https://zos.alipayobjects.com/rmsportal/xBrUaDROgtFBRRL.png', }, }, }, { name: 'block2', tag: { className: 'content7-tag', text: { children: 'DESKTOP', className: 'content7-tag-name' }, icon: { children: 'laptop' }, }, content: { className: 'content7-content', text: { className: 'content7-text', md: 14, xs: 24, children: ( <span> <h3>lorem</h3> <p> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... </p> <br /> <h3>lorem vel</h3> <p> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... </p> <br /> <h3> lorem porro quisquam </h3> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... </span> ), }, img: { className: 'content7-img', md: 10, xs: 24, children: 'https://zos.alipayobjects.com/rmsportal/xBrUaDROgtFBRRL.png', }, }, }, ], }, }; export const Content130DataSource = { OverPack: { className: 'home-page-wrapper content13-wrapper home-page-wrapper content13-wrapper jnwq7vhwgqg-editor_css', playScale: 0.3, }, titleWrapper: { className: 'title-wrapper', children: [ { name: 'title', children: 'Lorem', className: 'title-h1' }, { name: 'content', children: 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...', className: 'title-content', }, { name: 'content2', children: 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...', className: 'title-content', }, ], }, }; export const Content120DataSource = { wrapper: { className: 'home-page-wrapper content12-wrapper' }, page: { className: 'home-page content12' }, OverPack: { playScale: 0.3, className: '' }, titleWrapper: { className: 'title-wrapper', children: [{ name: 'title', children: 'Login ipsum text', className: 'title-h1' }], }, block: { className: 'img-wrapper', children: [ { name: 'block0', className: 'block', md: 8, xs: 24, children: { wrapper: { className: 'block-content' }, img: { children: 'https://gw.alipayobjects.com/zos/rmsportal/TFicUVisNHTOEeMYXuQF.svg', }, }, }, { name: 'block1', className: 'block', md: 8, xs: 24, children: { wrapper: { className: 'block-content' }, img: { children: 'https://gw.alipayobjects.com/zos/rmsportal/hkLGkrlCEkGZeMQlnEkD.svg', }, }, }, { name: 'block2', className: 'block', md: 8, xs: 24, children: { wrapper: { className: 'block-content' }, img: { children: 'https://gw.alipayobjects.com/zos/rmsportal/bqyPRSZmhvrsfJrBvASi.svg', }, }, }, { name: 'block3', className: 'block', md: 8, xs: 24, children: { wrapper: { className: 'block-content' }, img: { children: 'https://gw.alipayobjects.com/zos/rmsportal/UcsyszzOabdCYDkoPPnM.svg', }, }, }, { name: 'block4', className: 'block', md: 8, xs: 24, children: { wrapper: { className: 'block-content' }, img: { children: 'https://gw.alipayobjects.com/zos/rmsportal/kRBeaICGexAmVjqBEqgw.svg', }, }, }, { name: 'block5', className: 'block', md: 8, xs: 24, children: { wrapper: { className: 'block-content' }, img: { children: 'https://gw.alipayobjects.com/zos/rmsportal/ftBIiyJcCHpHEioRvPsV.svg', }, }, }, ], }, }; <file_sep>/frontend/src/components/Dashboard/index.js import React, {Fragment} from 'react'; import Footer from '../Footer' import 'antd/dist/antd.css'; import './index.css'; import { Layout, Menu, Avatar, Switch, Dropdown, Button } from 'antd'; import { SettingOutlined, LogoutOutlined, DownOutlined, HeartTwoTone, MenuUnfoldOutlined, MenuFoldOutlined, TransactionOutlined, WalletOutlined, AppstoreOutlined, } from '@ant-design/icons'; const { SubMenu } = Menu const { Header, Sider, Content } = Layout; const FooterDataSource = { wrapper: { className: 'footer-wrapper' }, OverPack: { className: 'footer', playScale: 0.00001 }, copyright: { className: 'copyright', children: ( <span> Make by <b>MoneyMon</b> with <HeartTwoTone twoToneColor="#eb2f96" /> A product from <a rel="noopener noreferrer" href="http://dungtran.top" target="_blank">Dungtran.top</a> </span> ), }, }; class DashboardDemo extends React.Component { state = { theme: 'dark', current: '1', collapsed: false, }; onCollapse = collapsed => { console.log(collapsed); this.setState({collapsed}); }; changeTheme = value => { this.setState({ theme: value ? "dark" : "light", }); }; handleClick = e => { console.log("click ", e); this.setState({ current: e.key, }); }; toggle = () => { this.setState({ collapsed: !this.state.collapsed, }); }; render() { const dropdown = ( <Menu style={{ width: '20em', boxShadow: '1px 8px 4px 5px rgba(208, 216, 243, 0.6)' }} > <Menu.ItemGroup title="Chọn ví"> <Menu.Item>1st menu item</Menu.Item> <Menu.Item>2nd menu item</Menu.Item> </Menu.ItemGroup> <Menu.ItemGroup title="Tính vào tổng"> <Menu.Item>1st menu item</Menu.Item> <Menu.Item>2nd menu item</Menu.Item> </Menu.ItemGroup> </Menu> ); const { avatar, username, } = this.props return ( <Layout> <Sider trigger={null} collapsible collapsed={this.state.collapsed}> <Menu style={{ minHeight: '100vh', height: '100%' }} theme={this.state.theme} onClick={this.handleClick} selectedKeys={[this.state.current]} mode="inline"> <a href="/"> <span> <img src="https://i.ibb.co/dfx6G33/logo.png" alt="logo" className="logo"/> </span> </a> <Menu.Item key="Transaction"> <a href="/transaction"> <span> <TransactionOutlined /> <span>Transactions</span> </span> </a> </Menu.Item> <Menu.Item key="Wallet"> <a href="/wallet"> <span> <WalletOutlined /> <span>Wallet</span> </span> </a> </Menu.Item> <Menu.Item key="Category"> <a href="/category"> <span> <AppstoreOutlined /> <span>Category</span> </span> </a> </Menu.Item> <div key="4" style={{ textAlign: "center", }} > <span> <Switch checked={this.state.theme === 'dark'} onChange={this.changeTheme} checkedChildren="Dark" unCheckedChildren="Light" /> </span> </div> </Menu> </Sider> <Layout className="site-layout" > <Header className="site-layout-background" > <Button className="dropdown-link" onClick={this.toggle}> {React.createElement(this.state.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined)} </Button> <Dropdown overlay={dropdown}> <Button className="dropdown-link" onClick={e => e.preventDefault()}> <DownOutlined /> </Button> </Dropdown> <Menu style={{float: 'right'}} theme="light" mode="horizontal" defaultSelectedKeys={['SignOut']}> <SubMenu title={ <Fragment> <span style={{ color: '#999', marginRight: 4 }}> Hi, </span> <span>{username}username</span> <Avatar style={{ marginLeft: 8 }} src={avatar} /> </Fragment> }> <Menu.Item key="UserSetting"> <a href="/test"> <SettingOutlined/> Settings</a> </Menu.Item> <Menu.Item key="SignOut"> <p> <LogoutOutlined/> Sign out </p> </Menu.Item> </SubMenu> </Menu> </Header> <Content className="site-layout-background" style={{ margin: '24px 16px', padding: 24 }} > {this.props.children} </Content> <Footer id="Footer_1" key="Footer_1" dataSource={{ ...FooterDataSource }} /> </Layout> </Layout> ); } } export default DashboardDemo;<file_sep>/backend/moneymon/users/admin.py from django.contrib import admin from .models import User class UserAdmin(admin.ModelAdmin): # fields = [ 'description', 'created_at'] # fieldsets = [ # (None, {'fields': ['email']}), # ('Date information', {'fields': ['date_joined']}), # ] list_display = ('username', 'is_staff', 'is_active') list_filter = ['date_joined'] search_fields = ['email', 'username'] admin.site.register(User, UserAdmin) # Register your models here. <file_sep>/frontend/src/api/config.js export const HOST = process.env.HOST || "http://localhost:3000"; const API_URI = { TRANSACTION: "api/transaction", WALLET: "api/wallet", CATEGORY: "api/category", EXPORT: "api/export", STATISTIC: "api/statistic", }; const AUTH_URI = { JWT_TOKEN: "auth/token", SOCIAL_TOKEN: "auth/convert-token", USER: "auth/users", }; const headers = new Headers(); headers.append("Content-Type", "application/x-www-form-urlencoded"); export { headers }; const URI = { API_URI, AUTH_URI }; export default URI; <file_sep>/frontend/src/components/Categories/index.jsx import React from 'react'; import ListCategory from './ListCat'; const CategoryComponent = props => { return ( <ListCategory></ListCategory> ) } export default CategoryComponent;<file_sep>/frontend/src/pages/Statistic/index.jsx import React from 'react'; import { Row } from 'antd'; import WeekStatistic from '../../components/Statistic/Week'; const StatisticPage = props => { return ( <Row justify="center" align='top' style={{ height: 'calc(100vh - 146.1px)' }}> <WeekStatistic></WeekStatistic> </Row> ) } export default StatisticPage;<file_sep>/frontend/src/components/Register/RegistrationForm.js import React from 'react'; import { Form, Input, Tooltip, Checkbox, Button, message } from 'antd'; import { QuestionCircleOutlined } from '@ant-design/icons'; import { Link } from 'react-router-dom'; import { useDispatch } from 'react-redux'; import { registerUser } from '../../actions/registration.action'; import ReCAPTCHAv2 from 'react-google-recaptcha'; const formItemLayout = { labelCol: { xs: { span: 24, }, sm: { span: 8, }, }, wrapperCol: { xs: { span: 24, }, sm: { span: 16, }, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; const RegistrationForm = () => { const [form] = Form.useForm(); const dispatch = useDispatch(); const recaptchaRef = React.createRef(); const onFinish = values => { console.log('Received values of form: ', values); const recaptchaValue = recaptchaRef.current.getValue(); if(!recaptchaValue) { message.error("Please complete the recaptcha"); return; } dispatch(registerUser(values)); }; return ( <Form {...formItemLayout} form={form} name="register" onFinish={onFinish} scrollToFirstError > <Form.Item name="email" label="E-mail" rules={[ { type: 'email', message: 'The input is not valid E-mail!', }, { required: true, message: 'Please input your E-mail!', }, ]} > <Input /> </Form.Item> <Form.Item name="password" label="Password" rules={[ { required: true, message: 'Please input a valid password!', pattern: '', min: 8 }, ]} hasFeedback > <Input.Password /> </Form.Item> <Form.Item name="confirm" label="Confirm" dependencies={['password']} hasFeedback rules={[ { required: true, message: 'Please confirm your password!', }, ({ getFieldValue }) => ({ validator(rule, value) { if (!value || getFieldValue('password') === value) { return Promise.resolve(); } return Promise.reject('The two passwords that you entered do not match!'); }, }), ]} > <Input.Password /> </Form.Item> <Form.Item name="username" label={ <span> Username&nbsp; <Tooltip title="You need to enter a username to login"> <QuestionCircleOutlined /> </Tooltip> </span> } rules={[ { required: true, message: 'Please input your username!', whitespace: false, }, ]} > <Input /> </Form.Item> <Form.Item name="location" label="Address" > <Input /> </Form.Item> <Form.Item name="agreement" valuePropName="checked" rules={[ { validator: (_, value) => value ? Promise.resolve() : Promise.reject('Should accept agreement'), }, ]} {...tailFormItemLayout} > <Checkbox style={{ color: 'white' }}> I have read the agreement </Checkbox> </Form.Item> <ReCAPTCHAv2 ref={recaptchaRef} sitekey="<KEY>" /> <Form.Item {...tailFormItemLayout}> <Button type="primary" htmlType="submit"> Register </Button> or <Link to='/login'>Login now!</Link> </Form.Item> </Form> ); }; export default RegistrationForm;<file_sep>/backend/moneymon/moneymon/__init__.py # Test Pull GIt Hub<file_sep>/backend/moneymon/seeder.py import random from django_seed import Seed seeder = Seed.seeder(locale='en-us') from transactions.models import Transactions from wallet.models import Wallet, Categories from users.models import User wallet_ids = Wallet.objects.all()#.values_list('id', flat=True) categories_ids = Categories.objects.all()#.values_list('id',flat=True) user_ids = User.objects.all()#.values_list('id', flat=True) user = User.objects.filter(id=14).first() actions = ['IN','OUT'] seeder.add_entity(Transactions, 50, { 'name': lambda x: 'transaction_'+ seeder.faker.name(), 'amount': lambda x: random.randint(10**4,10**6), # lambda x: seeder.faker.email(), 'action': lambda x: random.choice(actions), 'category': lambda x: (random.choice(categories_ids)), 'from_wallet': lambda x:(random.choice(wallet_ids)), 'created_at': lambda x: seeder.faker.date_time_this_year(), 'user': lambda x: user #(random.choice(user_ids)) }) inserted_pks = seeder.execute() print(inserted_pks)<file_sep>/frontend/src/components/Statistic/chart-option.js export const IncomeDatasets = { label: "Income", fill: false, lineTension: 0.1, backgroundColor: "rgba(75,192,192,0.5)", borderColor: "rgba(75,192,192,1)", borderCapStyle: "butt", borderDash: [], borderDashOffset: 0.0, borderJoinStyle: "miter", pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: "rgba(75,192,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, }; export const ExpenseDatasets = { label: "Expense", fill: false, lineTension: 0.1, backgroundColor: "rgba(255,99,132,0.5)", borderColor: "rgba(255,99,132,1)", borderCapStyle: "butt", borderDash: [], borderDashOffset: 0.0, borderJoinStyle: "miter", pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: "rgba(75,192,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, }; <file_sep>/backend/moneymon/transactions/models.py from django.db import models from django.utils import timezone from django.conf import settings from djmoney.models.fields import MoneyField from wallet.models import Categories, Wallet class Transactions(models.Model): ACTIONS = ( ('IN', 'Cộng'), ('OUT', 'Trừ') ) name = models.CharField(max_length=255) amount = MoneyField('amount', default_currency='VND', max_digits=15) action = models.CharField( max_length=255, choices=ACTIONS) created_at = models.DateTimeField('Created at', auto_now=True) category = models.ForeignKey( Categories, on_delete=models.CASCADE, related_name='category') from_wallet = models.ForeignKey( Wallet, on_delete=models.CASCADE, related_name='from_wallet') user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, to_field='username') def save_model(self, request, obj, form, change): if not obj.pk: obj.user = request.user super().save_model(request, obj, form, change) def __str__(self): return self.name <file_sep>/frontend/src/api/index.js export * from './auth.api'; export * from './transaction.api'; export * from './common.api'<file_sep>/frontend/src/api/common.api.js import fetch from 'cross-fetch'; import URI, { HOST, headers } from './config'; import { token } from '../utils/auth.util'; export const getAllCategories = async () => { const response = await fetch(`${HOST}/${URI.API_URI.CATEGORY}`, { method: 'get' }); const json = await response.json(); try { if (!json) throw json; else return json; } catch (error) { console.error(error); } } export const getAllUserWallets = async () => { const response = await fetch(`${HOST}/${URI.API_URI.WALLET}`, { method: 'get', headers: { ...headers, authorization: 'Bearer ' + token().access_token } }); const json = await response.json(); try { if (json.detail) throw json; else return json; } catch (error) { console.error(error); throw error; } } export const createCategory = async body => { try { const response = await fetch(`${HOST}/${URI.API_URI.CATEGORY}`, { method: 'post', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json', authorization: 'Bearer ' + token().access_token } }); const json = await response.json(); if (!json) throw json; else return json; } catch (error) { console.error("error:",error); throw error; } }<file_sep>/backend/moneymon/transactions/views.py from rest_framework.generics import ( ListCreateAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView) from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets from django.db.models import Q from .models import Transactions from drf_renderer_xlsx.mixins import XLSXFileMixin from drf_renderer_xlsx.renderers import XLSXRenderer from .serializers import TransactionsSerializer import datetime class TransactionsCreateView(viewsets.ModelViewSet): # queryset = Transactions.objects.all() serializer_class = TransactionsSerializer permission_classes = [IsAuthenticated] def get_queryset(self): from_wallet = self.request.query_params.get('from_wallet') print("from:", from_wallet) category = self.request.query_params.get('category') qs = Transactions.objects.filter(user=self.request.user) if from_wallet is None: return qs # elif category is None: # return qs else: qs = Transactions.objects.filter(Q(user=self.request.user) & Q(from_wallet=from_wallet) ) return qs def perform_create(self, serializer): category = self.request.data.get('category') from_wallet = self.request.data.get('from_wallet') serializer.save(category=category, from_wallet=from_wallet, user=self.request.user) def perform_update(self, serializer): category = self.request.data.get('category') from_wallet = self.request.data.get('from_wallet') if category or from_wallet: serializer.save(category=category, from_wallet=from_wallet) else: serializer.save() class TransactionsViewStatistic(viewsets.ReadOnlyModelViewSet): serializer_class = TransactionsSerializer permission_classes = [IsAuthenticated] def get_queryset(self): date_str = self.request.query_params.get('date') # YYYY-MM-DD start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') format_str = '%Y-%m-%d' if date_str: date = datetime.datetime.strptime(date_str, format_str) qs = Transactions.objects.filter(user=self.request.user, created_at__date=date.date()) elif start_date is not None and end_date is not None: start = datetime.datetime.strptime(start_date, format_str).date() end = datetime.datetime.strptime(end_date, format_str).date() qs = Transactions.objects.filter(user=self.request.user,created_at__date__range=(start, end)) else: qs = Transactions.objects.filter(user=self.request.user) return qs class ExportTransactionView(XLSXFileMixin, viewsets.ReadOnlyModelViewSet): serializer_class = TransactionsSerializer renderer_classes = [XLSXRenderer] permission_classes = [IsAuthenticated] filename = 'transaction.xlsx' def get_queryset(self): return Transactions.objects.filter(user=self.request.user)<file_sep>/frontend/src/reducers/index.js import { combineReducers } from 'redux'; import { connectRouter } from 'connected-react-router'; import authReducer from './auth.reducer'; import transactionsReducer from './transaction.reducer'; import alertReducer from './alert.reducer'; import registrationReducer from './registration.reducer'; const createRootReducer = history => combineReducers({ router: connectRouter(history), authReducer, transactionsReducer, alertReducer, registrationReducer }) export default createRootReducer;<file_sep>/frontend/src/components/Wallet/DetailWallet.jsx import React, { useState } from 'react'; import Modal from 'antd/lib/modal'; import { Button, Input, Select, Switch, notification, message } from 'antd'; import { w_types, CURRENCIES } from '../../constants/currency'; import MoneyInput from '../Transaction/MoneyInput'; import { EditOutlined, EyeOutlined } from '@ant-design/icons'; import { updateWallet } from '../../api/wallet.api'; const DetailWallet = (props) => { const { wallet } = props; const { id, wallet_name = null, wallet_type, description: desc, balance, balance_currency } = wallet const [edit, setEdit] = useState(false); const [walletName, setWalletName] = useState(wallet_name); const [description, setDescription] = useState(desc); const [walletType, setWalletType] = useState(wallet_type); const [balanceCurrency, setBalanceCurrency] = useState(balance_currency); const [loading, setLoading] = useState(false) const handleOk = async e => { if (walletName === "") { message.error("Please enter a wallet name"); return; } if (balanceCurrency === "") { message.error("Please choose balance currency"); return; } if (walletType === "") { message.error("Please choose a wallet type"); return; } setLoading(true); const payload = { wallet_name: walletName, wallet_type: walletType, description, balance_currency: balanceCurrency, } try { const response = await updateWallet(id, payload); console.log("DetailWal -> response", response) message.success(`Updated wallet ${response.id} successfully`); props.updatedWallet(response); console.log(response); } catch (error) { console.log("handleOk -> error", error) notification["error"]({ title: "Error", message: error.detail || "Error while creating wallet" }); } setLoading(false); props.setVisible(false); } const handleCancel = () => props.setVisible(false); return (<Modal visible={props.visible} title={wallet.wallet_name} onOk={handleOk} onCancel={handleCancel} footer={[ <Button key="back" onClick={handleCancel}> Close </Button>, edit && <Button key="Update" type="primary" loading={loading} onClick={handleOk}> Update </Button>, ]} > <Input.Group > <Switch checkedChildren={<EditOutlined />} unCheckedChildren={<EyeOutlined />} defaultChecked={edit} onChange={(checked, event) => setEdit(checked)} /> <Input disabled={!edit} addonBefore="Name" type="text" value={walletName} onChange={(e) => setWalletName(e.target.value)} placeholder="Enter wallet name" /> <Input disabled={!edit} addonBefore="Description" type="text" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Wallet description" /> <MoneyInput disabled addonBefore="Balance" value={balance} onChange={(e) => { }} /> <Select disabled={!edit} allowClear placeholder="Select wallet type" style={{ width: '100%' }} defaultValue={walletType} onChange={value => setWalletType(value)} > {w_types.map(type => (<Select.Option value={type} key={type}>{type}</Select.Option>))} </Select> <Select disabled={!edit} showSearch allowClear placeholder="Select currency" style={{ width: '100%' }} onChange={value => setBalanceCurrency(value)} defaultValue={balanceCurrency} > {CURRENCIES.map(currency => (<Select.Option value={currency} key={currency}>{currency}</Select.Option>))} </Select> </Input.Group> </Modal>) } export default DetailWallet;<file_sep>/frontend/src/constants/client-secret.js const CLIENT = { ID: "<KEY>", SECRET: "<KEY>", } export { CLIENT };<file_sep>/frontend/src/pages/Categories/index.jsx import React from 'react'; import CategoryComponent from '../../components/Categories'; import { Row } from 'antd'; const CategoryPage = props => { return ( <Row justify="start" align='top' style={{ height: 'calc(100vh - 146.1px)' }}> <CategoryComponent {...props}></CategoryComponent> </Row> ) } export default CategoryPage;<file_sep>/backend/moneymon/wallet/migrations/0003_auto_20200506_1050.py # Generated by Django 3.0.4 on 2020-05-06 03:50 from decimal import Decimal from django.db import migrations, models import djmoney.models.fields class Migration(migrations.Migration): dependencies = [ ('wallet', '0002_auto_20200506_1025'), ] operations = [ migrations.AddField( model_name='wallet', name='created_at', field=models.DateTimeField(auto_now=True, verbose_name='Created at'), ), migrations.AlterField( model_name='wallet', name='balance', field=djmoney.models.fields.MoneyField(decimal_places=2, default=Decimal('0'), default_currency='VND', max_digits=15, verbose_name='balance'), ), migrations.AlterField( model_name='wallet', name='wallet_type', field=models.CharField(choices=[('Money', 'Tiền mặt'), ('Digital', 'Ví điện tử'), ('Card', 'Thẻ ngân hàng'), ('Credit', 'Thẻ ghi nợ')], default='Tiền mặt', max_length=255), ), ] <file_sep>/backend/moneymon/transactions/serializers.py from rest_framework import serializers from .models import Transactions from wallet.models import Wallet, Categories from wallet.serializers import CategoriesSerializer, WalletSerializer from rest_framework.utils import model_meta from rest_framework.exceptions import NotFound class TransactionsSerializer(serializers.ModelSerializer): action = serializers.ChoiceField(choices=Transactions.ACTIONS) action_name = serializers.SerializerMethodField() # category = serializers.StringRelatedField() # from_wallet = serializers.StringRelatedField() category_name = serializers.StringRelatedField(source='category') from_wallet_name = serializers.StringRelatedField(source='from_wallet') user = serializers.PrimaryKeyRelatedField( default=serializers.CurrentUserDefault(), read_only=True) class Meta: model = Transactions fields = '__all__' def get_action_name(self, obj): return obj.get_action_display() def get_cat_name(self, obj): return obj.get_category_display() def create(self, validated_data): category = validated_data.get('category') action = validated_data.get('action') #lấy action từ transaction money_in_transaction = validated_data.get('amount') #lấy tiền từ transaction category_id = category if category != None else 1 wallet_id = validated_data.get('from_wallet') found_category = Categories.objects.filter(id=int(category_id)).first() # found_wallet = Wallet.objects.filter(id=int(wallet_id))[0] found_wallet = Wallet.objects.get(id=int(wallet_id)) #lấy Wallet if action == 'OUT' and found_wallet.balance.amount < money_in_transaction: raise serializers.ValidationError('Balance is not enough for current transaction') if found_category and found_wallet: #tìm found_wallet.balance => update balance dựa theo action validated_data['category'] = found_category validated_data['from_wallet'] = found_wallet #update dựa trên ví tiền if (action=='IN'): found_wallet.balance.amount += money_in_transaction else: found_wallet.balance.amount -= money_in_transaction found_wallet.save() transactions = Transactions.objects.create(**validated_data) transactions.save() return transactions def update(self, instance, validated_data): info = model_meta.get_field_info(instance) category_id = validated_data.get('category') wallet_id = validated_data.get('from_wallet') try: found_category = Categories.objects.get( id=int(category_id)) if category_id is not None else None if found_category: setattr(instance, 'category', found_category) except Exception: raise NotFound('Not found category with id %s' % category_id) try: found_wallet = Wallet.objects.get( id=int(wallet_id)) if wallet_id is not None else None if found_wallet: setattr(instance, 'from_wallet', found_wallet) except Exception: raise NotFound('Not found wallet with id %s' % wallet_id) m2m_fields = [] for attr, value in validated_data.items(): if attr in info.relations and info.relations[attr].to_many: m2m_fields.append((attr, value)) elif attr == 'category' or attr == 'from_wallet': pass else: setattr(instance, attr, value) instance.save() for attr, value in m2m_fields: field = getattr(instance, attr) field.set(value) return instance <file_sep>/backend/moneymon/moneymon/urls.py """moneymon URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from rest_framework import routers from wallet import views as wallet_views from transactions import views as transaction_views router = routers.DefaultRouter(trailing_slash=False) router.register(r'wallet', wallet_views.WalletCreateView, 'wallet') router.register( r'transaction', transaction_views.TransactionsCreateView, 'transaction') router.register( r'statistic', transaction_views.TransactionsViewStatistic, 'transaction') router.register( r'export', transaction_views.ExportTransactionView, 'export') router.register(r'category', wallet_views.CategoryView, 'category') urlpatterns = [ path(r'admin/', admin.site.urls), path(r'auth/', include('djoser.urls')), path(r'auth/', include('rest_framework_social_oauth2.urls')), # path(r'auth/', include('djoser.urls.jwt')), path(r'api/', include(router.urls)) ] <file_sep>/backend/moneymon/transactions/admin.py from django.contrib import admin from .models import Transactions from data_seeder.admin import DataGeneratorAdmin # Register your models here. admin.site.register(Transactions)<file_sep>/frontend/src/pages/Report/index.jsx import React from 'react'; import ReportSummary from '../../components/Report/Summary'; import Row from 'antd/lib/row'; export default function ReportPage(props) { return (<Row justify="start" align='top' style={{ height: 'calc(100vh - 146.1px)' }}> <ReportSummary /> </Row>) }<file_sep>/frontend/Dockerfile # builder FROM node:10-alpine as builder COPY package.json ./ COPY yarn.lock ./ RUN npm install && mkdir /moneymon-ui && mv ./node_modules ./moneymon-ui WORKDIR /moneymon-ui COPY . . RUN npm run build # production FROM nginx:alpine #!/bin/sh COPY nginx.conf /etc/nginx/nginx.conf RUN rm -rf /usr/share/nginx/html/* COPY --from=builder /moneymon-ui/build /usr/share/nginx/html EXPOSE 3001 80 ENTRYPOINT ["nginx", "-g", "daemon off;"]<file_sep>/backend/moneymon/wallet/migrations/0005_auto_20200506_1510.py # Generated by Django 3.0.4 on 2020-05-06 08:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wallet', '0004_wallet_updated_at'), ] operations = [ migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cat_name', models.CharField(max_length=255, unique=True)), ('cat_types', models.CharField(choices=[('bill_utils', 'Bills & Utilities'), ('families', 'Families'), ('education', 'Education'), ('entertainment', 'Entertainment'), ('health', 'Health')], max_length=255)), ], ), migrations.AlterField( model_name='wallet', name='wallet_type', field=models.CharField(choices=[('BASIC', 'Tiền mặt'), ('DIGITAL', 'Ví điện tử'), ('CARD', 'Thẻ ngân hàng'), ('CREDIT', 'Thẻ ghi nợ')], max_length=255), ), ] <file_sep>/backend/moneymon/wallet/permissions.py from rest_framework.permissions import BasePermission, SAFE_METHODS class IsOwnerWalletOrReadOnly(BasePermission): def has_object_permission(self, request, view, obj): print("Checking permission in obj:", obj) if request.method in SAFE_METHODS: return True return obj.user == request.user <file_sep>/frontend/src/components/Report/Summary.jsx import React, { useEffect, useState } from 'react'; import { Tabs } from 'antd'; import SummaryContent from './SumaryContent'; import { getAllUserWallets } from '../../api'; const { TabPane } = Tabs; const ReportSummary = props => { const [list, setList] = useState([]); const [initLoading, setInitLoading] = useState(false); useEffect(() => { const fetchWallets = async () => { setInitLoading(true); const wallets = await getAllUserWallets(); console.log("fetchWallets -> wallets", wallets) setList(wallets); setInitLoading(false); }; fetchWallets(); }, []); return ( <div style={style}> <h1 style={{ fontSize: 24 }}>Budget Report</h1> <Tabs defaultActiveKey="1" tabPosition="left" style={{ height: 'calc(100vh - 140px)' }}> {list.length > 0 && list.map(wallet => ( <TabPane tab={`${wallet.wallet_name}`} key={wallet.id}> <SummaryContent style={{ width: '100%' }} wallet={wallet} /> </TabPane> ))} </Tabs> </div> ) } const style = { textAlign: 'center', width: '100%' } export default ReportSummary<file_sep>/frontend/src/components/Transaction/index.jsx import React, { useEffect, useState } from 'react'; import { FileAddFilled, FileTextFilled } from '@ant-design/icons'; import { useSelector, useDispatch } from 'react-redux'; import { getTransactions, createNewTransaction } from '../../actions/transaction.action'; import { Button, Row, Table, Col } from 'antd'; import columns from './tableColumns'; import CreateTransactionModal from './CreateTransactionModal'; import { exportTransaction } from '../../api'; const Transactions = props => { const dispatch = useDispatch() const transactionData = useSelector(state => state.transactionsReducer); const [visible, setVisible] = useState(false); const handleOk = payload => { console.log('create transaction with payload', payload); dispatch(createNewTransaction(payload)); setVisible(false); } useEffect(() => { dispatch(getTransactions()); }, [dispatch]); const dataSource = transactionData.transactions.length > 0 ? transactionData.transactions.map(transaction => ({ ...transaction, key: transaction.id })) : [] const exportClicks = evt => { console.log('export clicked'); exportTransaction().then(blob => { console.log(blob); const url = window.URL.createObjectURL(blob); const link = document.createElement("a"); // Or maybe get it from the current document link.href = url; link.download = "transaction.xlsx"; link.click(); }) } return ( <Row justify="center" align='middle' style={{ height: 'calc(100vh - 140px)' }}> <Col > <h1>Transactions</h1> <Button type="primary" icon={<FileAddFilled />} onClick={() => setVisible(true)} >Create Transaction</Button> <Button icon={<FileTextFilled />} onClick={exportClicks}>Export</Button> <CreateTransactionModal visible={visible} loading={transactionData.loading} handleOk={handleOk} handleCancel={setVisible} /> <Table bordered={true} dataSource={dataSource} columns={columns} tableLayout='auto' /> </Col> </Row> ) } export default Transactions;<file_sep>/frontend/src/components/Report/SumaryContent.jsx import React, { useState } from 'react'; import { Row, Col, Statistic, Progress } from 'antd'; import CanvasJSReact from '../../libs/canvasjs.react'; import { useEffect } from 'react'; import { getTransactionsFromWallet } from '../../api'; import { mergeDupTransactionByCategory } from '../../utils/transaction.util'; const CanvasJSChart = CanvasJSReact.CanvasJSChart; // const initData = const setOptions = (dataPoints) => ({ animationEnabled: true, exportEnabled: true, theme: "dark2", // "light1", "dark1", "dark2" title: { text: "Rate" }, data: [{ type: "pie", indexLabel: "{label}: {y}VND", startAngle: -90, dataPoints }] }) export default function SummaryContent(props) { const { wallet } = props; const [transactionsWallet, setTransactionsWallet] = useState([]); const [dataPoints, setDataPoints] = useState([{ y: 100, label: "Category Name" }]); // const [options, setOptions] = useState(initOptions({ y: 100, label: "Category Name" })); useEffect(() => { //fetch all transactions of the wallet const fetchTransOfWallet = async () => { const listTransactions = await getTransactionsFromWallet(wallet.id); //remove init wallet transactions const idx = listTransactions.findIndex(tran => tran.category === 1); listTransactions.splice(idx, 1); console.log("fetchTransOfWal -> listTransactions", listTransactions) setTransactionsWallet(listTransactions); } fetchTransOfWallet(); }, []) useEffect(() => { const tempArray = []; const duplicateCat = []; transactionsWallet.forEach((tran => { if (tempArray.includes(tran.category) && !duplicateCat.includes(tran.category)) duplicateCat.push(tran.category); tempArray.push(tran.category); })); console.log("fetchTransOfWal -> duplicateCat", duplicateCat); let newDataPoints = []; transactionsWallet.forEach(tran => { // !tempArray.includes(tran.category); if (!duplicateCat.includes(tran.category)) { let sign = ""; if (tran.action === "IN") sign = "+" else sign = "-"; newDataPoints.push({ label: tran.category_name, y: `${sign}${tran.amount}` }) } }); console.log("fetchTransOfWal -> newDataPoints", newDataPoints) const dataPointsMerged = mergeDupTransactionByCategory(transactionsWallet, duplicateCat); console.log("fetchTransOfWal -> dataPointsMerged", dataPointsMerged) const rest = transactionsWallet .map(tran => tran.action === "IN" ? parseFloat(tran.amount) : -parseFloat(tran.amount)) .reduce((acc, curr) => acc + curr, 0); const used = parseFloat(wallet.balance) + rest; // if(newDataPoints.length===0) setDataPoints([...newDataPoints, ...dataPointsMerged, { y: used, label: "Số dư" }]); }, [transactionsWallet]) return ( <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}> <Col span={12}> <h1>All transactions by category from wallet {wallet.wallet_name}</h1> <CanvasJSChart options={setOptions(dataPoints)} /> </Col> <Col span={12}> <Statistic title="Balance" value={wallet.balance} precision={2} valueStyle={{ color: '#3f8600' }} // prefix={<ArrowUpOutlined />} suffix={wallet.balance_currency} /> <Progress strokeColor={{ '0%': '#108ee9', '100%': '#87d068', }} percent={99.9} status="active" type="circle" /> </Col> </Row> ) }
65c38e5843e1a0271b1960bef1356629be4cef95
[ "JavaScript", "TOML", "Python", "Text", "Dockerfile" ]
59
JavaScript
xuanthu01/MoneyMon
88326f872f1ba65a7208569933d1be057c3d9880
e300801246370c99f8ed853e83250531d8804d36
refs/heads/master
<file_sep>import sqlite3 def DBControl(kategoriSayisi): if(kategoriSayisi) == 0: print("Kategori bulunamadı") return False class Category: def __init__(self,_name,_description): self.Name = _name self.Description = _description def __str__(self): return "Kategori ismi:{}, Aciklama: {}".format(self.Name,self.Description) class DataBase: def __CreateConnection(self): self.Connection = sqlite3.connect("CategorySim.db") self.Cursor = self.Connection.cursor() __query = "create table if not exists Categories (id integer primary key autoincrement,Name text,Description text)" self.Cursor.execute(__query) self.Connection.commit() def __init__(self): self.__CreateConnection() def CloseConnection(self): self.Connection.close() def ShowCategories(self): __query = "select * from Categories" self.Cursor.execute(__query) __categoryList= self.Cursor.fetchall() if (DBControl(len(__categoryList))) == None: for k in __categoryList: kategori = Category(k[1],k[2]) print(kategori) def FindCategory(self,_name): __query = "select * from Categories where Name = ?" self.Cursor.execute(__query,(_name,)) __categoryDefault = self.Cursor.fetchall() if DBControl(len(__categoryDefault))==None: kategori = Category(__categoryDefault[0][1],__categoryDefault[0][2]) print(kategori) def AddCategory(self,veri:Category): __query = "insert into Categories (Name,Description) values (?,?)" self.Cursor.execute(__query,(veri.Name,veri.Description)) self.__Commit() def __Commit(self): __result = input("İşlemi gercekleştirmek istediginize emin misiniz?(E/H)") if __result == "E": self.Connection.commit() else: print("İşlem iptal edildi") def DeleteCategory(self,_name): __categoryDefault = self.FetchDefault(_name) if (DBControl(len(__categoryDefault)))==None: __query ="delete from Categories where Name=?" self.Cursor.execute(__query,(_name,)) self.__Commit() def UpdateCategory(self,_name,newName,newDescription): __categoryDefault = self.FetchDefault(_name) if(DBControl(len(__categoryDefault)))==None: __query="update Categories set Name = ?, Description = ? where Name = ?" self.Cursor.execute(__query,(newName,newDescription,_name)) self.__Commit() def FetchDefault(self,_name): __categoryDefault = "select * from Categories where Name= ?" self.Cursor.execute(__categoryDefault,(_name,)) __categoryDefault = self.Cursor.fetchall() return __categoryDefault <file_sep>def Sil(*abc): pass #*params keyword'u bir fonksiyonun kac parametre alacagından emin olmadıgınız durumlarda kullanılan bir keyword'tur. Böylece fonksiyon 1 parametre de alabilir 100 parametre de alabilir veya hic parametre de almayabilir... Sil("Category","CategoryName","Description") Sil("Book","<NAME>","Poe")
64ab0cd7381233cbdf07103b24cf76a627d8540a
[ "Python" ]
2
Python
CagriYolyapar/Dantex
5ac794aa6cd7ecb2c47012466c35f01e561d6db4
625bce0e11773c2a876de7b0a0195456a39a7ec6
refs/heads/master
<repo_name>maxsubota/webprojectsample<file_sep>/src/main/java/by/subota/max/command/CommandProvider.java package by.subota.max.command; import java.util.HashMap; import java.util.Map; /** * Command Provider */ public class CommandProvider { private static CommandProvider instance = new CommandProvider(); private Map<String, Command> commandMap = new HashMap<>(); public static CommandProvider getInstance() { return instance; } private CommandProvider() { commandMap.put("CommandExample", new CommandExample()); } /** * Return command by name * @param command name * @return command implementation */ public Command takeCommand(String command) { // Provide your code here throw new UnsupportedOperationException(); } } <file_sep>/src/main/java/by/subota/max/dao/Identified.java package by.subota.max.dao; import java.io.Serializable; /** * For identification entity * @param <PK> - type of primary key */ public interface Identified<PK extends Serializable> { /** * Get primary key * @return primary key */ PK getId(); } <file_sep>/src/main/java/by/subota/max/dao/DaoFactory.java package by.subota.max.dao; import by.subota.max.dao.exception.DaoException; import java.io.Serializable; /** * Dao Factory */ public interface DaoFactory { /** * Return implementation of DAO for entity class * @param entityClass - entity class * @return - implementation of DAO for entity class * @throws DaoException - should be clarify */ <T extends Identified<PK>, PK extends Serializable> GenericDao<T, PK> getDao(Class<T> entityClass) throws DaoException; } <file_sep>/src/main/java/by/subota/max/dto/ResponseContent.java package by.subota.max.dto; import by.subota.max.command.Router; /** * Provide response content to View layer */ public class ResponseContent { private Router router; //Provide your code here } <file_sep>/readme.md # Web application sample Base interfaces for developing your app ## Requirements 1. Java - 1.8.x 2. Maven - 3.x.x ## Installation **1. Clone the application** **2. Build and run the app using maven** ```bash mvn clean install mvn tomcat7:run ``` The app will start running at <http://localhost:8080>. <file_sep>/src/main/java/by/subota/max/dao/exception/DaoException.java package by.subota.max.dao.exception; /** * Dao Exception */ public class DaoException extends Exception { public DaoException(String message, Throwable cause) { super(message, cause); } public DaoException(String message) { super(message); } //provide your code here } <file_sep>/src/main/java/by/subota/max/dao/AbstractJdbcDao.java package by.subota.max.dao; import by.subota.max.dao.exception.DaoException; import by.subota.max.dao.exception.PersistException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * Abstract JDBC DAO * @param <T> - Identified entity * @param <PK> - Type primary key of entity */ public abstract class AbstractJdbcDao<T extends Identified<PK>, PK extends Number> implements GenericDao<T, PK> { protected Connection connection; protected abstract List<T> parseResultSet(ResultSet rs) throws SQLException; protected abstract void prepareStatementForInsert(PreparedStatement statement, T object) throws SQLException; protected abstract void prepareStatementForUpdate(PreparedStatement statement, T object) throws SQLException; public abstract String getSelectQuery(); public abstract String getCreateQuery(); public abstract String getUpdateQuery(); public abstract String getDeleteQuery(); @Override @AutoConnection public T getByPK(PK key) throws DaoException { // Write your code here return null; } @Override @AutoConnection public List<T> getAll() throws DaoException { // Write your code here throw new UnsupportedOperationException(); } @Override @AutoConnection public T persist(T object) throws PersistException { // Write your code here throw new UnsupportedOperationException(); } @Override @AutoConnection public void update(T object) throws PersistException { // Write your code here throw new UnsupportedOperationException(); } @Override @AutoConnection public void delete(T object) throws PersistException { // Write your code here throw new UnsupportedOperationException(); } void setConnection(Connection connection) { this.connection = connection; } } <file_sep>/src/main/java/by/subota/max/dao/ConnectionPoolFactory.java package by.subota.max.dao; import by.subota.max.dao.impl.ConnectionPoolImpl; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Connection Pool Factory */ public class ConnectionPoolFactory { private static ConnectionPoolFactory instance; private static Lock lock = new ReentrantLock(); private ConnectionPoolFactory() {} public static ConnectionPoolFactory getInstance() { lock.lock(); try { if (instance == null) { instance = new ConnectionPoolFactory(); } } finally { lock.unlock(); } return instance; } public ConnectionPool getConnectionPool() { return ConnectionPoolImpl.getInstance(); } } <file_sep>/src/main/java/by/subota/max/dao/TransactionManager.java package by.subota.max.dao; import by.subota.max.dao.exception.ConnectionPoolException; import by.subota.max.dao.exception.DaoException; import java.sql.Connection; /** * Implementation of transaction with DAO */ public final class TransactionManager { private Connection proxyConnection; public void begin(GenericDao dao, GenericDao ... daos) throws DaoException { ConnectionPool connectionPool = ConnectionPoolFactory.getInstance().getConnectionPool(); try { proxyConnection = connectionPool.retrieveConnection(); ((AbstractJdbcDao)dao).setConnection(proxyConnection); } catch (ConnectionPoolException e) { throw new DaoException("Failed to get a connection from CP.", e); } //provide your code here throw new UnsupportedOperationException(); } public void end() { //provide your code here throw new UnsupportedOperationException(); } public void commit() { //provide your code here throw new UnsupportedOperationException(); } public void rollback() { //provide your code here throw new UnsupportedOperationException(); } } <file_sep>/src/main/java/by/subota/max/dao/exception/PersistException.java package by.subota.max.dao.exception; /** * Persist Exception */ public class PersistException extends Exception { PersistException(String message, Throwable cause) { super(message, cause); } //provide your code here } <file_sep>/src/main/resources/db.properties driver = com.mysql.jdbc.Driver url = jdbc:mysql://127.0.0.1:3306/db_name user = root password = <PASSWORD> useUnicode = true characterEncoding = utf-8 autoReconnect = true poolCapacity = 20
145ca60c635033407bd50dbfa7b237c03678d176
[ "Markdown", "Java", "INI" ]
11
Java
maxsubota/webprojectsample
b56d540b934c59e38337c3661230aa37ede872df
a0050588b5359c8916ac1a0aa54609fd75034419
refs/heads/master
<repo_name>harlanhong/pythonProject<file_sep>/Keras/Autoencoder.py import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist from keras.models import Model from keras.layers import Dense, Input import matplotlib.pyplot as plt # download the mnist to the path '~/.keras/datasets/' if it is the first time to be called # X shape (60,000 28x28), y shape (10,000, ) (x_train, _), (x_test, y_test) = mnist.load_data() # data pre-processing x_train = x_train.astype('float32') / 255. - 0.5 # minmax_normalized x_test = x_test.astype('float32') / 255. - 0.5 # minmax_normalized x_train = x_train.reshape((x_train.shape[0], -1)) x_test = x_test.reshape((x_test.shape[0], -1)) print(x_train.shape) print(x_test.shape) """ (60000, 784) (10000, 784) """ encoding_dim = 2 input_img = Input(shape=(784,)) #encoder layer encoded = Dense(128,activation='relu')(input_img) encoded = Dense(64,activation='relu')(encoded) encoded = Dense(10,activation='relu')(encoded) encoded_output = Dense(encoding_dim,)(encoded) #decoder layers decoded = Dense(10,activation='relu')(encoded_output) decoded = Dense(64,activation='relu')(decoded) decoded = Dense(128,activation='relu')(decoded) decoded = Dense(784,activation='tanh')(decoded) #construct model autoencoder = Model(inputs=input_img,outputs=decoded) encoder = Model(inputs=input_img,outputs=encoded_output) autoencoder.compile(optimizer='adam',loss='mse') autoencoder.fit(x_train,x_train, nb_epoch=20, batch_size=256, shuffle=True) encoded_imgs = encoder.predict(x_test) plt.scatter(encoded_imgs[:, 0], encoded_imgs[:, 1], c=y_test) plt.colorbar() plt.show()<file_sep>/facc/B01.py import cv2 import numpy as np #去除指定大小的区域 from mpl_toolkits.mplot3d import Axes3D import math import matplotlib.pyplot as plt import facc.HistUtil as histUtil #用来强度分层 def intensitySlicing(img,i): cv2.imshow(str(i),img) sp = img.shape x = np.arange(sp[1]) y = np.arange(sp[0]) X, Y = np.meshgrid(x, y) Z=img fig = plt.figure() ax = Axes3D(fig) ax.contour3D(X, Y, Z, 50, cmap='binary') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z'); plt.show() def RemoveSelectRegion(src, AreaHigh, AreaLow, CheckMode, NeiborMode): RemoveCount = 0 # 新建一幅标签图像初始化为0像素点,为了记录每个像素点检验状态的标签,0代表未检查,1代表正在检查, 2代表检查不合格(需要反转颜色),3代表检查合格或不需检查 # 初始化的图像全部为0,未检查 PointLabel = np.zeros(src.shape, np.uint8) dst = np.zeros(src.shape, np.uint8) sp = src.shape if (CheckMode == 1): # 去除小连通区域的白色点,除去白色的 print("去除小连通域") for i in range(sp[0]): for j in range(sp[1]): if src[i, j] < 10: PointLabel[i, j] = 3 # 将背景黑色点标记为合格,像素为3 else: # 除去黑色的 print("去除孔洞") for i in range(sp[0]): for j in range(sp[1]): if src[i, j] > 10: PointLabel[i, j] = 3 # 如果原图是白色区域,标记为合格,像素为3 NeiborPos = [] # 将邻域压进容器 NeiborPos.append((-1, 0)) NeiborPos.append((1, 0)) NeiborPos.append((0, -1)) NeiborPos.append((0, 1)) if NeiborMode == 1: print("Neighbor mode: 8邻域.") NeiborPos.append((-1, -1)) NeiborPos.append((-1, 1)) NeiborPos.append((1, -1)) NeiborPos.append((1, 1)) else: print("Neighbor mode: 4邻域.") NeihborCount = 4 + 4 * NeiborMode; CurrX = 0 CurrY = 0 for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i, j] == 0: GrowBuffer = [] GrowBuffer.append((i, j)) PointLabel[i, j] = 1 CheckResult = 0 # 在这里说一下,python的for循环有点奇葩,就是范围是静态的,第一次获取到范围值后就不会改变了 z = 0 while z < len(GrowBuffer): for q in range(NeihborCount): CurrX = GrowBuffer[z][0] + NeiborPos[q][0] CurrY = GrowBuffer[z][1] + NeiborPos[q][1] if CurrX >= 0 and CurrX < sp[0] and CurrY >= 0 and CurrY < sp[1]: if PointLabel[CurrX, CurrY] == 0: GrowBuffer.append((CurrX, CurrY)) PointLabel[CurrX, CurrY] = 1 z += 1 # 对整个连通域检查完 if len(GrowBuffer) > AreaHigh or len(GrowBuffer) < AreaLow: CheckResult = 2 else: CheckResult = 1 RemoveCount += 1 for z in range(len(GrowBuffer)): CurrX = GrowBuffer[z][0] CurrY = GrowBuffer[z][1] PointLabel[CurrX, CurrY] += CheckResult CheckMode = 255 * (1 - CheckMode) for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i, j] == 2: dst[i, j] = CheckMode if PointLabel[i, j] == 3: dst[i, j] = src[i, j] return dst #去除二值图像边缘的突出部 def delete_jut(src,uthreshold,vthreshold,type): threshold = 0 dst = src.copy() sp = src.shape height = sp[0] width = sp[1] k = 0 #type = 0 就是消除黑色的突出部 type=1就是消除白色的突出部 mode = (1-type)*255 modeInver = 255-mode for i in range(height-1): for j in range(width-1): #行消除 if dst[i,j]== mode and dst[i,j+1] == modeInver: if j+uthreshold >= width: for k in range(j+1,width): dst[i,k] = mode else: for k in range(j+2,j+uthreshold+1): if dst[i,k] == mode: break if dst[i,k] == mode: for h in range(j+1,k): dst[i,h] = mode #列消除 if dst[i,j] == mode and dst[i+1,j] == modeInver: if i+vthreshold >= height: for k in range(i+1,height): dst[k,j] = mode else: for k in range(i+2,i+vthreshold+1): if dst[k,j] == mode: break if dst[k,j] == mode: for h in range(i+1,k): dst[h,j] = mode #根据需求,强制性去除上下四行 for i in range(2): for j in range(width): dst[i,j] = mode; for i in range(height-1,height-3,-1): for j in range(width): dst[i,j] = mode; return dst def inching(img,rect): x=0 y=0 height=0 width =0 #先对左列进行扫描 #左列扫描区域 left = img[rect[1]:rect[1]+rect[3],rect[0]-5:rect[0]+5] right = img[rect[1]:rect[1]+rect[3],rect[0]+rect[2]-5:rect[0]+rect[2]+5] up = img[rect[1]-3:rect[1]+3,rect[0]:rect[0]+rect[2]] down = img[rect[1]+rect[3]-3:rect[1]+rect[3]+3,rect[0]:rect[0]+rect[2]] anchor = (-1, -1); delta = 0; #自定义卷积核 # kernel = np.zeros((1,3)) # kernel[0,0]=-1;kernel[0,1]=1;kernel[0,2]=0 # dst = cv2.filter2D(left,-1,kernel,anchor=anchor,delta=delta,borderType=cv2.BORDER_DEFAULT) #直接寻找靠近255一半的行或列 #对列 cols = np.sum(left, axis=0) cols = cols/left.shape[0] for i in range(len(cols)): if cols[i]>=200: x = i-5+rect[0] print(i) break; cols = np.sum(right, axis=0) cols = cols/right.shape[0] for i in range(len(cols)-1,-1,-1): if cols[i] >= 200: width = i - 5 + rect[0]+rect[2] -x print(i) break; rows = np.sum(up, axis=1) rows = rows/up.shape[1] for i in range(len(rows)): if rows[i] >= 200: y = i-3+rect[1] break; rows = np.sum(down, axis=1) rows = rows/down.shape[1] for i in range(len(rows)-1,-1,-1): if rows[i] >= 200: height = i-3+rect[1]+rect[3]-y; break; newRect = (x,y,width,height) return newRect def avgGray(img): sp = img.shape sum = 0 for i in range(sp[0]): for j in range(sp[1]): sum+=img[i,j] return sum/(sp[0]*sp[1]) def process(input): #进行截取是为了降低时间和去噪 ROIBGR = input[143:891, 393:1239] #为了方便,我们新建一个与input一样大小的图片; cv2.imshow("ROIsrc",ROIBGR) ROIgray = cv2.cvtColor(ROIBGR, cv2.COLOR_BGR2GRAY) #强度分层 #intensitySlicing(ROIgray) #ROIgray = cv2.medianBlur(ROIgray,3) #因为精度要求很高,所以一切改变图像形态的操作都不能进行 ret, ROI = cv2.threshold(ROIgray, 100, 255, cv2.THRESH_BINARY) #ROI = RemoveSelectRegion(ROI, 500, 0, 0, 1) cv2.imshow("roiBinary",ROI) #第一次获取轮廓,用来矫正矩形 result, contours, hierarchy = cv2.findContours(ROI, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) result = np.zeros(ROI.shape, np.uint8) cv2.drawContours(result,contours,-1,255) cv2.imshow("contours",result) for i in range(len(contours)): rect = cv2.boundingRect(contours[i]) #先判断是圆还是方 if math.fabs(rect[2]-rect[3])>8:#是长方形,进行去毛刺处理 temp = ROI[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]] temp = delete_jut(temp,int(temp.shape[1]*2/5),int(temp.shape[0]*2/5),1) ROI[rect[1]:rect[1] + rect[3], rect[0]:rect[0] + rect[2]]=temp; cv2.imshow("newROI",ROI) # 第二次获取轮廓,用来确定中心点 result, contours, hierarchy = cv2.findContours(ROI, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) result = np.zeros(ROI.shape, np.uint8) cv2.drawContours(result, contours, -1, 255) cv2.imshow("contours2", result) colorlist = [(255,0,0),(0,255,0),(0,0,255),(0,0,0)] for i in range(len(contours)): if cv2.contourArea(contours[i]) < 100: continue rect = cv2.boundingRect(contours[i]) cv2.rectangle(input, (rect[0]+393,rect[1]+143), (rect[0]+rect[2]+393,rect[1]+rect[3]+143), (0,0,255)) if math.fabs(rect[2] - rect[3]) > 8: rect = inching(ROIgray,rect) #intensitySlicing(ROIgray[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]],i) cv2.rectangle(input, (rect[0]+393,rect[1]+143), (rect[0]+rect[2]+393,rect[1]+rect[3]+143), (0,255,0)) cX = int(rect[0]+rect[2]/2) + 393 cY = int(rect[1]+rect[3]/2) + 143 cv2.line(input, (cX, cY - 10), (cX, cY + 10), colorlist[i]) cv2.line(input, (cX - 10, cY), (cX + 10, cY), colorlist[i]) def unitTest(): input = cv2.imread("B01/B01-0" + str(8) + ".bmp", 1) process(input) cv2.imshow("result",input) def allTest(): i = 1 while i<10: print(i) input = cv2.imread("B01/B01-0" + str(i) + ".bmp", 1) process(input) cv2.imwrite("result/B01/B01-0" + str(i) + ".bmp",input) i+=1 if __name__ == '__main__': unitTest() cv2.waitKey(0) <file_sep>/傅里叶变化合集/fft2.py import math import numpy as np if __name__ == '__main__': data=[[1,1,3,2],[3,4,123,154],[55,2,22,233]] fft2 = data.copy() M = 4 N = 3 for u in range(N): for v in range(M): fft2[u][v] = 0+0j for x in range(N): for y in range(M): power = -2*math.pi*(u*x/N+v*y/M) fft2[u][v] +=(data[x][y]*(math.cos(power)+1j*math.sin(power))) print(fft2) <file_sep>/facc/HistUtil.py import cv2 import numpy as np import math #自定义直方图统计 def myCalHist(img): hist = np.zeros([256,1]) sp = img.shape for i in range(sp[0]): for j in range(sp[1]): hist[img[i,j]]+=1 hist[255] = 0 hist[0] = 0 return hist def DrawHist(hist, color,thresh = -1): minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist) histImg = np.zeros([512,256,3], np.uint8) hpt = int(0.9* 256); #cv2.line(histImg, (0, 256), (256, 256), [0,0,255]) for h in range(256): intensity = int(hist[h]*hpt/maxVal) if intensity!=0: cv2.line(histImg,(h,256), (h,256-intensity), color) if thresh != -1: cv2.line(histImg, (thresh, 512), (thresh,0), [0,0,255]) return histImg; #直方图平滑处理 #插值平滑 def interpolation(hist,step): start = int(step - step/2) end = int(256 - step/2) temp =0 res = hist.copy() for i in range(start,end): temp =0 for j in range(int(0-step/2),int(step/2)): temp += hist[i+j] temp /=step res[i] = int(temp) return res #频率滤波 def fourier(hist): ft = hist.copy() N = 256 Cu = 1 for u in range(N): if u == 0: Cu= 1.0/math.sqrt(2) sum = 0 for x in range(N): sum += (hist[x]*math.cos(((2*x)+1)*u*math.pi/(2*N))) temp = Cu*math.sqrt(2.0/N)*sum ft[u] = int(temp) return ft # def fourier(hist,alterComponent): # ft = hist.copy() # N = 256 # Cu = 1 # for u in range(N): # if u == 0: # Cu= 1.0/math.sqrt(2) # sum = 0 # for x in range(N): # theta = ((2*x)+1)*u*math.pi/(2*N) # if theta == 0 or u<alterComponent: # sum += (hist[x]*math.cos(theta)) # temp = Cu*math.sqrt(2.0/N)*sum # ft[u] = int(temp) # return ft def inverFourier(hist): inverseft = hist.copy() N = 256 for x in range(N): sum =(1/math.sqrt(2.0))*hist[0] for u in range(1,N): sum+=hist[u]*math.cos((2*x+1)*u*math.pi/(2*N)) temp = math.sqrt(2.0/N)*sum inverseft[x] = math.fabs(temp) return inverseft #求直方图的导数图 def coefficientHist(hist): res = hist.copy() N = 256 res[0]=0 res[255]=0 for x in range(1,255): res[x]=hist[x+1]-hist[x] return res #迭代最佳阈值 def GetIterativeBestThreshold(hist): X, Iter = 0,0; MinValue, MaxValue=0,0; for MinValue in range(256): if hist[MinValue]!=0: break; for MaxValue in range(255,-1,-1): if hist[MaxValue]!=0: break; if MaxValue == MinValue: return MaxValue; # 图像中只有一个颜色 if MinValue + 1 == MaxValue: return MinValue; # 图像中只有二个颜色 Threshold = MinValue; NewThreshold = (MaxValue + MinValue)/2; while Threshold != NewThreshold: # 当前后两次迭代的获得阈值相同时,结束迭代 SumOne = 0; SumIntegralOne = 0; SumTwo = 0; SumIntegralTwo = 0; Threshold = NewThreshold; for X in range(math.ceil(MinValue),math.ceil(Threshold)):# 根据阈值将图像分割成目标和背景两部分,求出两部分的平均灰度值 SumIntegralOne += hist[X] * X; SumOne += hist[X]; MeanValueOne = SumIntegralOne / SumOne; for X in range(math.ceil(Threshold+1),math.ceil(MaxValue+1)): SumIntegralTwo += hist[X] * X; SumTwo += hist[X]; MeanValueTwo = SumIntegralTwo / SumTwo; NewThreshold = (MeanValueOne + MeanValueTwo)/2; # 求出新的阈值 Iter+=1; if Iter >= 1000: return -1; return Threshold; #OSTU大津法 def GetOSTUThreshold(histGram): X, Y, Amount = 0,0,0; MinValue, MaxValue=0,0; Threshold = 0; for MinValue in range(256): if histGram[MinValue]!=0: break; for MaxValue in range(255,-1,-1): if histGram[MaxValue]!=0: break; if MaxValue == MinValue: return MaxValue; # 图像中只有一个颜色 if MinValue + 1 == MaxValue: return MinValue; # 图像中只有二个颜色 for Y in range(MinValue,MaxValue+1):Amount += histGram[Y];#像素个数 PixelIntegral = 0; for Y in range(MinValue, MaxValue + 1): PixelIntegral += histGram[Y] * Y;#像素总值 SigmaB = -1; PixelBack = 0 PixelIntegralBack=0 for Y in range(MinValue, MaxValue + 1): PixelBack = PixelBack + histGram[Y]; PixelFore = Amount - PixelBack; OmegaBack = float(PixelBack / Amount); OmegaFore = float(PixelFore / Amount); PixelIntegralBack += histGram[Y] * Y; PixelIntegralFore = PixelIntegral - PixelIntegralBack; MicroBack = float(PixelIntegralBack / PixelBack); MicroFore = float(PixelIntegralFore / PixelFore); Sigma = OmegaBack * OmegaFore * (MicroBack - MicroFore) * (MicroBack - MicroFore); if (Sigma > SigmaB): SigmaB = Sigma; Threshold = Y; return Threshold; #力矩保持法 def GetMomentPreservingThreshold(HistGram): X, Y, Index = 0,0,0; Amount = 0; Avec = [0]*256 X2, X1, X0, Min=0,0,0,0; for Y in range(256):Amount+=HistGram[Y] for Y in range(256): Avec[Y]=A(HistGram,Y)/Amount X2 = (B(HistGram, 255) * C(HistGram, 255) - A(HistGram, 255) * D(HistGram, 255)) / ( A(HistGram, 255) * C(HistGram, 255) - B(HistGram, 255) * B(HistGram, 255)); X1 = (B(HistGram, 255) * D(HistGram, 255) - C(HistGram, 255) * C(HistGram, 255)) / ( A(HistGram, 255) * C(HistGram, 255) - B(HistGram, 255) * B(HistGram, 255)); X0 = 0.5 - (B(HistGram, 255) / A(HistGram, 255) + X2 / 2) / math.sqrt(X2 * X2 - 4 * X1); Min = 9999999999 for Y in range(256): if (math.fabs(Avec[Y] - X0) < Min): Min = math.fabs(Avec[Y] - X0); Index = Y; return Index def A(hist,index): sum = 0 for Y in range(index+1): sum+=hist[Y] return sum; def B(hist,index): sum = 0 for Y in range(index + 1): sum += hist[Y]*Y return sum; def C(hist,index): sum = 0 for Y in range(index + 1): sum += Y*Y*hist[Y] return sum; def D(hist,index): sum = 0 for Y in range(index + 1): sum += Y*Y*Y*hist[Y] return sum; #谷底最小值 def GetMinimumThreshold(HistGram): Y, Iter = 0,0; HistGramC = HistGram.copy(); HistGramCC = HistGram.copy(); # 通过三点求均值来平滑直方图 while IsDimodal(HistGramCC) == False: # 判断是否已经是双峰的图像了 HistGramCC[0] = (HistGramC[0] + HistGramC[0] + HistGramC[1]) / 3; # 第一点 for Y in range(1,255): HistGramCC[Y] = (HistGramC[Y - 1] + HistGramC[Y] + HistGramC[Y + 1]) / 3; # 中间的点 HistGramCC[255] = (HistGramC[254] + HistGramC[255] + HistGramC[255]) / 3; # 最后一点 HistGramC = HistGramCC.copy(); Iter+=1; if (Iter >= 1000): return -1; # 直方图无法平滑为双峰的,返回错误代码 # 阈值极为两峰之间的最小值 Peakfound = False; for Y in range(1, 255): if (HistGramCC[Y - 1] < HistGramCC[Y] and HistGramCC[Y + 1] < HistGramCC[Y]): Peakfound = True; if (Peakfound == True and HistGramCC[Y - 1] >= HistGramCC[Y] and HistGramCC[Y + 1] >= HistGramCC[Y]): histImg = DrawHist(HistGramCC, [255, 255, 255],Y-1) cv2.imshow("newHist", histImg) return Y - 1; return -1; def IsDimodal(HistGram): # 对直方图的峰进行计数,只有峰数位2才为双峰 Count = 0; for Y in range(1, 255): if (HistGram[Y - 1] < HistGram[Y] and HistGram[Y + 1] < HistGram[Y]): Count +=1; if (Count > 2): return False; if (Count == 2): return True; else: return False; def adaptiveThreshold(img): hist = myCalHist(img) histImg = DrawHist(hist, [255, 255, 255]) cv2.imshow("histInit", histImg) min, max, hist = removeNoiseOfHist(hist) histImg = DrawHist(hist, [255, 255, 255]) cv2.imshow("histIMG", histImg) thresh = GetMinimumThreshold(hist) return min, max, thresh + 15 def removeNoiseOfHist(hist): result = hist.copy() counter = 0 for i in range(255,-1,-1): if result[i] != 0: counter += 1 result[i] = 0 if counter == 10: break counter = 0 for i in range(255): if result[i] !=0: counter+=1 result[i] = 0 if counter == 10: break for i in range(255): if result[i]<50: result[i] = 0 else: break for i in range(255,-1,-1): if result[i]<50: result[i] = 0 else: break for i in range(70): if result[i]>500: break result[i]=0 min ,max =0,0 for i in range(255): if result[i]!=0: min = i; break for i in range(255,-1,-1): if result[i]!=0: max = i; break return min,max,result def subtractFun(src,erode_ouput,threshold): result = np.zeros(src.shape,np.int64) sp = src.shape for i in range(sp[0]): for j in range(sp[1]): if src[i,j,0]-erode_ouput[i,j,0]>threshold or src[i, j, 1] - erode_ouput[i, j, 1] > threshold or src[i, j, 2] - erode_ouput[i, j,2] > threshold: result[i,j,0] =255 result[i,j,1] =255 result[i,j,2] =255 else: result[i,j,0]=0 result[i,j,1]=0 result[i,j,2]=0 return result def removeNoiseOfHist(hist): result = hist.copy() counter = 0 min=0;max =0 for i in range(256): counter+=hist[i] if counter>200: break else: result[i]=0; min = i counter = 0 for i in range(255,-1,-1): counter+=hist[i] if counter>200: break else: result[i]=0; max = i return min,max,result def getSkeleton(img,removedetails_times,erode_times):#输入为去除背景后的bgr图 element = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5)) img = cv2.erode(img,element,iterations=2) erode_output = img.copy() outLineResult = img.copy() openResult = img.copy() closeResult = img.copy() #噪声滤除 if removedetails_times ==1: closeResult=cv2.morphologyEx(img,cv2.MORPH_CLOSE,element,iterations=1) openResult = cv2.morphologyEx(closeResult,cv2.MORPH_OPEN,element,iterations=1) elif removedetails_times == 2: openResult = cv2.morphologyEx(img,cv2.MORPH_OPEN,element,iterations=1) closeResult=cv2.morphologyEx(openResult,cv2.MORPH_CLOSE,element,iterations=1) openResult = cv2.morphologyEx(closeResult,cv2.MORPH_OPEN,element,iterations=1) closeResult=cv2.morphologyEx(openResult,cv2.MORPH_CLOSE,element,iterations=1) #腐蚀操作 erode_output = cv2.erode(closeResult,element,erode_times) ret,closeResult = cv2.threshold(closeResult,5,255,cv2.THRESH_BINARY) ret,erode_output = cv2.threshold(erode_output,5,255,cv2.THRESH_BINARY) outLineResult = cv2.subtract(closeResult,erode_output) result = cv2.medianBlur(outLineResult,3) if result.ndim >1: result = cv2.cvtColor(result,cv2.COLOR_BGR2GRAY) ret,result = cv2.threshold(result,100,255,cv2.THRESH_BINARY_INV) result = cv2.erode(result,element,iterations=1) return result #去除指定大小的区域 def RemoveSelectRegion(src,AreaHigh,AreaLow,CheckMode,NeiborMode): RemoveCount = 0 # 新建一幅标签图像初始化为0像素点,为了记录每个像素点检验状态的标签,0代表未检查,1代表正在检查, 2代表检查不合格(需要反转颜色),3代表检查合格或不需检查 # 初始化的图像全部为0,未检查 PointLabel = np.zeros(src.shape,np.uint8) dst = np.zeros(src.shape, np.uint8) sp = src.shape if(CheckMode == 1):#去除小连通区域的白色点,除去白色的 print("去除小连通域") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]<10: PointLabel[i,j] = 3#将背景黑色点标记为合格,像素为3 else: #除去黑色的 print("去除孔洞") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]>10: PointLabel[i,j] = 3#如果原图是白色区域,标记为合格,像素为3 NeiborPos = [] #将邻域压进容器 NeiborPos.append((-1,0)) NeiborPos.append((1, 0)) NeiborPos.append((0, -1)) NeiborPos.append((0, 1)) if NeiborMode ==1: print("Neighbor mode: 8邻域.") NeiborPos.append((-1, -1)) NeiborPos.append((-1, 1)) NeiborPos.append((1, -1)) NeiborPos.append((1, 1)) else: print("Neighbor mode: 4邻域.") NeihborCount = 4+4*NeiborMode; CurrX = 0 CurrY =0 for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 0: GrowBuffer = [] GrowBuffer.append((i,j)) PointLabel[i,j] = 1 CheckResult = 0 #在这里说一下,python的for循环有点奇葩,就是范围是静态的,第一次获取到范围值后就不会改变了 z=0 while z<len(GrowBuffer): for q in range(NeihborCount): CurrX = GrowBuffer[z][0]+NeiborPos[q][0] CurrY = GrowBuffer[z][1]+NeiborPos[q][1] if CurrX >=0 and CurrX < sp[0] and CurrY >=0 and CurrY<sp[1]: if PointLabel[CurrX,CurrY] == 0: GrowBuffer.append((CurrX,CurrY)) PointLabel[CurrX,CurrY] = 1 z += 1 #对整个连通域检查完 if len(GrowBuffer)> AreaHigh or len(GrowBuffer) < AreaLow: CheckResult = 2 else: CheckResult = 1 RemoveCount +=1 for z in range(len(GrowBuffer)): CurrX = GrowBuffer[z][0] CurrY = GrowBuffer[z][1] PointLabel[CurrX,CurrY] += CheckResult CheckMode = 255*(1-CheckMode) for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 2: dst[i,j] = CheckMode if PointLabel[i,j] == 3: dst[i,j] = src[i,j] return dst <file_sep>/faceThreshold/globalThresholdMothed.py import cv2 import math import numpy as np def skinModel(srcImg): img = srcImg.copy() rows, cols, channels = img.shape # light compensation gamma = 0.95 for r in range(rows): for c in range(cols): # get values of blue, green, red B = img.item(r, c, 0) G = img.item(r, c, 1) R = img.item(r, c, 2) # gamma correction B = int(B ** gamma) G = int(G ** gamma) R = int(R ** gamma) # set values of blue, green, red img.itemset((r, c, 0), B) img.itemset((r, c, 1), G) img.itemset((r, c, 2), R) ############################################################################### # convert color space from rgb to ycbcr imgYcc = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) # convert color space from bgr to rgb img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # prepare an empty image space imgSkin = np.zeros(img.shape, np.uint8) # copy original image imgSkin = np.zeros((img.shape[0],img.shape[1]),np.uint8) ################################################################################ # define variables for skin rules Wcb = 46.97 Wcr = 38.76 WHCb = 14 WHCr = 10 WLCb = 23 WLCr = 20 Ymin = 16 Ymax = 235 Kl = 125 Kh = 188 WCb = 0 WCr = 0 CbCenter = 0 CrCenter = 0 ################################################################################ skinCounter=0 for r in range(rows): for c in range(cols): # non-skin area if skin equals 0, skin area otherwise skin = 0 ######################################################################## # color space transformation # get values from ycbcr color space Y = imgYcc.item(r, c, 0) Cr = imgYcc.item(r, c, 1) Cb = imgYcc.item(r, c, 2) if Y < Kl: WCr = WLCr + (Y - Ymin) * (Wcr - WLCr) / (Kl - Ymin) WCb = WLCb + (Y - Ymin) * (Wcb - WLCb) / (Kl - Ymin) CrCenter = 154 - (Kl - Y) * (154 - 144) / (Kl - Ymin) CbCenter = 108 + (Kl - Y) * (118 - 108) / (Kl - Ymin) elif Y > Kh: WCr = WHCr + (Y - Ymax) * (Wcr - WHCr) / (Ymax - Kh) WCb = WHCb + (Y - Ymax) * (Wcb - WHCb) / (Ymax - Kh) CrCenter = 154 + (Y - Kh) * (154 - 132) / (Ymax - Kh) CbCenter = 108 + (Y - Kh) * (118 - 108) / (Ymax - Kh) if Y < Kl or Y > Kh: Cr = (Cr - CrCenter) * Wcr / WCr + 154 Cb = (Cb - CbCenter) * Wcb / WCb + 108 ######################################################################## # skin color detection #if Cb >= 80 and Cb <= 127 and Cr >= 141 and Cr <= 173: if Cb >= 80 and Cb <= 127 and Cr >= 133 and Cr <= 177: skin = 1 # print 'Skin detected!' if 0 == skin: imgSkin[r,c] = 0 else: imgSkin[r,c] = 255 skinCounter+=1 # display original image and skin image return skinCounter,imgSkin def globalThreshod(inputImg): face_cascade = cv2.CascadeClassifier("data/haarcascades/haarcascade_frontalface_alt2.xml") Y=[0] #inputImg = cv2.resize(inputImg,(int(inputImg.shape[1]/2),int(inputImg.shape[0]/2))) ycrcb = cv2.cvtColor(inputImg,cv2.COLOR_RGB2YCrCb) #保存亮度通道 gr = ycrcb[:,:,0] faces = face_cascade.detectMultiScale(gr, 1.3, 5) if len(faces)<1: return cv2.cvtColor(inputImg,cv2.COLOR_BGR2GRAY) facemax = -1 for i, (x, y, w, h) in enumerate(faces): if w*h>facemax: facemax=w*h ansface = [x,y,w,h] avgback = 0 s =1;ct =1 for i in range(ansface[1]): for j in range(gr.shape[1]): s+=gr[i,j] ct+=1 avgback = s/ct mask1 = np.zeros((inputImg.shape[0] + 2, inputImg.shape[1] + 2), np.uint8) cv2.floodFill(inputImg,mask1,(ansface[0],ansface[1]),(255, 255, 255), (3, 3, 3), (3, 3, 3)) ycrcb = cv2.cvtColor(inputImg,cv2.COLOR_RGB2YCrCb) # for i in range(ycrcb.shape[0]): # for j in range(ycrcb.shape[1]): # cr = ycrcb[i,j,1] # cb = ycrcb[i,j,2] # if 77<=cr and cr<=127 and 133<=cb and cb<=173: # inputImg[i,j]=(255,255,255) # else: # inputImg[i, j]=(0,0,0) skinCounter,skin = skinModel(inputImg) for i in range(skin.shape[0]): for j in range(skin.shape[1]): if skin[i,j]>100: inputImg[i, j] = (255, 255, 255) else: inputImg[i, j] = (0, 0, 0) resolution = 1.6 ansface[0] = int(ansface[0]-ansface[2]*((resolution-1)/2)) ansface[1] = int(ansface[1]-ansface[3]*((resolution-1)/2)) ansface[2] = int(ansface[2]*resolution) ansface[3] = int(ansface[3]*resolution*0.85) if ansface[0]<0: ansface[2]=ansface[2]+ansface[0] ansface[0]=0 if ansface[1]<0: ansface[3]=ansface[3]+ansface[1] ansface[1]=0 if ansface[2]+ansface[0]>=inputImg.shape[1]: ansface[2]=inputImg.shape[1]-ansface[0]-1 if ansface[3]+ansface[1]>=inputImg.shape[0]: ansface[3] = inputImg.shape[0]-ansface[1]-1 print(ansface) inputROI = inputImg[ansface[1]:ansface[1]+ansface[3],ansface[0]:ansface[0]+ansface[2]] grROI = gr[ansface[1]:ansface[1]+ansface[3],ansface[0]:ansface[0]+ansface[2]] cv2.imshow("inputROI",inputROI) cv2.imshow("grROI",grROI) temp = cv2.cvtColor(inputROI,cv2.COLOR_RGB2GRAY) facebin = cv2.cvtColor(inputROI,cv2.COLOR_RGB2GRAY) binary, contours, hierarchy = cv2.findContours(temp, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) temp = grROI.copy() contour_ok = 0 for c in range(len(contours)-1,-1,-1): result = cv2.convexHull(contours[c]) if cv2.pointPolygonTest(result,(ansface[3]/2,ansface[2]/2),0)==1: contour_ok = 1 py =0;s=0;ct =1; for i in range(temp.shape[0]): for j in range(temp.shape[1]): if cv2.pointPolygonTest(result,(i,j),0)==1: if facebin[i,j]: s = s+temp[i,j] ct+=1 Y[py] = temp[i,j] Y.append(0) py+=1 Y.sort() out = [0]*300 for i in range(Y.__len__()): out[Y[i]]+=1 avg = s/ct mask = cv2.Canny(temp,avgback,avgback*2) element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) mask = cv2.dilate(mask,element) cv2.imshow("cannyMask",mask) ret,temp = cv2.threshold(temp,avgback*avgback*0.9/1000+0.9*(avg+Y[int(py/2)])*(avg+Y[int(py/2)])/1000,255,cv2.THRESH_BINARY) for i in range(temp.shape[0]): for j in range(temp.shape[1]): if cv2.pointPolygonTest(result,(i,j),0)!=1: if temp[i,j]>avgback: temp[i,j]=255 else: temp[i,j]=0 if mask[i,j]: temp[i,j]=0 break if(contour_ok == 0): py=0 s=0 ct =1 for i in range(temp.shape[0]): for j in range(temp.shape[1]): if facebin[i,j]: s=s+temp[i,j] ct+=1 Y[py] = temp[i, j] Y.append(0) py+=1 Y.sort() out=[0]*300 for i in range(Y.__len__()): out[Y[i]]+=1 avg=s/ct mask = cv2.Canny(temp, avgback, avgback * 2) element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) mask = cv2.dilate(mask, element) cv2.imshow("cannyMask", mask) ret, temp = cv2.threshold(temp, avgback * avgback * 0.9 / 1000 + 0.9 * (avg + Y[int(py / 2)]) * ( avg + Y[int(py / 2)]) / 1000, 255, cv2.THRESH_BINARY) temp = cv2.medianBlur(temp,3) return temp if __name__ == '__main__': img = cv2.imread("imageTailor/1 (156).jpg") result = globalThreshod(img) cv2.imshow("result",result) cv2.waitKey(0) <file_sep>/faceFeature/partitionMethod.py # encoding:utf-8 import cv2 import numpy as np import math import faceFeature.HistUtil as histUtil import faceFeature.globalThresholdMothed as globalThresholdMothod import faceFeature.nonSkinMethod as nonSkinMode #检测人脸 def detectFaces(srcImg): img = srcImg.copy() #print 1 face_cascade = cv2.CascadeClassifier("data/haarcascades/haarcascade_frontalface_default.xml") if img.ndim == 3: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: gray = img faces = face_cascade.detectMultiScale(gray, 1.3, 5)#1.3and5 counts to the result of face recognation return faces #在人脸的基础上检测眼睛 def detectEyes(srcImg): src = srcImg.copy() faces = detectFaces(src) eye_cascade = cv2.CascadeClassifier('data/haarcascades_cuda/haarcascade_eye_tree_eyeglasses.xml') gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) result = [[]] for j,(x,y,w,h) in enumerate(faces): cv2.rectangle(src, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = src[y:y + h,x:x + w] # 检测视频中脸部的眼睛,并用vector保存眼睛的坐标、大小(用矩形表示) eyes = eye_cascade.detectMultiScale(roi_gray) #眼睛检测 #选择最大的两个框当成眼睛 max = 0 temp = [] index = 0 for i,(ex,ey,ew,eh) in enumerate(eyes): if ew*eh>max and ex<w and ey<h/2: max = ew*eh index = i temp = (ex+x,ey+y,ew,eh) if index != 0: result[j].append(temp) cv2.rectangle(src, (temp[0], temp[1]), (temp[0] + temp[2], temp[1] + temp[3]), (0, 255, 0), 2) max = 0 temp = [] #用来确认是否找到眼睛 flag = 0 for i,(ex,ey,ew,eh) in enumerate(eyes): if ew*eh>max and i != index and ex<w and ey<h/2: print(ex,ey,x+w,y+h/2) max = ew*eh flag = 1 temp = (ex+x,ey+y,ew,eh) if flag == 1: result[j].append(temp) cv2.rectangle(src, (temp[0], temp[1]), (temp[0] + temp[2], temp[1] + temp[3]), (0, 255, 0), 2) #cv2.imshow("eye",src) return faces,result #肤色检测 def skinModel(srcImg): img = srcImg.copy() rows, cols, channels = img.shape # light compensation gamma = 0.95 for r in range(rows): for c in range(cols): # get values of blue, green, red B = img.item(r, c, 0) G = img.item(r, c, 1) R = img.item(r, c, 2) # gamma correction B = int(B ** gamma) G = int(G ** gamma) R = int(R ** gamma) # set values of blue, green, red img.itemset((r, c, 0), B) img.itemset((r, c, 1), G) img.itemset((r, c, 2), R) ############################################################################### # convert color space from rgb to ycbcr imgYcc = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) # convert color space from bgr to rgb img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # prepare an empty image space imgSkin = np.zeros(img.shape, np.uint8) # copy original image imgSkin = np.zeros((img.shape[0],img.shape[1]),np.uint8) ################################################################################ # define variables for skin rules Wcb = 46.97 Wcr = 38.76 WHCb = 14 WHCr = 10 WLCb = 23 WLCr = 20 Ymin = 16 Ymax = 235 Kl = 125 Kh = 188 WCb = 0 WCr = 0 CbCenter = 0 CrCenter = 0 ################################################################################ skinCounter=0 for r in range(rows): for c in range(cols): # non-skin area if skin equals 0, skin area otherwise skin = 0 ######################################################################## # color space transformation # get values from ycbcr color space Y = imgYcc.item(r, c, 0) Cr = imgYcc.item(r, c, 1) Cb = imgYcc.item(r, c, 2) if Y < Kl: WCr = WLCr + (Y - Ymin) * (Wcr - WLCr) / (Kl - Ymin) WCb = WLCb + (Y - Ymin) * (Wcb - WLCb) / (Kl - Ymin) CrCenter = 154 - (Kl - Y) * (154 - 144) / (Kl - Ymin) CbCenter = 108 + (Kl - Y) * (118 - 108) / (Kl - Ymin) elif Y > Kh: WCr = WHCr + (Y - Ymax) * (Wcr - WHCr) / (Ymax - Kh) WCb = WHCb + (Y - Ymax) * (Wcb - WHCb) / (Ymax - Kh) CrCenter = 154 + (Y - Kh) * (154 - 132) / (Ymax - Kh) CbCenter = 108 + (Y - Kh) * (118 - 108) / (Ymax - Kh) if Y < Kl or Y > Kh: Cr = (Cr - CrCenter) * Wcr / WCr + 154 Cb = (Cb - CbCenter) * Wcb / WCb + 108 ######################################################################## # skin color detection #if Cb >= 80 and Cb <= 127 and Cr >= 141 and Cr <= 173: if Cb >= 80 and Cb <= 127 and Cr >= 133 and Cr <= 177: skin = 1 # print 'Skin detected!' if 0 == skin: imgSkin[r,c] = 0 else: imgSkin[r,c] = 255 skinCounter+=1 # display original image and skin image return skinCounter,imgSkin #通过漫水填充去除背景 def removeBackground(srcImg,color=(255,255,255)): img = srcImg.copy() sp = img.shape mask = np.zeros((img.shape[0]+2,img.shape[1]+2),np.uint8) mask1 = np.zeros((img.shape[0]+2,img.shape[1]+2),np.uint8) cv2.floodFill(img, mask, (3, 3), color, (3, 3, 3), (3, 3, 3), 8) cv2.floodFill(img,mask1,(sp[1]-3,3),color, (3, 3, 3), (3, 3, 3), 8) #img = myFloodFill(img,mask,(5,5),(3, 3, 3), (3, 3, 3), 8) #mask = np.zeros((img.shape[0]+2,img.shape[1]+2),np.uint8) #cv2.floodFill(img, mask, (5,img.shape[0]-5), (255, 255, 255), (3, 3, 3), (3, 3, 3), 8) cv2.imshow("floodfill", img) return img #通过人脸检测裁剪人脸 def tailorImg(img,faces): if len(faces) == 1 or len(faces)>1: for i,(x,y,w,h) in enumerate(faces): #注意不要越界 new_x = x - int(w/3) if x - int(w/3)>0 else 0 new_y = y - int(h/3) if y - int(h/3)>0 else 0 new_w = w +int(2/3*w) if new_x+w+int(2/3*w)<img.shape[1] else img.shape[1]-new_x new_h = h +int(2/3*h) if new_y+h +int(2/3*h)<img.shape[0] else img.shape[0]-new_y new_img = img[new_y:new_y+new_h,new_x:new_x+new_w] return new_img #计算肤色部分的平均灰度 def meanBrightness(imgSKIN,imgGRAY): sp = imgSKIN.shape brightness = 0 count = 0 for i in range(sp[0]): for j in range(sp[1]): if imgSKIN[i,j] >100:# and imgGRAY[i,j]<err_mean[1]+70: brightness += imgGRAY[i,j] count +=1 if count !=0: return count,brightness/count else: return count,0 #计算全局平均肤色值(包括背景) def computAvg(imgGray): sp = imgGray.shape avg = 0 counter = 0 for i in range(sp[0]): for j in range(sp[1]): avg+=imgGray[i,j] counter+=1 return avg/counter #获取最大的轮廓区域 def getMaxArea(new_skin): img,contours, hierarchy = cv2.findContours(new_skin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) maxValue = 0 if len(contours) == 1: return 1,cv2.contourArea(contours[0]) else: for i,contour in enumerate(contours): if cv2.contourArea(contour)>maxValue: maxValue = cv2.contourArea(contour) return len(contours),maxValue #轮廓完善,因为计算量过大,所以不采用这种方法,而是采用 def skeletonComplete(imgResult,imgSKIN,imgFace): kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) new_skin = imgSKIN new_skin = cv2.medianBlur(new_skin,3) new_skin = cv2.dilate(new_skin, kernel) new_skin = cv2.erode(new_skin, kernel) new_skin = cv2.dilate(new_skin, kernel) new_skin = cv2.erode(new_skin, kernel) new_skin = cv2.dilate(new_skin, kernel) new_skin = cv2.dilate(new_skin, kernel) new_skin = cv2.erode(new_skin, kernel) new_skin = cv2.erode(new_skin, kernel) new_skin = cv2.erode(new_skin, kernel) new_skin = cv2.dilate(new_skin, kernel) new_skin = RemoveSmallRegion(new_skin,3000,0,1) count,maxth = getMaxArea(new_skin) cv2.imshow("beforeRemoveLargestArea",new_skin) print("最大面积:",maxth,count) if count != 1: new_skin = RemoveSmallRegion(new_skin,maxth-1000,1,1) cv2.imshow("new_skin",new_skin) if count == 1 and maxth > 3/5*(new_skin.shape[0]*new_skin.shape[1]): print("轮廓面积过大,不认为是正常的轮廓!") result = imgResult else: #binary, contours, hierarchy = cv2.findContours(new_skin, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) #cv2.drawContours(binary, contours, -1, (0, 0, 255), 3) #cv2.imshow("inver",binary) img = cv2.GaussianBlur(new_skin, (3, 3), 0) # 高斯平滑处理原图像降噪 canny = cv2.Canny(img, 50, 150) # apertureSize默认为3 ret,skeleton = cv2.threshold(canny,100,255,cv2.THRESH_BINARY_INV) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) skeleton = cv2.erode(skeleton, kernel) #skeleton = cv2.erode(skeleton, kernel) result = cv2.bitwise_and(skeleton,imgResult) cv2.imshow("skeletonComplete",result) return result #去除二值图像边缘的突出部 def delete_jut(src,uthreshold,vthreshold,type): threshold = 0 dst = src.copy() sp = src.shape height = sp[0] width = sp[1] k = 0 mode = (1-type)*255 modeInver = 255-mode for i in range(height-1): for j in range(width-1): #行消除 if dst[i,j]== mode and dst[i,j+1] == modeInver: if j+uthreshold >= width: for k in range(j+1,width): dst[i,k] = mode else: for k in range(j+2,j+uthreshold+1): if dst[i,k] == mode: break if dst[i,k] == mode: for h in range(j+1,k): dst[i,h] = mode #列消除 if dst[i,j] == mode and dst[i+1,j] == modeInver: if i+vthreshold >= height: for k in range(i+1,height): dst[k,j] = mode else: for k in range(i+2,i+vthreshold+1): if dst[k,j] == mode: break if dst[k,j] == mode: for h in range(i+1,k): dst[h,j] = mode return dst #对图片进行处理 #去除小区域的 def RemoveSmallRegion(src,AreaLimit,CheckMode,NeiborMode): RemoveCount = 0 # 新建一幅标签图像初始化为0像素点,为了记录每个像素点检验状态的标签,0代表未检查,1代表正在检查, 2代表检查不合格(需要反转颜色),3代表检查合格或不需检查 # 初始化的图像全部为0,未检查 PointLabel = np.zeros(src.shape,np.uint8) dst = np.zeros(src.shape, np.uint8) sp = src.shape if(CheckMode == 1):#去除小连通区域的白色点,除去白色的 print("去除小连通域") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]<10: PointLabel[i,j] = 3#将背景黑色点标记为合格,像素为3 else: #除去黑色的 print("去除孔洞") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]>10: PointLabel[i,j] = 3#如果原图是白色区域,标记为合格,像素为3 NeiborPos = [] #将邻域压进容器 NeiborPos.append((-1,0)) NeiborPos.append((1, 0)) NeiborPos.append((0, -1)) NeiborPos.append((0, 1)) if NeiborMode ==1: print("Neighbor mode: 8邻域.") NeiborPos.append((-1, -1)) NeiborPos.append((-1, 1)) NeiborPos.append((1, -1)) NeiborPos.append((1, 1)) else: print("Neighbor mode: 4邻域.") NeihborCount = 4+4*NeiborMode; CurrX = 0 CurrY =0 for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 0: GrowBuffer = [] GrowBuffer.append((i,j)) PointLabel[i,j] = 1 CheckResult = 0 #在这里说一下,python的for循环有点奇葩,就是范围是静态的,第一次获取到范围值后就不会改变了 z=0 while z<len(GrowBuffer): for q in range(NeihborCount): CurrX = GrowBuffer[z][0]+NeiborPos[q][0] CurrY = GrowBuffer[z][1]+NeiborPos[q][1] if CurrX >=0 and CurrX < sp[0] and CurrY >=0 and CurrY<sp[1]: if PointLabel[CurrX,CurrY] == 0: GrowBuffer.append((CurrX,CurrY)) PointLabel[CurrX,CurrY] = 1 z += 1 #对整个连通域检查完 if len(GrowBuffer)>AreaLimit: CheckResult = 2 else: CheckResult = 1 RemoveCount +=1 for z in range(len(GrowBuffer)): CurrX = GrowBuffer[z][0] CurrY = GrowBuffer[z][1] PointLabel[CurrX,CurrY] += CheckResult CheckMode = 255*(1-CheckMode) for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 2: dst[i,j] = CheckMode if PointLabel[i,j] == 3: dst[i,j] = src[i,j] return dst #去除指定大小的区域 def RemoveSelectRegion(src,AreaHigh,AreaLow,CheckMode,NeiborMode): RemoveCount = 0 # 新建一幅标签图像初始化为0像素点,为了记录每个像素点检验状态的标签,0代表未检查,1代表正在检查, 2代表检查不合格(需要反转颜色),3代表检查合格或不需检查 # 初始化的图像全部为0,未检查 PointLabel = np.zeros(src.shape,np.uint8) dst = np.zeros(src.shape, np.uint8) sp = src.shape if(CheckMode == 1):#去除小连通区域的白色点,除去白色的 print("去除小连通域") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]<10: PointLabel[i,j] = 3#将背景黑色点标记为合格,像素为3 else: #除去黑色的 print("去除孔洞") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]>10: PointLabel[i,j] = 3#如果原图是白色区域,标记为合格,像素为3 NeiborPos = [] #将邻域压进容器 NeiborPos.append((-1,0)) NeiborPos.append((1, 0)) NeiborPos.append((0, -1)) NeiborPos.append((0, 1)) if NeiborMode ==1: print("Neighbor mode: 8邻域.") NeiborPos.append((-1, -1)) NeiborPos.append((-1, 1)) NeiborPos.append((1, -1)) NeiborPos.append((1, 1)) else: print("Neighbor mode: 4邻域.") NeihborCount = 4+4*NeiborMode; CurrX = 0 CurrY =0 for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 0: GrowBuffer = [] GrowBuffer.append((i,j)) PointLabel[i,j] = 1 CheckResult = 0 #在这里说一下,python的for循环有点奇葩,就是范围是静态的,第一次获取到范围值后就不会改变了 z=0 while z<len(GrowBuffer): for q in range(NeihborCount): CurrX = GrowBuffer[z][0]+NeiborPos[q][0] CurrY = GrowBuffer[z][1]+NeiborPos[q][1] if CurrX >=0 and CurrX < sp[0] and CurrY >=0 and CurrY<sp[1]: if PointLabel[CurrX,CurrY] == 0: GrowBuffer.append((CurrX,CurrY)) PointLabel[CurrX,CurrY] = 1 z += 1 #对整个连通域检查完 if len(GrowBuffer)> AreaHigh or len(GrowBuffer) < AreaLow: CheckResult = 2 else: CheckResult = 1 RemoveCount +=1 for z in range(len(GrowBuffer)): CurrX = GrowBuffer[z][0] CurrY = GrowBuffer[z][1] PointLabel[CurrX,CurrY] += CheckResult CheckMode = 255*(1-CheckMode) for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 2: dst[i,j] = CheckMode if PointLabel[i,j] == 3: dst[i,j] = src[i,j] return dst #阈值化 def myThreshold(imgGray,imgSkin,skinPoint,thresh,globalAvg=0,localAvg=0): #对每一个局部进行阈值处理,在这里,对各个因素加以考虑,下面列举几种情况 #是皮肤且应该阈值化为白色的但是因为肤色偏暗 #是皮肤但是因为肤色模型的原因,检测为非皮肤,应该阈值化为白色 #非皮肤但是被肤色模型判定为肤色,例如眉毛、额头上的头发,这些应该阈值化为黑色 #非皮肤且肤色模型检测正确,但是因为灰度值很高,很难阈值化为黑色 sp = imgGray.shape dst = imgGray.copy() #print(thresh,globalAvg,localAvg) if globalAvg<135: for i in range(sp[0]): for j in range(sp[1]): if imgSkin[i,j] >100: if imgGray[i,j]>thresh:# and imgGray[i,j]>globalAvg-25: dst[i,j] = 255 else: dst[i,j] = 0 else: for i in range(sp[0]): for j in range(sp[1]): if imgSkin[i,j] >100: if imgGray[i,j]>thresh and imgGray[i,j]>(globalAvg+localAvg)/2.25: dst[i,j] = 255 else: dst[i,j] = 0 return dst #计算图片中边缘点的个数 def computeEdgesPoint(img): sp = img.shape point = 0 sum =0 for i in range(sp[0]): for j in range(sp[1]): if img[i,j]>100: point +=1 sum +=1 temp = point/sum if temp > 0 and temp<=0.05: return 5*temp elif temp> 0.05 and temp<=0.1: return 3*temp elif temp>0.1 and temp<=0.2: return 1.5*temp elif temp>0.3 and temp<=0.4: return 1.1*temp else: return temp #分区结合边缘检测的方法来进行二值化 def divisionThreshold(imgSKIN,imgFace,imgCanny,imgHair,imgBGR): useless,theta = meanBrightness(imgSKIN=imgSKIN, imgGRAY=imgFace) print("平均亮度",theta) sp = imgSKIN.shape divisionCount = math.floor(sp[1]/6) #初始化数组大小 imgSegment = [None] * divisionCount imgSkinSegment = [None] * divisionCount for i in range(len(imgSegment)): imgSegment[i] = [0] * divisionCount imgSkinSegment[i] = [0] * divisionCount new_w = math.floor(sp[1]/divisionCount) new_h = math.floor(sp[0]/divisionCount) dst = imgSKIN.copy() dst = dst[0:new_h*divisionCount,0:new_w*divisionCount] newSkin = imgSKIN[0:new_h*divisionCount,0:new_w*divisionCount] newFace = imgFace[0:new_h*divisionCount,0:new_w*divisionCount] #newHair = imgHair[0:new_h*divisionCount,0:new_w*divisionCount] newBGR = imgBGR[0:new_h*divisionCount,0:new_w*divisionCount] for i in range(divisionCount): for j in range(divisionCount): imgSegment[i][j] = imgFace[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w] imgSkinSegment[i][j] = imgSKIN[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w] skinPoint,alpha = meanBrightness(imgSKIN=imgSkinSegment[i][j],imgGRAY=imgSegment[i][j]) if alpha !=0: min_th = min(alpha,theta) max_th = max(alpha,theta) #imgSegment[i][j] = myThreshold(imgSegment[i][j],imgSkinSegment[i][j],skinPoint,0.71*thresh) gamma = 0.63 lamda = 0.855 bata = 0.145 edges = imgCanny[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w] #计算在这一小块中边缘点为多少个 edgesPointPercent = computeEdgesPoint(edges) if alpha>theta: #尽量往上 imgSegment[i][j] = myThreshold(imgSegment[i][j],imgSkinSegment[i][j],skinPoint,(1+edgesPointPercent)*gamma*(lamda*max_th+bata*min_th),globalAvg=theta,localAvg=alpha) else: #尽量往下 imgSegment[i][j] = myThreshold(imgSegment[i][j],imgSkinSegment[i][j],skinPoint,(1+edgesPointPercent)*gamma*(lamda1*max_th+bata1*min_th),globalAvg=theta,localAvg=alpha) for i in range(divisionCount): for j in range(divisionCount): dst[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w]=imgSegment[i][j] ret,dst = cv2.threshold(dst,150,255,cv2.THRESH_BINARY) return dst,newSkin,newFace,newBGR #头发处理 def hairProcess(imageSrc): img = imageSrc.copy() sp = img.shape imgRGB = img.copy() img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.imshow("hairhaha",img) x = 0 y =0 while img[x,y] >100 : y+=1 x+=1 mask = np.zeros((imgRGB.shape[0] + 2, img.shape[1] + 2), np.uint8) cv2.floodFill(imgRGB,mask,(x+2,y+3),(0,0,0),(3,3,3),(3,3,3),8) print("1",x,y) x1=0 y1=img.shape[1]-1 while img[x1,y1] > 100: x1+=2; y1-=2; mask = np.zeros((imgRGB.shape[0] + 2, img.shape[1] + 2), np.uint8) cv2.floodFill(imgRGB, mask, (y1 - 2,x1 + 2),(0, 0, 0),(3,3,3),(3,3,3), 8) print("2",x1,y1) imghair = cv2.cvtColor(imgRGB,cv2.COLOR_BGR2GRAY); return imghair #去除肤色噪声 def removeSkinNoise(imgGray,imgBin): img = imgGray.copy() sp = imgGray.shape for i in range(sp[0]): for j in range(sp[1]): if imgBin[i,j]<100: img[i,j]=255 cv2.imshow("11",img) hist = histUtil.myCalHist(img) histImg = histUtil.DrawHist(hist, [255, 255, 255]) cv2.imshow("histInit", histImg) min,max,hist =histUtil.removeNoiseOfHist(hist) histImg = histUtil.DrawHist(hist,[255,255,255]) cv2.imshow("histIMG",histImg) for i in range(sp[0]): for j in range(sp[1]): if imgBin[i, j] > 100: if imgGray[i,j]<min or imgGray[i,j]>max: imgBin[i,j] = 0 cv2.imshow("newskin",imgBin) return imgBin #总的图片处理过程 def processImg(img): kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) if img.shape[1]>800 or img.shape[0]>800: img = cv2.resize(img,(int(img.shape[1]/2) ,int(img.shape[0]/2)),interpolation=cv2.INTER_CUBIC) #cv2.imshow("img",img) #人脸检测 faces = detectFaces(img) if len(faces)<1: print("人脸识别失败,采用全局阈值") return globalThresholdMothod.globalThreshod(img) #获取到的人物头像前景图 imgFace = tailorImg(img,faces) cv2.imwrite("skeleton/1 "+str(name)+".jpg",imgFace) cv2.imshow("img", imgFace) #获取imgFace的肤色图 imgFace = removeBackground(imgFace) skinCounter,imgFace_Skin = skinModel(imgFace) cv2.imshow("skin", imgFace_Skin) if skinCounter<imgFace_Skin.shape[0]*imgFace_Skin.shape[1]/5: print(skinCounter,imgFace_Skin.shape[0]*imgFace_Skin.shape[1]) print("肤色检测:少于1/5区域,肤色模型沦陷,采用非肤色模式") result = nonSkinMode.processImg(img) return result; else: #去除肤色噪点 imgFace_Gray = cv2.cvtColor(imgFace, cv2.COLOR_BGR2GRAY) imgFace_Skin = removeSkinNoise(imgFace_Gray,imgFace_Skin) #################################################### #harlan #对肤色图进行修剪 imgFace_Skin = RemoveSelectRegion(imgFace_Skin,5000,0,0,1) cv2.imshow("RemoveSelectRegion",imgFace_Skin) #imgHair = hairProcess(imgFace) #cv2.imshow("skinTemp", imgFace_Skin) #harlan======================================= cv2.imshow("imgFace_gray",imgFace_Gray) canny = cv2.Canny(imgFace_Gray,40,120) cv2.imshow("canny",canny) imgFace_thresh,newSkin,newFace,newBGR = divisionThreshold(imgSKIN=imgFace_Skin,imgFace=imgFace_Gray,imgCanny=canny,imgHair= None,imgBGR = imgFace) cv2.imshow("face_threshold",imgFace_thresh) cv2.imwrite("skeleton/thresh.jpg",imgFace_thresh) #轮廓补充 #result = skeletonComplete(imgFace_thresh,imgSKIN=newSkin,imgFace=newFace) skeletonFace = removeBackground(newBGR, (0, 0, 0)) skeleton = histUtil.getSkeleton(skeletonFace, 1, 1) skeleton = RemoveSmallRegion(skeleton,200,0,0) cv2.imshow("skeleton",skeleton) cv2.imwrite("skeleton/38skeleton.jpg",skeleton) result = cv2.bitwise_and(imgFace_thresh, skeleton) return result #整套图片处理 def createResult(): i = 1 while i <= 907: print(i) #img = cv2.imread("imageTailor/1 (" + str(i) + ").jpg", 1) img = cv2.imread("img/"+str(i)+".jpg") i = i + 1 if img is None: continue; #img = cv2.medianBlur(img,3) dst = processImg(img) dst = cv2.medianBlur(dst, 3) dst = RemoveSelectRegion(dst, 20, 0, 0, 1) dst = delete_jut(dst, 1, 1, 1) dst = delete_jut(dst, 1, 1, 0) cv2.imwrite("result/" + str(i-1) + ".jpg", dst) #单个图片处理 def unitTest(): img = cv2.imread("img/"+str(name)+".jpg",1) #img = cv2.imread("imageTailor/1 ("+str(name)+").jpg") img = cv2.medianBlur(img, 3) dst = processImg(img) #cv2.imwrite("skeleton/1 "+str(name)+".jpg",dst) dst = cv2.medianBlur(dst, 3) dst = RemoveSelectRegion(dst, 20, 0, 0, 1) #dst = delete_jut(dst, 1, 1, 1) #dst = delete_jut(dst, 1, 1, 0) cv2.imwrite("skeleton/1 "+str(name)+"_.jpg",dst) cv2.imshow("result",dst) print(dst.shape) if __name__ == '__main__': name = 39 gamma = 0.700 lamda = 0.7000 bata = 0.3000 lamda1 = 0.35000 bata1 = 0.65000 unitTest() cv2.waitKey(0)<file_sep>/faceFeature/newThresholdMethod.py import cv2 import numpy as np import math from faceFeature.HistUtil import * def detectFaces(srcImg): img = srcImg.copy() #print 1 face_cascade = cv2.CascadeClassifier("data/haarcascades/haarcascade_frontalface_default.xml") if img.ndim == 3: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: gray = img faces = face_cascade.detectMultiScale(gray, 1.3, 5)#1.3and5 counts to the result of face recognation return faces def tailorImg(img,faces): x_up=[] y_up = [] x_down=[] y_down=[] if len(faces) == 1: for i,(x,y,w,h) in enumerate(faces): #注意不要越界 new_x = x - int(w/3) if x - int(w/3)>0 else 0 new_y = y - int(h/3) if y - int(h/3)>0 else 0 new_w = w +int(2/3*w) if new_x+w+int(2/3*w)<img.shape[1] else img.shape[1]-new_x new_h = h +int(2/3*h) if new_y+h +int(2/3*h)<img.shape[0] else img.shape[0]-new_y new_img = img[new_y:new_y+new_h,new_x:new_x+new_w] return new_img #cv2.imshow("new_img",new_img) elif len(faces)>1: for i, (x, y, w, h) in enumerate(faces): x_up.append(x); y_up.append(y); x_down.append(x+w); y_down.append(y+h); # 注意不要越界 x = min(x_up) y = min(y_up) w = max(x_down) - x h = max(y_down) - y new_x = x - int(w / 3) if x - int(w / 3) > 0 else 0 new_y = y - int(h / 3) if y - int(h / 3) > 0 else 0 new_w = w + int(2 / 3 * w) if new_x + w + int(2 / 3 * w) < img.shape[1] else img.shape[1] - new_x new_h = h + int(2 / 3 * h) if new_y + h + int(2 / 3 * h) < img.shape[0] else img.shape[0] - new_y new_img = img[new_y:new_y + new_h, new_x:new_x + new_w] cv2.imshow("tailor",new_img) return new_img # 通过漫水填充去除背景 def removeBackground(srcImg,color = (255,255,255)): img = srcImg.copy() sp = img.shape mask1 = np.zeros((img.shape[0] + 2, img.shape[1] + 2), np.uint8) mask = np.zeros((img.shape[0] + 2, img.shape[1] + 2), np.uint8) cv2.floodFill(img, mask, (3, 3), color, (3, 3, 3), (3, 3, 3), 8) cv2.floodFill(img, mask1, (sp[1] - 3, 3), color, (3, 3, 3), (3, 3, 3), 8) return img def myThreshold(imgGray,imgSkin,skinPoint,thresh): sp = imgGray.shape dst = imgGray.copy() for i in range(sp[0]): for j in range(sp[1]): if imgSkin[i,j] >100: if imgGray[i,j]>thresh: dst[i,j] = 255 else: dst[i,j] = 0 return dst #肤色检测 def skinModel(srcImg): img = srcImg.copy() rows, cols, channels = img.shape # light compensation gamma = 0.95 for r in range(rows): for c in range(cols): # get values of blue, green, red B = img.item(r, c, 0) G = img.item(r, c, 1) R = img.item(r, c, 2) # gamma correction B = int(B ** gamma) G = int(G ** gamma) R = int(R ** gamma) # set values of blue, green, red img.itemset((r, c, 0), B) img.itemset((r, c, 1), G) img.itemset((r, c, 2), R) ############################################################################### # convert color space from rgb to ycbcr imgYcc = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) # convert color space from bgr to rgb img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # copy original image imgSkin = np.zeros((img.shape[0],img.shape[1]),np.uint8) ################################################################################ # define variables for skin rules Wcb = 46.97 Wcr = 38.76 WHCb = 14 WHCr = 10 WLCb = 23 WLCr = 20 Ymin = 16 Ymax = 235 Kl = 125 Kh = 188 WCb = 0 WCr = 0 CbCenter = 0 CrCenter = 0 ################################################################################ for r in range(rows): for c in range(cols): # non-skin area if skin equals 0, skin area otherwise skin = 0 ######################################################################## # color space transformation # get values from ycbcr color space Y = imgYcc.item(r, c, 0) Cr = imgYcc.item(r, c, 1) Cb = imgYcc.item(r, c, 2) if Y < Kl: WCr = WLCr + (Y - Ymin) * (Wcr - WLCr) / (Kl - Ymin) WCb = WLCb + (Y - Ymin) * (Wcb - WLCb) / (Kl - Ymin) CrCenter = 154 - (Kl - Y) * (154 - 144) / (Kl - Ymin) CbCenter = 108 + (Kl - Y) * (118 - 108) / (Kl - Ymin) elif Y > Kh: WCr = WHCr + (Y - Ymax) * (Wcr - WHCr) / (Ymax - Kh) WCb = WHCb + (Y - Ymax) * (Wcb - WHCb) / (Ymax - Kh) CrCenter = 154 + (Y - Kh) * (154 - 132) / (Ymax - Kh) CbCenter = 108 + (Y - Kh) * (118 - 108) / (Ymax - Kh) if Y < Kl or Y > Kh: Cr = (Cr - CrCenter) * Wcr / WCr + 154 Cb = (Cb - CbCenter) * Wcb / WCb + 108 ######################################################################## # skin color detection #if Cb >= 80 and Cb <= 127 and Cr >= 141 and Cr <= 173: if Cb >= 80 and Cb <= 127 and Cr >= 141 and Cr <= 175: skin = 1 # print 'Skin detected!' if 0 == skin: imgSkin[r,c] = 0 else: imgSkin[r,c] = 255 # display original image and skin image return imgSkin def adaptiveThreshold(img): hist = myCalHist(img) histImg = DrawHist(hist, [255, 255, 255]) cv2.imshow("histInit", histImg) min,max,hist = removeNoiseOfHist(hist) histImg = DrawHist(hist,[255,255,255]) cv2.imshow("histIMG",histImg) #没有用处,可以不用,只是为了可视化 #thresh = GetMinimumThreshold(hist) return min,max,0 def getFaceBySkin(skin,grayFace): sp = skin.shape result = grayFace.copy() for i in range(sp[0]): for j in range(sp[1]): if skin[i,j] != 255: result[i,j] = 255 return result def computeEdgesPoint(img): sp = img.shape point = 0 sum =0 for i in range(sp[0]): for j in range(sp[1]): if img[i,j]>100: point +=1 sum +=1 temp = point/sum if temp > 0 and temp<=0.05: return 5*temp elif temp> 0.05 and temp<=0.1: return 3*temp elif temp>0.1 and temp<=0.2: return 1.5*temp elif temp>0.3 and temp<=0.4: return 1.1*temp else: return temp def removeNoiseOfHist(hist): result = hist.copy() counter = 0 for i in range(255,-1,-1): if result[i] != 0: counter += 1 result[i] = 0 if counter == 10: break counter = 0 for i in range(255): if result[i] !=0: counter+=1 result[i] = 0 if counter == 10: break for i in range(255): if result[i]<50: result[i] = 0 else: break for i in range(255,-1,-1): if result[i]<50: result[i] = 0 else: break for i in range(70): if result[i]>500: break result[i]=0 min ,max =0,0 for i in range(255): if result[i]!=0: min = i; break for i in range(255,-1,-1): if result[i]!=0: max = i; break return min,max,result def AvgGray(imgSKIN,imgGRAY): sp = imgSKIN.shape brightness = 0 count = 0 for i in range(sp[0]): for j in range(sp[1]): if imgSKIN[i,j] >100:# and imgGRAY[i,j]<err_mean[1]+70: brightness += imgGRAY[i,j] count +=1 if count !=0: return count,brightness/count else: return count,0 def partitionThreshold(imgSKIN,imgFace,imgCanny,patchSize): counter, theta = AvgGray(imgSKIN=imgSKIN, imgGRAY=imgFace) sp = imgFace.shape; divisionCount = math.floor(sp[1] / patchSize) imgFaceSegment = [None] * divisionCount imgSkinSegment = [None] * divisionCount for i in range(len(imgFaceSegment)): imgFaceSegment[i] = [0] * divisionCount imgSkinSegment[i] = [0] * divisionCount new_w = math.floor(sp[1]/divisionCount) new_h = math.floor(sp[0]/divisionCount) newGray = imgFace[0:new_h * divisionCount, 0:new_w * divisionCount] newSkin = imgSKIN[0:new_h * divisionCount, 0:new_w * divisionCount] newCanny = imgCanny[0:new_h * divisionCount, 0:new_w * divisionCount] dst = imgFace.copy() dst = dst[0:new_h * divisionCount, 0:new_w * divisionCount] for i in range(divisionCount): for j in range(divisionCount): imgFaceSegment[i][j] = imgFace[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w] imgSkinSegment[i][j] = imgSKIN[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w] skinpoint,alpha = AvgGray(imgSkinSegment[i][j],imgFaceSegment[i][j]) if alpha !=0: min_th = min(alpha, theta) max_th = max(alpha, theta) # imgSegment[i][j] = myThreshold(imgSegment[i][j],imgSkinSegment[i][j],skinPoint,0.71*thresh) gamma = 0.63 lamda = 0.855 bata = 0.145 edges = imgCanny[i * new_h:(i + 1) * new_h, j * new_w:(j + 1) * new_w] # 计算在这一小块中边缘点为多少个 edgesPointPercent = computeEdgesPoint(edges) if alpha > theta: # 尽量往上 imgFaceSegment[i][j] = myThreshold(imgFaceSegment[i][j], imgSkinSegment[i][j], skinpoint, (1 + edgesPointPercent) * gamma * (lamda * max_th + bata * min_th)) else: # 尽量往下 imgFaceSegment[i][j] = myThreshold(imgFaceSegment[i][j], imgSkinSegment[i][j], skinpoint, (1 + edgesPointPercent) * gamma * (lamda1 * max_th + bata1 * min_th)) for i in range(divisionCount): for j in range(divisionCount): dst[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w]=imgFaceSegment[i][j] cv2.imshow("initResult",dst) ret, dst = cv2.threshold(dst, 40, 255, cv2.THRESH_BINARY) return dst, newSkin, newGray def process(img): img = cv2.resize(img, (int(img.shape[1] / 2), int(img.shape[0] / 2)), interpolation=cv2.INTER_CUBIC) faces = detectFaces(srcImg=img) print(len(faces)) imgFaceBGR = tailorImg(img=img,faces=faces) imgFaceBGR = removeBackground(imgFaceBGR) imgFaceGray = cv2.cvtColor(imgFaceBGR,cv2.COLOR_BGR2GRAY) #cv2.imshow("imgFaceGray", imgFaceGray) imgSkin = skinModel(imgFaceBGR) #cv2.imshow("imgskin",imgSkin) imgFaceByskin = getFaceBySkin(skin=imgSkin,grayFace=imgFaceGray) #cv2.imshow("imgfacebyskin",imgFaceByskin) #统计直方图,去除肤色噪点 min,max,thresh = adaptiveThreshold(imgFaceByskin) sp = imgFaceByskin.shape for i in range(sp[0]): for j in range(sp[1]): if imgSkin[i,j]>100 and (imgFaceByskin[i,j]<min or imgFaceByskin[i,j]>max): imgSkin[i,j]=0 imgFaceByskin[i,j] =255 cv2.imshow("realSkin",imgFaceByskin) canny = cv2.Canny(imgFaceGray, 40, 120) imgFace_thresh,newSkin,newFace = partitionThreshold(imgSKIN=imgSkin,imgFace=imgFaceGray,imgCanny=canny,patchSize=15) imgFace_thresh = cv2.medianBlur(imgFace_thresh,3) #获取轮廓 skeletonFace = removeBackground(newFace,(0,0,0)) skeleton = getSkeleton(skeletonFace,2,3) result = cv2.bitwise_and(imgFace_thresh,skeleton) result = RemoveSelectRegion(result,100,0,0,0) cv2.imshow("result",result) return result def unitTest(): img = cv2.imread("imageTailor/1 (28).jpg") img = cv2.medianBlur(img, 3) reslut = process(img) def allTest(): for i in range(1, 105): print(i) img = cv2.imread("img/" + str(i) + ".jpg") img = cv2.medianBlur(img, 3) reslut = process(img) cv2.imwrite("result/" + str(i) + ".jpg", reslut) if __name__ == '__main__': gamma = 0.700 lamda = 0.7000 bata = 0.3000 lamda1 = 0.35000 bata1 = 0.65000 unitTest() cv2.waitKey(0)<file_sep>/Keras/regressor.py from keras import Sequential from keras.layers import Dense import matplotlib.pyplot as plt import numpy as np X = np.linspace(-1,1,200) np.random.shuffle(X) Y = 0.5*X +2+np.random.normal(0,0.05,(200,)) plt.scatter(X,Y) plt.show() X_train,Y_train = X[:160],Y[:160] X_test,Y_test = X[160:],Y[160:] model = Sequential() model.add(Dense(output_dim=1,input_dim=1)) model.compile(loss='mse',optimizer='sgd') for step in range(501): cost = model.train_on_batch(X_train,Y_train) if step%100==0: print("train cost" ,cost) print('\nTesting----------') cost = model.evaluate(X_test,Y_test,batch_size=40) print('test cost',cost) w,b = model.layers[0].get_weights() print('weight=',w,"bias=",b) Y_pred = model.predict(X_test) plt.scatter(X_test,Y_test) plt.plot(X_test,Y_pred) plt.show() <file_sep>/deepResidualLearningForImageRecognition/__init__.py import numpy as np from matplotlib import pyplot as plt t = np.arange(0, 4,1) # x轴上的点,0到2之间以0.01为间隔 s = [4,3,5,7] t1 = np.arange(0,4,1) s2 = [4,4,6,8] plt.plot(t, s) # 画图 plt.plot(t1,s2) plt.xlabel('time (s)') # x轴标签 plt.ylabel('voltage (mV)') # y轴标签 plt.title('About as simple as it gets, folks') # 图的标签 plt.grid(True) # 产生网格 plt.savefig("test.png") # 保存图像 plt.show() # 显示图像<file_sep>/faceFeature/GuanssSkinModel.py import cv2 import numpy as np def P(img,u,s): result = np.zeros((img.shape[0],img.shape[1])) img = cv2.cvtColor(img,cv2.COLOR_BGR2YCrCb) sp = img.shape for i in range(sp[0]): for j in range(sp[1]): x = np.array([[img[i,j,2]],[img[i,j,1]]]) x = np.matrix(x) result[i, j]=np.exp(-0.5*(x-u).T*s.I*(x-u)) cv2.imshow("fdfd",result) if __name__ == '__main__': u = np.array([[117.4361],[156.5599]]) u = np.matrix(u) s = np.array([[160.1301,12.1430],[12.1430,299.4574]]) s = np.matrix(s) img = cv2.imread("skeleton/41.jpg") P(img,u,s) print(type(u)) cv2.waitKey(0)<file_sep>/facc/test.py import cv2 import numpy as np import matplotlib.pyplot as plt import imutils from mpl_toolkits.mplot3d import Axes3D if __name__ == '__main__': img = cv2.imread('B01/B01-01.bmp', 0) # 直接读为灰度图像 img = img[143:891, 393:1239] # 为了方便,我们新建一个与input一样大小的图片; sp = img.shape x = np.arange(sp[1]) y = np.arange(sp[0]) X, Y = np.meshgrid(x, y) Z=img fig = plt.figure() ax = Axes3D(fig) ax.contour3D(X, Y, Z, 50, cmap='binary') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z'); plt.show() cv2.waitKey(0)<file_sep>/Keras/classification.py from keras import Sequential from keras.layers import Dense,Activation from matplotlib import pyplot as plt import numpy as np from keras.datasets import mnist from keras.optimizers import RMSprop from keras.utils import np_utils np.random.seed(1337) if __name__ == '__main__': (x_train,y_train),(x_test,y_test) = mnist.load_data() x_train = x_train.reshape(x_train.shape[0],-1)/255 x_test = x_test.reshape(x_test.shape[0],-1)/255 y_train = np_utils.to_categorical(y_train,num_classes=10) y_test = np_utils.to_categorical(y_test,num_classes=10) #build neural net model = Sequential([ Dense(32,input_dim=784), Activation('relu'), Dense(10), Activation('softmax') ]) #define optimizer rmsprop = RMSprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0) #get more results you want to see model.compile(optimizer=rmsprop, loss='categorical_crossentropy', metrics=['accuracy']) print("training==========") model.fit(x_train,y_train,nb_epoch=2,batch_size=32) print("\ntesting============") loss,accuracy = model.evaluate(x_test,y_test) print("test loss",loss) print("test accuracy",accuracy)<file_sep>/faceFeature/buildModel.py import cv2 import numpy as np import os import tensorlayer as tl import tensorflow as tf import pylab from mpl_toolkits.mplot3d import Axes3D from sklearn import svm from matplotlib import pyplot as plt from sklearn.externals import joblib from sklearn import metrics from sklearn.linear_model import LogisticRegression from skinDetect import tensorlayerUtil from faceFeature import HistUtil def importData(): src = [] bin = [] path1 = "Face_Dataset/Ground_Truth/GroundT_FacePhoto" # 文件夹目录 path2 = "Face_Dataset/Pratheepan_Dataset/FacePhoto" files = os.listdir(path2) # 得到文件夹下的所有文件名称 for file in files: # 遍历文件夹 if not os.path.isdir(file): # 判断是否是文件夹,不是文件夹才打开 portion = os.path.splitext(file) # 将文件名拆成名字和后缀 if portion[1] != ".png": # 关于后缀 newname = portion[0] + ".png" os.rename(path2 + "/" + file, path2 + "/" + newname) # 修改 src.append(path2 + "/" + file) bin.append(path1 + "/" + file) path1 = "Face_Dataset/Ground_Truth/GroundT_FamilyPhoto" # 文件夹目录 path2 = "Face_Dataset/Pratheepan_Dataset/FamilyPhoto" files = os.listdir(path2) # 得到文件夹下的所有文件名称 for file in files: # 遍历文件夹 if not os.path.isdir(file): # 判断是否是文件夹,不是文件夹才打开 portion = os.path.splitext(file) # 将文件名拆成名字和后缀 if portion[1] != ".png": # 关于后缀 newname = portion[0] + ".png" os.rename(path2 + "/" + file, path2 + "/" + newname) # 修改 src.append(path2 + "/" + file) bin.append(path1 + "/" + file) return src,bin def model(src,bin): sum = np.zeros((2,)) size = len(src) CB=np.zeros((300,1)) CR=np.zeros((300,1)) crcb = np.zeros((300,300)) count = 0 for i in range(size): srcImg = cv2.imread(src[i]) #cv2.imshow("src",srcImg) srcImg = cv2.cvtColor(srcImg, cv2.COLOR_BGR2YCrCb) binImg = cv2.imread(bin[i], 0) #cv2.imshow("bin",binImg) sp = srcImg.shape for x in range(sp[0]): for y in range(sp[1]): if binImg[x, y] > 200: crcb[srcImg[x,y,1],srcImg[x,y,2]]+=1 x = np.arange(300) y = np.arange(300) X, Y = np.meshgrid(x, y) Z=crcb fig = plt.figure() ax = Axes3D(fig) ax.contour3D(X, Y, Z, 50, cmap='binary') ax.set_xlabel('cr') ax.set_ylabel('cb') ax.set_zlabel('z'); plt.show() #彩色图 # fig = plt.figure() # ax = Axes3D(fig) # ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow') # plt.show() np.savetxt("crcb.txt",crcb) u = getParameter(crcb) print(u) return crcb def getParameter(crcb): sp = crcb.shape crSum=0 cbSum=0 point = 0 CB=[] CR =[] for i in range(sp[0]): for j in range(sp[1]): crSum += crcb[i,j]*i cbSum +=crcb[i,j]*j for time in range(int(crcb[i,j])): CB.append(j) CR.append(i) point+=crcb[i,j] y = [CB,CR] C = np.cov(y) m=np.matrix(np.array([[crSum / point], [cbSum / point]])) return C,m def classify(X,m,C): return np.exp(-1/2*(X-m).T*C.I*(X-m)) def process(img,m,C): img = cv2.cvtColor(img,cv2.COLOR_BGR2YCrCb) sp = img.shape gaussian = np.zeros((sp[0],sp[1]),np.uint8) binary = np.zeros((sp[0],sp[1])) for x in range(sp[0]): for y in range(sp[1]): cr = img[x, y, 1]# / (img[x, y, 0] + img[x, y, 1] + img[x, y, 2]) cb = img[x, y, 2] #/ (img[x, y, 0] + img[x, y, 1] + img[x, y, 2]) X = np.array([[cr],[cb]]) X = np.matrix(X) gaussian[x,y] = (classify(X,m,C))*255 ret,binary = cv2.threshold(gaussian,40,255,cv2.THRESH_BINARY) return binary,gaussian def gaussModel(img): crcb = np.loadtxt("crcb.txt") # s,u = getParameter(crcb) C = np.loadtxt("s.txt") C = np.matrix(C) m = np.loadtxt("u.txt") m = np.matrix(m) m = np.reshape(m, [2, 1]) return process(img, m, C) if __name__ == '__main__': #数据导入 # src,bin = importData() # print(src,bin) #获取模型数据 #crcb = model(src,bin) img = cv2.imread("imageTailor/1 (169).jpg") faces = HistUtil.detectFaces(img) img1 = HistUtil.tailorImg(img,faces) img = HistUtil.removeBackground(img1,(0,0,0)) binary,gauss = gaussModel(img); cv2.imshow("binary",binary) cv2.imshow("gauss",gauss) cv2.imshow("wrc",img1) cv2.imwrite("skeleton/b1.jpg",binary) cv2.imwrite("skeleton/g1.jpg",gauss) cv2.imwrite("skeleton/src1.jpg",img1) cv2.waitKey(0) <file_sep>/facc/B07.py import cv2 import numpy as np #去除指定大小的区域 from mpl_toolkits.mplot3d import Axes3D import math import matplotlib.pyplot as plt import facc.HistUtil as histUtil def delete_jut(src,uthreshold,vthreshold,type): threshold = 0 dst = src.copy() sp = src.shape height = sp[0] width = sp[1] k = 0 #type = 0 就是消除黑色的突出部 type=1就是消除白色的突出部 mode = (1-type)*255 modeInver = 255-mode for i in range(height-1): for j in range(width-1): #行消除 if dst[i,j]== mode and dst[i,j+1] == modeInver: if j+uthreshold >= width: for k in range(j+1,width): dst[i,k] = mode else: for k in range(j+2,j+uthreshold+1): if dst[i,k] == mode: break if dst[i,k] == mode: for h in range(j+1,k): dst[i,h] = mode #列消除 if dst[i,j] == mode and dst[i+1,j] == modeInver: if i+vthreshold >= height: for k in range(i+1,height): dst[k,j] = mode else: for k in range(i+2,i+vthreshold+1): if dst[k,j] == mode: break if dst[k,j] == mode: for h in range(i+1,k): dst[h,j] = mode #根据需求,强制性去除上下四行 for i in range(2): for j in range(width): dst[i,j] = mode; for i in range(height-1,height-3,-1): for j in range(width): dst[i,j] = mode; return dst if __name__ == '__main__': img = cv2.imread("B07/B07-02.bmp",0) ROI = img[445:635,560:1050] #rows from 445 to 635 ,cols from 560 to 1050 cv2.imshow("ROI",ROI) #转换成二值图,方便获取轮廓 ret,ROIbin = cv2.threshold(ROI,100,255,cv2.THRESH_BINARY) cv2.imshow("ROIbin",ROIbin) result, contours, hierarchy = cv2.findContours(ROIbin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) result = np.zeros(ROI.shape, np.uint8) cv2.drawContours(result, contours, -1, 255) cv2.imshow("contours", result) for i in range(len(contours)): rect = cv2.boundingRect(contours[i]) #先判断是圆还是方 if math.fabs(rect[2]-rect[3])>8:#是长方形,进行去毛刺处理 temp = ROIbin[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]] temp = delete_jut(temp,int(temp.shape[1]*1/5),int(temp.shape[0]*3/5),1) ROIbin[rect[1]:rect[1] + rect[3], rect[0]:rect[0] + rect[2]]=temp; cv2.imshow("newROI",ROIbin) cv2.waitKey(0)<file_sep>/kaggle/titanic/__init__.py import pandas as pd if __name__ == '__main__': train_df = pd.read_csv("train.csv") test_df = pd.read_csv("test.csv") combine = [train_df,test_df] print(train_df.columns.values)<file_sep>/faceFeature/pythonForTest.py import cv2 import math import matplotlib import numpy as np from matplotlib import pyplot as plt import faceFeature.newThresholdMethod as newOne import faceFeature.HistUtil as histUtil def DrawHist(hist, color): minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist) histImg = np.zeros([512,256], np.uint8) hpt = int(0.9* 256); #cv2.line(histImg, (0, 256), (256, 256), [0,0,255]) for h in range(256): intensity = int(hist[h]*hpt/maxVal) if intensity!=0: cv2.line(histImg,(h,256), (h,256-intensity), color) return histImg; def fourier(hist,Mode,alterComponent = 0,radio = 0): ft = hist.copy() N = 256 Cu = 1 #高通滤波 if Mode == 0: for u in range(N): if u == 0: Cu= 1.0/math.sqrt(2) sum = 0 for x in range(N): theta = ((2*x)+1)*u*math.pi/(2*N) if theta == 0 or u<alterComponent: sum += (hist[x]*math.cos(theta)) temp = Cu*math.sqrt(2.0/N)*sum ft[u] = int(temp) else: #低通滤波 sum_direct = 0 for u in range(N): if u == 0: Cu= 1.0/math.sqrt(2) sum = 0 for x in range(N): theta = ((2*x)+1)*u*math.pi/(2*N) if theta == 0: sum_direct+=(hist[x]*math.cos(theta)) sum += (hist[x]*math.cos(theta)) temp = Cu*math.sqrt(2.0/N)*sum ft[u] = int(temp) sum_direct = Cu*math.sqrt(2.0/N)*sum_direct for u in range(N): if ft[u]>sum_direct*radio: ft[u]=0 return ft if __name__ == '__main__': myfont = matplotlib.font_manager.FontProperties(fname='c:\\windows\\fonts\\simfang.ttf') img = cv2.imread("skeleton/src1.jpg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.subplot(231) ,plt.title('原图',fontproperties=myfont) plt.imshow(img) plt.xticks([]), plt.yticks([]) img = cv2.imread("skeleton/g1.jpg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.subplot(232),plt.title('肤色概率图',fontproperties=myfont) plt.imshow(img) plt.xticks([]), plt.yticks([]) img = cv2.imread("skeleton/b1.jpg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.subplot(233),plt.title('肤色图',fontproperties=myfont) plt.imshow(img) plt.xticks([]), plt.yticks([]) img = cv2.imread("skeleton/src2.jpg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.subplot(234),plt.title('原图',fontproperties=myfont) plt.imshow(img) plt.xticks([]), plt.yticks([]) img = cv2.imread("skeleton/g2.jpg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.subplot(235),plt.title('肤色概率图',fontproperties=myfont) plt.imshow(img) plt.xticks([]), plt.yticks([]) img = cv2.imread("skeleton/b2.jpg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.subplot(236),plt.title('肤色图',fontproperties=myfont) plt.imshow(img) plt.xticks([]), plt.yticks([]) # # img = cv2.imread("skeleton/52.jpg") # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # plt.subplot(245) # plt.imshow(img) # plt.xticks([]), plt.yticks([]) # img = cv2.imread("skeleton/52_.jpg") # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # plt.subplot(246) # plt.imshow(img) # plt.xticks([]), plt.yticks([]) # img = cv2.imread("skeleton/41.jpg") # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # plt.subplot(247) # plt.imshow(img) # plt.xticks([]), plt.yticks([]) # img = cv2.imread("skeleton/41_.jpg") # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # plt.subplot(248) # plt.imshow(img) # plt.xticks([]), plt.yticks([]) plt.show() # img_man = cv2.imread('skeleton/5.png', 0) # 直接读为灰度图像 # # # img_man = cv2.imread('skeleton/test.jpg', 0) # 直接读为灰度图像 # plt.subplot(232), plt.imshow(img_man, 'gray'), plt.title('原图',fontproperties=myfont) # plt.xticks([]), plt.yticks([]) # # -------------------------------- # rows, cols = img_man.shape # mask = np.zeros(img_man.shape, np.uint8) # #mask[int(rows / 2) - 30:int(rows / 2) + 30, int(cols / 2) - 30:int(cols / 2) + 30] = 1 # for x in range(rows): # for y in range(cols): # if np.sqrt(np.power(x-rows/2,2)+np.power(y-cols/2,2))<50-5: # mask[x,y]=255 # elif np.sqrt(np.power(x-rows/2,2)+np.power(y-cols/2,2))>50+5: # mask[x,y]=255 # else: # mask[x,y]=0 # # -------------------------------- # plt.subplot(231), plt.imshow(mask, 'gray'), plt.title('理想带阻滤波器', fontproperties=myfont) # plt.xticks([]), plt.yticks([]) # f1 = np.fft.fft2(img_man) # f1shift = np.fft.fftshift(f1) # f1shift = f1shift * mask # f2shift = np.fft.ifftshift(f1shift) # 对新的进行逆变换 # img_new = np.fft.ifft2(f2shift) # # 出来的是复数,无法显示 # img_new = np.abs(img_new) # # 调整大小范围便于显示 # img_new = (img_new - np.amin(img_new)) / (np.amax(img_new) - np.amin(img_new)) # plt.subplot(233), plt.imshow(img_new, 'gray'), plt.title('理想带阻滤波结果图',fontproperties=myfont) # plt.xticks([]), plt.yticks([]) # # img_man = cv2.imread('skeleton/test.jpg', 0) # 直接读为灰度图像 # plt.subplot(235), plt.imshow(img_man, 'gray'), plt.title('原图', fontproperties=myfont) # plt.xticks([]), plt.yticks([]) # # -------------------------------- # rows, cols = img_man.shape # mask = np.zeros(img_man.shape, np.uint8) # # mask[int(rows / 2) - 30:int(rows / 2) + 30, int(cols / 2) - 30:int(cols / 2) + 30] = 1 # for x in range(rows): # for y in range(cols): # if np.sqrt(np.power(x - rows / 2, 2) + np.power(y - cols / 2, 2)) < 50 - 5: # mask[x, y] = 0 # elif np.sqrt(np.power(x - rows / 2, 2) + np.power(y - cols / 2, 2)) > 50 + 5: # mask[x, y] = 0 # else: # mask[x, y] = 255 # # -------------------------------- # plt.subplot(234), plt.imshow(mask, 'gray'), plt.title('理想带通滤波器', fontproperties=myfont) # plt.xticks([]), plt.yticks([]) # f1 = np.fft.fft2(img_man) # f1shift = np.fft.fftshift(f1) # f1shift = f1shift * mask # f2shift = np.fft.ifftshift(f1shift) # 对新的进行逆变换 # img_new = np.fft.ifft2(f2shift) # # 出来的是复数,无法显示 # img_new = np.abs(img_new) # # 调整大小范围便于显示 # img_new = (img_new - np.amin(img_new)) / (np.amax(img_new) - np.amin(img_new)) # plt.subplot(236), plt.imshow(img_new, 'gray'), plt.title('理想带通滤波结果图', fontproperties=myfont) # plt.xticks([]), plt.yticks([]) # plt.show() <file_sep>/skinDetect/test.py import cv2 import matplotlib import numpy as np import math import skimage from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D #OSTU大津法 def GetOSTUThreshold(histGram): X, Y, Amount = 0,0,0; MinValue, MaxValue=0,0; Threshold = 0; for MinValue in range(256): if histGram[MinValue]!=0: break; for MaxValue in range(255,-1,-1): if histGram[MaxValue]!=0: break; if MaxValue == MinValue: return MaxValue; # 图像中只有一个颜色 if MinValue + 1 == MaxValue: return MinValue; # 图像中只有二个颜色 for Y in range(MinValue,MaxValue+1):Amount += histGram[Y];#像素个数 PixelIntegral = 0; for Y in range(MinValue, MaxValue + 1): PixelIntegral += histGram[Y] * Y;#像素总值 SigmaB = -1; PixelBack = 0 PixelIntegralBack=0 for Y in range(MinValue, MaxValue + 1): PixelBack = PixelBack + histGram[Y]; PixelFore = Amount - PixelBack; OmegaBack = float(PixelBack / Amount); OmegaFore = float(PixelFore / Amount); PixelIntegralBack += histGram[Y] * Y; PixelIntegralFore = PixelIntegral - PixelIntegralBack; MicroBack = float(PixelIntegralBack / PixelBack); MicroFore = float(PixelIntegralFore / PixelFore); Sigma = OmegaBack * OmegaFore * (MicroBack - MicroFore) * (MicroBack - MicroFore); if (Sigma > SigmaB): SigmaB = Sigma; Threshold = Y; return Threshold; #手动画出直方图和阈值 def calcAndDrawHist(image, color): hist = cv2.calcHist([image], [0], None, [256], [0.0, 255.0]) minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist) histImg = np.zeros([256, 256, 3], np.uint8) hpt = int(0.9 * 256); for h in range(256): intensity = int(hist[h] * hpt / maxVal) cv2.line(histImg, (h, 256), (h, 256 - intensity), color) thresh = GetOSTUThreshold(hist) cv2.line(histImg, (thresh, 255), (thresh,0), [0,0,255]) return thresh,histImg; if __name__ == '__main__': img = cv2.imread('2.3/11.jpg', 0) # 直接读为灰度图像 thresh,histimg = calcAndDrawHist(img,[255,255,255]) cv2.imshow("HistByHand",histimg) cv2.imwrite("2.3/11_HistByHand.jpg",histimg) cv2.imshow("lena",img) cv2.imwrite("2.3/11_Gray.jpg",img) ret,result = cv2.threshold(img,thresh,255,cv2.THRESH_BINARY) cv2.imshow("binary",result) cv2.imwrite("2.3/11_binary.jpg",result) #使用python画出直方图 plt.figure("7_HistByPython") arr = img.flatten() n, bins, patches = plt.hist(arr, bins=256, normed=1, facecolor='green', alpha=0.75) plt.show() cv2.waitKey(0) <file_sep>/Keras/cnn.py from keras import Sequential from keras.layers import Dense,Activation,Convolution2D,MaxPooling2D,Flatten from matplotlib import pyplot as plt import numpy as np from keras.datasets import mnist from keras.optimizers import Adam from keras.utils import np_utils np.random.seed(1337) if __name__ == '__main__': (x_train,y_train),(x_test,y_test) = mnist.load_data() x_train = x_train.reshape(-1,1,28,28) x_test = x_test.reshape(-1,1,28,28) y_train = np_utils.to_categorical(y_train,num_classes=10) y_test = np_utils.to_categorical(y_test,num_classes=10) model = Sequential() #output (32,28,28) model.add(Convolution2D( filters=32, kernel_size=(5,5), padding='same', input_shape=(1,28,28) )) model.add(Activation('relu')) #pooling output (32,14,14) model.add(MaxPooling2D( pool_size=(2,2), strides=(2,2), padding="same" )) #conv layer2 output(64,14,14) model.add( Convolution2D(64,(5,5),padding="same") ) model.add(Activation("relu")) #pooling2 output(64,7,7) model.add(MaxPooling2D(pool_size=(2,2),padding="same")) #full connected1 output(64,7,7) model.add(Flatten()) model.add(Dense(1024)) model.add((Activation('relu'))) #full connected2 model.add(Dense(10)) model.add(Activation('softmax')) #define optimizer adam = Adam(lr=1e-4) model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['accuracy']) print('training===================') model.fit(x_train,y_train,batch_size=32,nb_epoch=2) print('\ntesting===================') loss,accuracy = model.evaluate(x_test,y_test) print('\nloss=',loss) print('\naccuracy=',accuracy) <file_sep>/tensorflowLearn/__init__.py import tensorflow as tf import tensorlayer as tl if __name__ == '__main__': sess = tf.InteractiveSession(); x_train,y_train,x_val,y_val,x_test,y_test = None #设置输入 x = tf.placeholder(tf.float32,shape=[50,184,184,3],name='x') y_ = tf.placeholder(tf.float32,shape=[50,184,184,1],name='y_') #设置网络 network = tl.layers.InputLayer(inputs=x,name='input') network = tl.layers.DropoutLayer(network,keep=0.8) network = tl.layers.Conv3dLayer(network,act=tf.nn.relu,shape=[1,1,121,3,114], strides=[1,1,1,1,1],padding='SAME',name='cnn_layer1')#output(?,64,184,114) network =tl.layers.Conv3dLayer(network,act=tf.nn.relu,shape=[3,121,1,114,38], strides=[1,1,1,1,1],padding='SAEM',name='cnn_layers2')#output(?,64,64,38) network = tl.layers.Conv3dLayer(network,act=tf.nn.relu,shape=[38,1,1,38,1], strides=[1,1,1,1,1],padding='SAME',name='cnn_layer3')#output(?,64,64,1) network =tl.layers.Conv3dLayer(network,act=tf.nn.relu,shape=[1,16,16,1,512], strides=[1,1,1,1,1],padding='SAME',name='cnn_layer4')#output(?,49,49,512) network = tl.layers.DeConv3dLayer(network,act=tf.nn.relu,shape=[512,1,1,1,512], output_shape=[120,120,1],strides=[1,1,1,1,1],padding='SAME',name='deconv3d'); y = network.outputs; #定义损失函数 cost = tl.cost.cross_entropy(y_,y,name='loss') train_params = network.all_params train_op = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(cost, var_list=train_params) tl.layers.initialize_global_variables(sess) tl.utils.fit(sess,network,train_op,cost, x_train,y_train,x,y_, batch_size=500,n_epoch=500, print_freq=5,X_val=x_val,y_val=y_val,eval_train=False) tl.files.save_npz(network.all_params,name='model.npz') sess.close() <file_sep>/skinDetect/tensorlayerUtil.py import tensorflow as tf import tensorlayer as tl from sklearn.cross_validation import train_test_split def useNet(X,Y): # x为数据集的feature熟悉,y为label. X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4) X_test, X_val, y_test, y_val = train_test_split(X_test, y_test, test_size=0.5) sess = tf.InteractiveSession() # 定义 placeholder x = tf.placeholder(tf.float32, shape=[None, 2], name='x') y_ = tf.placeholder(tf.int64, shape=[None, 1], name='y_') # 定义模型 network = tl.layers.InputLayer(x, name='input_layer') network = tl.layers.DropoutLayer(network, keep=0.8, name='drop1') network = tl.layers.DenseLayer(network, n_units=20, act=tf.nn.relu, name='relu1') network = tl.layers.DropoutLayer(network, keep=0.5, name='drop2') network = tl.layers.DenseLayer(network, n_units=20, act=tf.nn.relu, name='relu2') network = tl.layers.DropoutLayer(network, keep=0.5, name='drop3') network = tl.layers.DenseLayer(network, n_units=1, act=tf.identity, name='output_layer') # 定义损失函数和衡量指标 # tl.cost.cross_entropy 在内部使用 tf.nn.sparse_softmax_cross_entropy_with_logits() 实现 softmax y = network.outputs cost = tl.cost.cross_entropy(y, y_, name="cost") correct_prediction = tf.equal(y, y_) acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) y_op = tf.argmax(tf.nn.softmax(y), 1) # 定义 optimizer train_params = network.all_params train_op = tf.train.AdamOptimizer(learning_rate=0.0001, beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False).minimize(cost, var_list=train_params) # 初始化 session 中的所有参数 tl.layers.initialize_global_variables(sess) # 训练模型 tl.utils.fit(sess, network, train_op, cost, X_train, y_train, x, y_, acc=acc, batch_size=500, n_epoch=500, print_freq=5, X_val=X_val, y_val=y_val, eval_train=False) # 评估模型 tl.utils.test(sess, network, acc, X_test, y_test, x, y_, batch_size=None, cost=cost) # 把模型保存成 .npz 文件 tl.files.save_npz(network.all_params, name='model.npz') sess.close()<file_sep>/ImageTest/__init__.py import cv2 def fillRunVectors(bwImage): rows = bwImage.shape[0] cols = bwImage.shape[1] NumberOfRuns = 0; stRun = [] enRun = [] rowRun = [] for i in range(rows): if bwImage[rows,0]==255: NumberOfRuns+=1 stRun.append(0) rowRun.append(i) for j in range(cols): if bwImage[i,j-1] == 0 and bwImage[i,j]==255: NumberOfRuns+=1 stRun.append(j) rowRun.append(i) elif bwImage[i,j-1]==255 and bwImage[i,j]==0: enRun.append(j-1) if bwImage[i,cols-1]: enRun.append(cols-1) return NumberOfRuns,stRun,enRun,rowRun def firstPass(NumberOfRuns,stRun,enRun,rowRun,offset): runLabels = [0]*NumberOfRuns; idxLabel = 1 curRowIdx = 0 firstRunOnCur = 0 firstRunOnPre = 0 lastRunOnPre = -1 equivalence =[(None,None)] for i in range(NumberOfRuns): if rowRun[i] != curRowIdx: curRowIdx = rowRun[i] #换一行 firstRunOnPre = firstRunOnCur lastRunOnPre = i-1 firstRunOnCur = i for j in range(firstRunOnPre,lastRunOnPre+1): if stRun[i]<=enRun[j]+offset and enRun[i]>=stRun[j]-offset and rowRun == rowRun[j]+1: if runLabels[i]==0: runLabels[i] = runLabels[j] elif runLabels[i]!=runLabels[j]: equivalence.append((runLabels[i],runLabels.append(j))) if runLabels[i] == 0: runLabels[i] = idxLabel idxLabel+=1 if __name__ == '__main__': t = [0]*5 print(t) <file_sep>/傅里叶变化合集/fft1.py import numpy as np import math if __name__ == '__main__': data = [15, 32, 9, 222, 18, 151, 5, 7, 56, 233, 56, 121, 235, 89, 98, 111] M = data.__len__() Cu = 1 fft = [] for u in range(M): sum = complex(0, 0) for x in range(M): temp = -2*math.pi*u*x/M sum+=(data[x]*(math.cos(temp)+1j*math.sin(temp))) fft.append(sum) print(fft) infft = [] for x in range(M): sum = complex(0, 0) for u in range(M): power = 2*math.pi*u*x/M sum +=fft[u]*(math.cos(power)+1j*math.sin(power)) infft.append(1/M*sum); print(infft); <file_sep>/faceFeature/recordFile/partitionMethod10.15.15.py # encoding:utf-8 import cv2 import numpy as np import math #检测人脸 def detectFaces(srcImg): img = srcImg.copy() #print 1 face_cascade = cv2.CascadeClassifier("data/haarcascades/haarcascade_frontalface_default.xml") if img.ndim == 3: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: gray = img faces = face_cascade.detectMultiScale(gray, 1.3, 5)#1.3and5 counts to the result of face recognation return faces #在人脸的基础上检测眼睛 def detectEyes(srcImg): src = srcImg.copy() faces = detectFaces(src) eye_cascade = cv2.CascadeClassifier('data/haarcascades_cuda/haarcascade_eye_tree_eyeglasses.xml') gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) result = [[]] for j,(x,y,w,h) in enumerate(faces): cv2.rectangle(src, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = src[y:y + h,x:x + w] # 检测视频中脸部的眼睛,并用vector保存眼睛的坐标、大小(用矩形表示) eyes = eye_cascade.detectMultiScale(roi_gray) #眼睛检测 #选择最大的两个框当成眼睛 max = 0 temp = [] index = 0 for i,(ex,ey,ew,eh) in enumerate(eyes): if ew*eh>max and ex<w and ey<h/2: max = ew*eh index = i temp = (ex+x,ey+y,ew,eh) if index != 0: result[j].append(temp) cv2.rectangle(src, (temp[0], temp[1]), (temp[0] + temp[2], temp[1] + temp[3]), (0, 255, 0), 2) max = 0 temp = [] #用来确认是否找到眼睛 flag = 0 for i,(ex,ey,ew,eh) in enumerate(eyes): if ew*eh>max and i != index and ex<w and ey<h/2: print(ex,ey,x+w,y+h/2) max = ew*eh flag = 1 temp = (ex+x,ey+y,ew,eh) if flag == 1: result[j].append(temp) cv2.rectangle(src, (temp[0], temp[1]), (temp[0] + temp[2], temp[1] + temp[3]), (0, 255, 0), 2) #cv2.imshow("eye",src) return faces,result #皮肤检测。。。。。实践不行 def skinEllipse(srcImg): img = srcImg.copy() sp = img.shape model = np.zeros((256,256),np.uint8) result = np.zeros((sp[0],sp[1]),np.uint8) cv2.ellipse(model, (113, 155), (25, 17), 43, 0, 360, 255,-1) imgYcrcb = cv2.cvtColor(img,cv2.COLOR_BGR2YCrCb) for i in range(sp[0]): for j in range(sp[1]): #if model[imgYcrcb[i,j,1],imgYcrcb[i,j,2]] == 255: if imgYcrcb[i,j,1]>30 and imgYcrcb[i,j,1]<115 and imgYcrcb[i,j,2]>90 and imgYcrcb[i,j,2]<240: result[i,j]=255 else: result[i,j]=0 cv2.imshow("ellipseSkin",result) return result #肤色检测 def skinModel(srcImg): img = srcImg.copy() rows, cols, channels = img.shape # light compensation gamma = 0.95 for r in range(rows): for c in range(cols): # get values of blue, green, red B = img.item(r, c, 0) G = img.item(r, c, 1) R = img.item(r, c, 2) # gamma correction B = int(B ** gamma) G = int(G ** gamma) R = int(R ** gamma) # set values of blue, green, red img.itemset((r, c, 0), B) img.itemset((r, c, 1), G) img.itemset((r, c, 2), R) ############################################################################### # convert color space from rgb to ycbcr imgYcc = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) # convert color space from bgr to rgb img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # prepare an empty image space imgSkin = np.zeros(img.shape, np.uint8) # copy original image imgSkin = np.zeros((img.shape[0],img.shape[1]),np.uint8) ################################################################################ # define variables for skin rules Wcb = 46.97 Wcr = 38.76 WHCb = 14 WHCr = 10 WLCb = 23 WLCr = 20 Ymin = 16 Ymax = 235 Kl = 125 Kh = 188 WCb = 0 WCr = 0 CbCenter = 0 CrCenter = 0 ################################################################################ for r in range(rows): for c in range(cols): # non-skin area if skin equals 0, skin area otherwise skin = 0 ######################################################################## # color space transformation # get values from ycbcr color space Y = imgYcc.item(r, c, 0) Cr = imgYcc.item(r, c, 1) Cb = imgYcc.item(r, c, 2) if Y < Kl: WCr = WLCr + (Y - Ymin) * (Wcr - WLCr) / (Kl - Ymin) WCb = WLCb + (Y - Ymin) * (Wcb - WLCb) / (Kl - Ymin) CrCenter = 154 - (Kl - Y) * (154 - 144) / (Kl - Ymin) CbCenter = 108 + (Kl - Y) * (118 - 108) / (Kl - Ymin) elif Y > Kh: WCr = WHCr + (Y - Ymax) * (Wcr - WHCr) / (Ymax - Kh) WCb = WHCb + (Y - Ymax) * (Wcb - WHCb) / (Ymax - Kh) CrCenter = 154 + (Y - Kh) * (154 - 132) / (Ymax - Kh) CbCenter = 108 + (Y - Kh) * (118 - 108) / (Ymax - Kh) if Y < Kl or Y > Kh: Cr = (Cr - CrCenter) * Wcr / WCr + 154 Cb = (Cb - CbCenter) * Wcb / WCb + 108 ######################################################################## # skin color detection #if Cb >= 80 and Cb <= 127 and Cr >= 141 and Cr <= 173: if Cb >= 77 and Cb <= 127 and Cr >= 140and Cr <= 175: skin = 1 # print 'Skin detected!' if 0 == skin: imgSkin[r,c] = 0 else: imgSkin[r,c] = 255 # display original image and skin image cv2.imshow("skin",imgSkin) return imgSkin #通过漫水填充去除背景 def removeBackground(srcImg): img = srcImg.copy() sp = img.shape mask = np.zeros((img.shape[0]+2,img.shape[1]+2),np.uint8) cv2.floodFill(img, mask, (5, 5), (255, 255, 255), (4.5, 4.5, 4.5), (3.5, 3.5, 3.5), 8) #mask = np.zeros((img.shape[0]+2,img.shape[1]+2),np.uint8) #cv2.floodFill(img, mask, (5,img.shape[0]-5), (255, 255, 255), (3, 3, 3), (3, 3, 3), 8) cv2.imshow("floodfill", img) return img #通过人脸检测裁剪人脸 def tailorImg(img,faces): if len(faces) == 1: for i,(x,y,w,h) in enumerate(faces): #注意不要越界 new_x = x - int(w/3) if x - int(w/3)>0 else 0 new_y = y - int(h/3) if y - int(h/3)>0 else 0 new_w = w +int(2/3*w) if new_x+w+int(2/3*w)<img.shape[1] else img.shape[1]-new_x new_h = h +int(2/3*h) if new_y+h +int(2/3*h)<img.shape[0] else img.shape[0]-new_y new_img = img[new_y:new_y+new_h,new_x:new_x+new_w] #cv2.imshow("new_img",new_img) return new_img #计算肤色部分的平均亮度 def meanBrightness(imgSKIN,imgGRAY): sp = imgSKIN.shape brightness = 0 count = 0 for i in range(sp[0]): for j in range(sp[1]): if imgSKIN[i,j] >100: brightness += imgGRAY[i,j] count +=1 if count !=0: return count,brightness/count else: return count,0 #轮廓完善 def skeletonComplete(imgResult,imgSKIN): kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) new_skin = imgSKIN new_skin = cv2.erode(new_skin, kernel) new_skin = cv2.dilate(new_skin, kernel) new_skin = cv2.erode(new_skin, kernel) new_skin = cv2.dilate(new_skin, kernel) new_skin = RemoveSmallRegion(new_skin,3000,0,1) new_skin = RemoveSmallRegion(new_skin,3000,1,1) cv2.imshow("new_skinHAHA",new_skin) new_skin = delete_jut(new_skin, 10, 10, 0) new_skin = delete_jut(new_skin, 10, 10, 1) new_skin = RemoveSmallRegion(new_skin,2000,0,1) new_skin = RemoveSmallRegion(new_skin,2000,1,1) cv2.imshow("new_skin",new_skin) #binary, contours, hierarchy = cv2.findContours(new_skin, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) #cv2.drawContours(binary, contours, -1, (0, 0, 255), 3) #cv2.imshow("inver",binary) img = cv2.GaussianBlur(new_skin, (3, 3), 0) # 高斯平滑处理原图像降噪 canny = cv2.Canny(img, 50, 150) # apertureSize默认为3 ret,skeleton = cv2.threshold(canny,100,255,cv2.THRESH_BINARY_INV) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) skeleton = cv2.erode(skeleton, kernel) #skeleton = cv2.erode(skeleton, kernel) result = cv2.bitwise_and(skeleton,imgResult) cv2.imshow("skeletonComplete",result) return result #去除二值图像边缘的突出部 def delete_jut(src,uthreshold,vthreshold,type): threshold = 0 dst = src.copy() sp = src.shape height = sp[0] width = sp[1] k = 0 mode = (1-type)*255 modeInver = 255-mode for i in range(height-1): for j in range(width-1): #行消除 if dst[i,j]== mode and dst[i,j+1] == modeInver: if j+uthreshold >= width: for k in range(j+1,width): dst[i,k] = mode else: for k in range(j+2,j+uthreshold+1): if dst[i,k] == mode: break if dst[i,k] == mode: for h in range(j+1,k): dst[i,h] = mode #列消除 if dst[i,j] == mode and dst[i+1,j] == modeInver: if i+vthreshold >= height: for k in range(i+1,height): dst[k,j] = mode else: for k in range(i+2,i+vthreshold+1): if dst[k,j] == mode: break if dst[k,j] == mode: for h in range(i+1,k): dst[h,j] = mode return dst #对图片进行处理 def RemoveSmallRegion(src,AreaLimit,CheckMode,NeiborMode): RemoveCount = 0 # 新建一幅标签图像初始化为0像素点,为了记录每个像素点检验状态的标签,0代表未检查,1代表正在检查, 2代表检查不合格(需要反转颜色),3代表检查合格或不需检查 # 初始化的图像全部为0,未检查 PointLabel = np.zeros(src.shape,np.uint8) dst = np.zeros(src.shape, np.uint8) sp = src.shape if(CheckMode == 1):#去除小连通区域的白色点,除去白色的 print("去除小连通域") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]<10: PointLabel[i,j] = 3#将背景黑色点标记为合格,像素为3 else: #除去黑色的 print("去除孔洞") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]>10: PointLabel[i,j] = 3#如果原图是白色区域,标记为合格,像素为3 NeiborPos = [] #将邻域压进容器 NeiborPos.append((-1,0)) NeiborPos.append((1, 0)) NeiborPos.append((0, -1)) NeiborPos.append((0, 1)) if NeiborMode ==1: print("Neighbor mode: 8邻域.") NeiborPos.append((-1, -1)) NeiborPos.append((-1, 1)) NeiborPos.append((1, -1)) NeiborPos.append((1, 1)) else: print("Neighbor mode: 4邻域.") NeihborCount = 4+4*NeiborMode; CurrX = 0 CurrY =0 for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 0: GrowBuffer = [] GrowBuffer.append((i,j)) PointLabel[i,j] = 1 CheckResult = 0 #在这里说一下,python的for循环有点奇葩,就是范围是静态的,第一次获取到范围值后就不会改变了 z=0 while z<len(GrowBuffer): for q in range(NeihborCount): CurrX = GrowBuffer[z][0]+NeiborPos[q][0] CurrY = GrowBuffer[z][1]+NeiborPos[q][1] if CurrX >=0 and CurrX < sp[0] and CurrY >=0 and CurrY<sp[1]: if PointLabel[CurrX,CurrY] == 0: GrowBuffer.append((CurrX,CurrY)) PointLabel[CurrX,CurrY] = 1 z += 1 #对整个连通域检查完 if len(GrowBuffer)>AreaLimit: CheckResult = 2 else: CheckResult = 1 RemoveCount +=1 for z in range(len(GrowBuffer)): CurrX = GrowBuffer[z][0] CurrY = GrowBuffer[z][1] PointLabel[CurrX,CurrY] += CheckResult CheckMode = 255*(1-CheckMode) for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 2: dst[i,j] = CheckMode if PointLabel[i,j] == 3: dst[i,j] = src[i,j] return dst def RemoveSelectRegion(src,AreaHigh,AreaLow,CheckMode,NeiborMode): RemoveCount = 0 # 新建一幅标签图像初始化为0像素点,为了记录每个像素点检验状态的标签,0代表未检查,1代表正在检查, 2代表检查不合格(需要反转颜色),3代表检查合格或不需检查 # 初始化的图像全部为0,未检查 PointLabel = np.zeros(src.shape,np.uint8) dst = np.zeros(src.shape, np.uint8) sp = src.shape if(CheckMode == 1):#去除小连通区域的白色点,除去白色的 print("去除小连通域") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]<10: PointLabel[i,j] = 3#将背景黑色点标记为合格,像素为3 else: #除去黑色的 print("去除孔洞") for i in range(sp[0]): for j in range(sp[1]): if src[i,j]>10: PointLabel[i,j] = 3#如果原图是白色区域,标记为合格,像素为3 NeiborPos = [] #将邻域压进容器 NeiborPos.append((-1,0)) NeiborPos.append((1, 0)) NeiborPos.append((0, -1)) NeiborPos.append((0, 1)) if NeiborMode ==1: print("Neighbor mode: 8邻域.") NeiborPos.append((-1, -1)) NeiborPos.append((-1, 1)) NeiborPos.append((1, -1)) NeiborPos.append((1, 1)) else: print("Neighbor mode: 4邻域.") NeihborCount = 4+4*NeiborMode; CurrX = 0 CurrY =0 for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 0: GrowBuffer = [] GrowBuffer.append((i,j)) PointLabel[i,j] = 1 CheckResult = 0 #在这里说一下,python的for循环有点奇葩,就是范围是静态的,第一次获取到范围值后就不会改变了 z=0 while z<len(GrowBuffer): for q in range(NeihborCount): CurrX = GrowBuffer[z][0]+NeiborPos[q][0] CurrY = GrowBuffer[z][1]+NeiborPos[q][1] if CurrX >=0 and CurrX < sp[0] and CurrY >=0 and CurrY<sp[1]: if PointLabel[CurrX,CurrY] == 0: GrowBuffer.append((CurrX,CurrY)) PointLabel[CurrX,CurrY] = 1 z += 1 #对整个连通域检查完 if len(GrowBuffer)> AreaHigh or len(GrowBuffer) < AreaLow: CheckResult = 2 else: CheckResult = 1 RemoveCount +=1 for z in range(len(GrowBuffer)): CurrX = GrowBuffer[z][0] CurrY = GrowBuffer[z][1] PointLabel[CurrX,CurrY] += CheckResult CheckMode = 255*(1-CheckMode) for i in range(sp[0]): for j in range(sp[1]): if PointLabel[i,j] == 2: dst[i,j] = CheckMode if PointLabel[i,j] == 3: dst[i,j] = src[i,j] return dst def myThreshold(imgGray,imgSkin,skinPoint,thresh): sp = imgGray.shape dst = imgGray.copy() for i in range(sp[0]): for j in range(sp[1]): if imgSkin[i,j] >100: if imgGray[i,j]>thresh: dst[i,j] = 255 else: dst[i,j] = 0 return dst def divisionThreshold(imgSKIN,imgFace): useless,theta = meanBrightness(imgSKIN=imgSKIN, imgGRAY=imgFace) print("平均亮度",theta) divisionCount = 30 #初始化数组大小 imgSegment = [None] * divisionCount imgSkinSegment = [None] * divisionCount for i in range(len(imgSegment)): imgSegment[i] = [0] * divisionCount imgSkinSegment[i] = [0] * divisionCount sp = imgSKIN.shape new_w = math.floor(sp[1]/divisionCount) new_h = math.floor(sp[0]/divisionCount) dst = imgSKIN.copy() dst = dst[0:new_h*divisionCount,0:new_w*divisionCount] newSkin = imgSKIN[0:new_h*divisionCount,0:new_w*divisionCount] for i in range(divisionCount): for j in range(divisionCount): imgSegment[i][j] = imgFace[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w] imgSkinSegment[i][j] = imgSKIN[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w] skinPoint,alpha = meanBrightness(imgSKIN=imgSkinSegment[i][j],imgGRAY=imgSegment[i][j]) if alpha !=0: min_th = min(alpha,theta) max_th = max(alpha,theta) #imgSegment[i][j] = myThreshold(imgSegment[i][j],imgSkinSegment[i][j],skinPoint,0.71*thresh) gamma = 0.63 lamda = 0.855 bata = 0.145 imgSegment[i][j] = myThreshold(imgSegment[i][j],imgSkinSegment[i][j],skinPoint,gamma*(lamda*max_th+bata*min_th)) for i in range(divisionCount): for j in range(divisionCount): dst[i*new_h:(i+1)*new_h,j*new_w:(j+1)*new_w]=imgSegment[i][j] ret,dst = cv2.threshold(dst,100,255,cv2.THRESH_BINARY) return dst,newSkin def processImg(img): kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) img = cv2.resize(img,(int(img.shape[1]/2) ,int(img.shape[0]/2)),interpolation=cv2.INTER_CUBIC) cv2.imshow("img",img) #获取到前景图,但是这里因为外层头发比较稀疏,所以可能会被误识别成肤色,所以用形态学操作把这层头发给去掉 imgFront = removeBackground(img) #眼睛和人脸检测 faces,eyes = detectEyes(img) if len(faces)<1: print("cannot detect the face") exit(0) temp = img.copy() mask = np.zeros((img.shape[0] + 2, img.shape[1] + 2), np.uint8) imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #获取到的人物头像前景图 imgFace = tailorImg(imgFront,faces) #获取imgFace的肤色图 imgFace_Skin = skinModel(imgFace) #################################################### #对肤色图进行修剪 skinTemp = cv2.erode(imgFace_Skin, kernel) skinTemp = cv2.dilate(skinTemp, kernel) #harlan imgFace_Skin = RemoveSmallRegion(skinTemp, 2000, 1, 1) imgFace_Skin = RemoveSelectRegion(imgFace_Skin, 2000,200, 0, 1) imgFace_Skin = RemoveSelectRegion(imgFace_Skin, 250,1, 0, 1) cv2.imshow("skinTemp", imgFace_Skin) imgFace_Gray = cv2.cvtColor(imgFace,cv2.COLOR_BGR2GRAY) #harlan======================================= #获取到作阈值化的阈值 #theta = meanBrightness(imgSKIN=imgFace_Skin,imgGRAY=imgFace_Gray) #进行阈值化 cv2.imshow("imgFace_gray",imgFace_Gray) imgFace_thresh,newSkin = divisionThreshold(imgSKIN=imgFace_Skin,imgFace=imgFace_Gray) #ret,imgFace_thresh = cv2.threshold(imgFace_Gray,0.7*int(theta),255,cv2.THRESH_BINARY) cv2.imshow("face_threshold",imgFace_thresh) #轮廓补充 result = skeletonComplete(imgFace_thresh,imgSKIN=newSkin) return result def createResult(): i = 1 while i <= 22: print(i) img = cv2.imread("img/" + str(i) + ".jpg", 1) img = cv2.medianBlur(img, 3) dst = processImg(img) dst = cv2.medianBlur(dst, 3) dst = RemoveSmallRegion(dst, 10, 0, 1) dst = delete_jut(dst, 1, 1, 1) dst = delete_jut(dst, 1, 1, 0) cv2.imwrite("result/" + str(i) + ".jpg", dst) i = i + 1 def unitTest(): img = cv2.imread("img/15.jpg",1) img = cv2.medianBlur(img,3) dst = processImg(img) dst = cv2.medianBlur(dst,3) #dst = RemoveSelectRegion(dst,10,0,0,1) dst = delete_jut(dst,1,1,1) dst = delete_jut(dst,1,1,0) cv2.imshow("result",dst) if __name__ == '__main__': gamma = 0.62 lamda = 0.6700 bata = 0.3300 unitTest() cv2.waitKey(0)
4c4df39de1bcc371a3155f31ebbf4481fea9e7f8
[ "Python" ]
23
Python
harlanhong/pythonProject
007a6a391a01448f40d6e4ccce07b2cd28f33ea3
00fe58b16073da46a0b701b05c52a92a10f124cb
refs/heads/master
<file_sep>FROM python:3.7 ADD requirements.txt /tmp/requirements.txt RUN pip install -r /tmp/requirements.txt RUN mkdir /code WORKDIR /code COPY . /code COPY docker-entrypoint.sh docker-entrypoint.sh RUN chmod +x docker-entrypoint.sh RUN apt-get install libfontconfig ENV BROKER_HOST 192.168.127.12 ENV BROKER_PORT 5672 ENV VIRTUAL_HOST 'yct' EXPOSE 5555 CMD /code/docker-entrypoint.sh <file_sep># celery_flower ### 启动命令 --- docker run --env BROKER_HOST=192.168.3.11 --env BROKER_PORT=5672 --env VIRTUAL_HOST='yct' --name flower -p 5555:5555 -d <file_sep>celery==4.3.0rc1 flower==0.9.3<file_sep>#!/bin/sh set -e celery flower --broker=amqp://cic_admin:JYcxys@3030@$BROKER_HOST:$BROKER_PORT/$VIRTUAL_HOST
2fbf37cd3210d8cd34158d5c78e4f68727f6b1c3
[ "Markdown", "Text", "Dockerfile", "Shell" ]
4
Dockerfile
HU-A-U/celery_flower_docker
f92eb3e17e67f7868be7bc1d70f9493b29d8b6a4
c54357658116a604357c98e5b202ba7c49f5c5f2
refs/heads/main
<file_sep>package com.dxc.repository; import org.springframework.data.mongodb.repository.MongoRepository; import com.dxc.document.Users; public interface UserRepository extends MongoRepository<Users, Integer> { }
f2de16316b34d6a3c301d1add7997be3f3163fbe
[ "Java" ]
1
Java
mmanoharan8/MONGODB-SPRINGBOOT
3ab4fab5835f36f6cbd104ae4f8c105a06ef62d5
fae48fd2e66d6f5154519b476921385df14a7b23
refs/heads/master
<file_sep># Random Quotes Generator This is a Random Quote Generator web application which displays to the user random quotes on the click of a button. User are also able to tweet out the quotes. This app was built using AJAX while utilizing a JSON-encoded, third party external API to fetch the quotes data. Twitter Web Intents was integrated to enable the tweets feature. ## Mockup Design ![alt tag](/images/design.jpg) ## Working Demo [Demo](https://nedu.github.io/RQG/) ![alt tag](/images/demo.png) ## Built With * HTML5 * CSS3 * Javascript (ES6+) * AJAX * Fetch API * [Random Famous Quotes API](https://market.mashape.com/andruxnet/random-famous-quotes) ## Authors * **<NAME>** ## License This project is licensed under the [MIT](https://choosealicense.com/licenses/mit/) License. <file_sep>const newQuote = document.querySelector('.newQuote'); const url = 'https://andruxnet-random-famous-quotes.p.mashape.com/'; const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'X-Mashape-Key': '<KEY>', Accept: 'application/json', }); // Get quote from API using fetch async function getQuote() { const res = await fetch(url, { headers }); const data = await res.json(); return [data.quote, data.author]; } // Display quote async function displayQuote() { const [quote, author] = await getQuote(); const quoteText = document.querySelector('.quote'); const authorText = document.querySelector('#author'); const tweetQuote = document.querySelector('.tweet'); quoteText.textContent = quote; authorText.textContent = author; tweetQuote.setAttribute('href', `https://twitter.com/intent/tweet?text=${quote}-${author}`); } newQuote.addEventListener('click', displayQuote); displayQuote();
8b1a2d1c94eeb3a08e4262c54408ab019412ad3f
[ "Markdown", "JavaScript" ]
2
Markdown
Nedu/RQG
c78e9ac60e5bceecacc8fb5ccc71570eb7253eb0
e188078e625d987daa0b5a789d43d6710f73ec50
refs/heads/master
<file_sep>package main import ( "bufio" "errors" "flag" "fmt" "github.com/garyburd/redigo/redis" "html/template" "io/ioutil" "log" "net" "net/http" "os" "regexp" ) var ( redis_address = "127.0.0.1:6379" validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$") templates = template.Must(template.ParseFiles("views/edit.html", "views/view.html", "views/parts.html")) addr = flag.Bool("addr", false, "find open address and print to final-port.txt") ) type Page struct { Title string Body []byte HTML template.HTML } func (p *Page) save() error { conn, err := redis.Dial("tcp", redis_address) defer conn.Close() if err != nil { fmt.Println(err) } conn.Send("MULTI") conn.Send("SET", p.Title, string(p.Body)) conn.Do("EXEC") reply, err := conn.Do("GET", p.Title) if err != nil { fmt.Println(err) } values, _ := redis.String(reply, nil) fmt.Println("BODY: ", values) filename := "data/" + p.Title + ".html" return ioutil.WriteFile(filename, p.Body, 0600) } func getTitle(w http.ResponseWriter, r *http.Request) (string, error) { m := validPath.FindStringSubmatch(r.URL.Path) if m == nil { http.NotFound(w, r) return "", errors.New("invalid page title") } return m[2], nil // The title is the second subexpression. } func loadPage(title string) (*Page, error) { conn, err := redis.Dial("tcp", redis_address) defer conn.Close() if err != nil { fmt.Println(err) } reply, err := conn.Do("GET", title) if err != nil { fmt.Println(err) } body, err := redis.String(reply, nil) if err != nil { return nil, err } fmt.Println("BODY: ", body) return &Page{Title: title, HTML: template.HTML(body)}, nil // return &Page{Title: title, Body: body, HTML: template.HTML(body)}, nil } func viewHandler(w http.ResponseWriter, r *http.Request, title string) { p, err := loadPage(title) if err != nil { http.Redirect(w, r, "/edit/"+title, http.StatusFound) return } renderTemplate(w, "view", p) } func editHandler(w http.ResponseWriter, r *http.Request, title string) { p, err := loadPage(title) if err != nil { p = &Page{Title: title} } renderTemplate(w, "edit", p) } func saveHandler(w http.ResponseWriter, r *http.Request, title string) { body := r.FormValue("body") // fmt.Println(r.PostForm) p := &Page{Title: title, Body: []byte(body)} err := p.save() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/view/"+title, http.StatusFound) } func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { err := templates.ExecuteTemplate(w, tmpl+".html", p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { m := validPath.FindStringSubmatch(r.URL.Path) // fmt.Println(m) if m == nil { http.NotFound(w, r) return } fn(w, r, m[2]) } } func AdminTerminal(port string) { fmt.Println("Listening @ " + port) exit := false for !exit { scanner := bufio.NewScanner(os.Stdin) fmt.Print("$ ") scanner.Scan() input := scanner.Text() if input == "quit" || input == "exit" { exit = true break } else if input == "reload" { templates = template.Must(template.ParseFiles("views/edit.html", "views/view.html", "views/parts.html")) input = "reloading templates...\n" } fmt.Println(input) } } func ExampleRedis() { conn, err := redis.Dial("tcp", redis_address) if err != nil { fmt.Println(err) } conn.Send("MULTI") conn.Send("SET", "hello", "world!") conn.Send("SET", "ilove", "ruby") conn.Do("EXEC") reply, err := conn.Do("GET", "hello") if err != nil { fmt.Println(err) } values, _ := redis.String(reply, nil) fmt.Println("REPLY: ", values) } func main() { port := ":8080" flag.Parse() http.HandleFunc("/view/", makeHandler(viewHandler)) http.HandleFunc("/edit/", makeHandler(editHandler)) http.HandleFunc("/save/", makeHandler(saveHandler)) // ExampleRedis(conn) if *addr { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { log.Fatal(err) } err = ioutil.WriteFile("final-port.txt", []byte(l.Addr().String()), 0644) if err != nil { log.Fatal(err) } s := &http.Server{} s.Serve(l) return } go http.ListenAndServe(port, nil) AdminTerminal(port) } <file_sep>Press ============ Content Management System (CMS) written in Go. <strong>Note:</strong> Unfinished project; currently under development. <file_sep>package press package main import ( "bufio" "errors" "flag" "fmt" "github.com/garyburd/redigo/redis" "html/template" "io/ioutil" "log" "net" "net/http" "os" "regexp" ) var ( redis_address = "127.0.0.1:6379" validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$") templates = template.Must(template.ParseFiles("views/edit.html", "views/view.html", "views/parts.html")) addr = flag.Bool("addr", false, "find open address and print to final-port.txt") ) type Page struct { Title string Body []byte HTML template.HTML }
9fc5bed28accef4dd25751b245083854156ed155
[ "Markdown", "Go" ]
3
Go
openwonk/press
13bb50a6b821aa1763776bd84f0a45a9c5cade39
1b933384cf285165a83d4452b2227e4f57c918c7
refs/heads/master
<file_sep>package tools.haha.com.androidtools.ui; import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.Scroller; import tools.haha.com.androidtools.MyApp; @SuppressWarnings("unused") public class MyScrollView extends ViewGroup { private static final String LOG_TAG = "VerticalViewPager"; private static final boolean DEBUG = true; private static final int MIN_DISTANCE_FOR_FLING = 25; // dips private static final int MIN_FLING_VELOCITY = 400; // dips private static final int CLOSE_ENOUGH = 2; // dp private static final int INVALID_POINTER = -1; public static final int SCROLL_STATE_IDLE = 0; /** * Indicates that the pager is currently being dragged by the user. */ public static final int SCROLL_STATE_DRAGGING = 1; /** * Indicates that the pager is in the process of settling to a final position. */ public static final int SCROLL_STATE_SETTLING = 2; private int mScrollState = SCROLL_STATE_IDLE; private VelocityTracker mVelocityTracker; private Scroller mScroller; private int mChildWidthMeasureSpec; private int mChildHeightMeasureSpec; private int mTouchSlop; private int mMinimumVelocity; private int mMaximumVelocity; private int mFlingDistance; private int mCloseEnough; private boolean mIsBeingDragged; private float mLastMotionX; private float mLastMotionY; private float mInitialMotionX; private float mInitialMotionY; private int mActivePointerId = -1; private int mTopShowingPage; private int mChildHeight; private int mOldScrollY; private GestureDetector mGestureDetector; public MyScrollView(Context context) { super(context); init(); } public MyScrollView(Context context, AttributeSet attrs) { this(context, attrs, 0); init(); } public MyScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init(){ Context context = getContext(); mTopShowingPage = 1; if(MyApp.getContext() == null){ Log.v("test_11", "ddddddddddddddddddddddddddddddddddddddddd"); } final ViewConfiguration configuration = ViewConfiguration.get(MyApp.getContext()); final float density = context.getResources().getDisplayMetrics().density; mTouchSlop = configuration.getScaledPagingTouchSlop(); mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density); mCloseEnough = (int) (CLOSE_ENOUGH * density); if(mScroller == null){ mScroller = new Scroller(getContext()); } mGestureDetector = new GestureDetector(this.getContext(), new MyGestureListener()); } /** * Any layout manager that doesn't scroll will want this. */ @Override public boolean shouldDelayChildPressedState() { return false; } /** * Ask all children to measure themselves and compute the measurement of this * layout based on the children. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int count = getChildCount(); int w = getDefaultSize(0, widthMeasureSpec); setMeasuredDimension(w, getDefaultSize(0, heightMeasureSpec)); final int measuredWidth = getMeasuredWidth(); int childWidthSize = measuredWidth - getPaddingLeft() - getPaddingRight(); int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom(); mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY); for (int i = 0; i < count; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int heightSpec = MeasureSpec.makeMeasureSpec( (int)(childHeightSize * lp.heightFactor), MeasureSpec.EXACTLY); child.measure(mChildWidthMeasureSpec, heightSpec); } } } /** * Position all children within this layout. */ @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { final int count = getChildCount(); int childLeft = 0; int childTop; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { mChildHeight = child.getMeasuredHeight(); childTop = mChildHeight * i; child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } // ---------------------------------------------------------------------- // The rest of the implementation is for custom per-child layout parameters. // If you do not need these (for example you are writing a layout manager // that does fixed positioning of its children), you can drop all of this. @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MyScrollView.LayoutParams(getContext(), attrs); } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams; } @Override public void computeScroll() { super.computeScroll(); if(mScroller.computeScrollOffset()){ scrollTo(0, mScroller.getCurrY()); invalidate(); } } private void setScrollState(int newState) { if (mScrollState == newState) { return; } mScrollState = newState; // if (mOnPageChangeListener != null) { // mOnPageChangeListener.onPageScrollStateChanged(newState); // } } private void completeScroll() { setScrollingCacheEnabled(false); mScroller.abortAnimation(); // int oldX = getScrollX(); // int oldY = getScrollY(); // int x = mScroller.getCurrX(); // int y = mScroller.getCurrY(); // if (oldX != x || oldY != y) { // scrollTo(x, y); // } } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = ev.getActionIndex(); final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionY = ev.getX(newPointerIndex); mActivePointerId = ev.getPointerId(newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } private void endDrag() { mOldScrollY = getScrollY(); mIsBeingDragged = false; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private void setScrollingCacheEnabled(boolean enabled) { // if (mScrollingCacheEnabled != enabled) { // mScrollingCacheEnabled = enabled; // if (USE_CACHE) { // final int size = getChildCount(); // for (int i = 0; i < size; ++i) { // final View child = getChildAt(i); // if (child.getVisibility() != GONE) { // child.setDrawingCacheEnabled(enabled); // } // } // } // } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { final int action = ev.getAction() & MotionEvent.ACTION_MASK; if(DEBUG){ Log.v(LOG_TAG, "onInterceptTouchEvent got action : " + action); } if(action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP){ mIsBeingDragged = false; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } return false; } if (action != MotionEvent.ACTION_DOWN) { if (mIsBeingDragged) { if(DEBUG){ Log.v(LOG_TAG, "onInterceptTouchEvent mIsBeingDragged is already true"); } return true; } } switch (action){ case MotionEvent.ACTION_DOWN: mInitialMotionX = mLastMotionX = ev.getX(); mInitialMotionY = mLastMotionY = ev.getY(); mActivePointerId = ev.getPointerId(0); mScroller.computeScrollOffset(); if (mScrollState == SCROLL_STATE_SETTLING && Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) { mScroller.abortAnimation(); //populate(); mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); } else { completeScroll(); mIsBeingDragged = false; } break; case MotionEvent.ACTION_MOVE: final int activePointerId = mActivePointerId; if(activePointerId == INVALID_POINTER){ if(DEBUG){ Log.v(LOG_TAG, "onInterceptTouchEvent got invalid pointer"); } break; } final int pointerIndex = ev.findPointerIndex(activePointerId); final float x = ev.getX(pointerIndex); final float dx = x - mLastMotionX; final float xDiff = Math.abs(dx); final float y = ev.getY(pointerIndex); final float dy = y - mLastMotionY; final float yDiff = Math.abs(dy); if(yDiff > mTouchSlop && yDiff * 0.5 > xDiff){ mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); setScrollingCacheEnabled(true); } break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; default: break; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); if(DEBUG){ Log.v(LOG_TAG, "onInterceptTouchEvent return : " + mIsBeingDragged); } return mIsBeingDragged; } @Override public boolean onTouchEvent(@NonNull MotionEvent ev) { if(mGestureDetector.onTouchEvent(ev)) { return true; } final int action = ev.getAction() & MotionEvent.ACTION_MASK; if(DEBUG){ Log.v(LOG_TAG, "onTouchEvent got action : " + action); } if (action == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { // Don't handle edge touches immediately -- they may actually belong to one of our // descendants. if(DEBUG){ Log.v(LOG_TAG, "onTouchEvent touch edges"); } return false; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); switch (action){ case MotionEvent.ACTION_DOWN: mScroller.abortAnimation(); mIsBeingDragged = true; break; case MotionEvent.ACTION_MOVE: if (!mIsBeingDragged) { final int pointerIndex = ev.findPointerIndex(mActivePointerId); final float x = ev.getX(pointerIndex); final float xDiff = Math.abs(x - mLastMotionX); final float y = ev.getY(pointerIndex); final float yDiff = Math.abs(y - mLastMotionY); if (yDiff > mTouchSlop && yDiff > xDiff) { mIsBeingDragged = true; } } if (mIsBeingDragged) { final int activePointerIndex = ev.findPointerIndex(mActivePointerId); final float y = ev.getY(activePointerIndex); scrollBy(0, (int)(mLastMotionY - y)); mLastMotionY = y; } break; case MotionEvent.ACTION_UP: //handleActionUp(ev); break; case MotionEvent.ACTION_POINTER_DOWN: final int index = ev.getActionIndex(); mLastMotionY = ev.getY(index); mActivePointerId = ev.getPointerId(index); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); mLastMotionY = ev.getY(ev.findPointerIndex(mActivePointerId)); break; default: break; } invalidate(); return true; } private void handleActionUp(MotionEvent ev){ final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId); int ceilingPage = (mChildHeight + getScrollY())/mChildHeight; final int activePointerIndex = ev.findPointerIndex(mActivePointerId); final float y = ev.getY(activePointerIndex); float motionDy = mInitialMotionY - y; mTopShowingPage = determineNextPage(ceilingPage, initialVelocity, motionDy); int dy = (mChildHeight)*(mTopShowingPage-1) - getScrollY(); mScroller.startScroll(0, getScrollY(), 0, dy, 1000); endDrag(); } private int determineNextPage(int ceilingPage, int velocity, float deltaY) { int nextPage; if (Math.abs(deltaY) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) { nextPage = velocity > 0 ? mTopShowingPage-1 : mTopShowingPage + 1; }else{ int pageInc = 0; if(Math.abs(deltaY / mChildHeight) > 0.3f){ if(mOldScrollY > getScrollY()){ ;//pageInc = -1; }else{ pageInc = 1; } } nextPage = ceilingPage + pageInc; } return nextPage; } /** * Custom per-child layout information. */ public static class LayoutParams extends MarginLayoutParams { float heightFactor = 0.8f; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } } private class MyGestureListener implements GestureDetector.OnGestureListener{ @Override public boolean onDown(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if(Math.abs(velocityY) > Math.abs(velocityX)){ fling((int) -velocityX, (int) -velocityY); return true; } return false; } private void fling(int velocityX, int velocityY) { // Before flinging, aborts the current animation. mScroller.forceFinished(true); // Begins the animation mScroller.fling( getScrollX(), getScrollY(), 0, velocityY, 0, 0, 0, (getChildCount()-1)*getChildAt(0).getHeight()); // Invalidates to trigger computeScroll() ViewCompat.postInvalidateOnAnimation(MyScrollView.this); } } } <file_sep>package tools.haha.com.androidtools.demo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import tools.haha.com.androidtools.R; public class PerfTestDemo extends Activity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_perf_test); findViewById(R.id.btn_long_runnable).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_long_runnable: startLongRunnable(); break; } } private void startLongRunnable(){ Handler handler = new Handler(getMainLooper()); handler.post(new Runnable() { @Override public void run() { try { Thread.sleep(3000); }catch (Exception e){ } } }); } } <file_sep>package tools.haha.com.androidtools.utils; public class DumpStackTrace { public static String dump(StackTraceElement[] stackTraceElements){ if(stackTraceElements == null || stackTraceElements.length == 0){ return ""; } String sep= System.getProperty("line.separator"); StringBuilder sb = new StringBuilder(); for (StackTraceElement element : stackTraceElements){ sb.append(element.toString()).append(sep); } return sb.toString(); } } <file_sep>package tools.haha.com.androidtools.perf_monitor; import android.os.*; import android.util.Log; import com.taobao.android.dexposed.DexposedBridge; import com.taobao.android.dexposed.XC_MethodHook; import java.lang.reflect.Field; import java.util.HashMap; public class RunnableMetrics { private HashMap<String, Long> mBeginTimeMap = new HashMap<>(); private XC_MethodHook methodHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { Message message = (Message)param.args[0]; try { Field callbackField = message.getClass().getDeclaredField("callback"); callbackField.setAccessible(true); Runnable runnable = (Runnable)callbackField.get(message); mBeginTimeMap.put(runnable.getClass().getName(), System.currentTimeMillis()); }catch (Exception e){ Log.e("RunnableMetrics", "beforeHookedMethod failed " + e.getMessage()); } super.beforeHookedMethod(param); } @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); long endTime = System.currentTimeMillis(); Message message = (Message)param.args[0]; try { Field callbackField = message.getClass().getDeclaredField("callback"); callbackField.setAccessible(true); Runnable runnable = (Runnable)callbackField.get(message); long duration = endTime - mBeginTimeMap.get(runnable.getClass().getName()); if(duration > 1000){ Log.e("RunnableMetrics", ">>>>>>>>>>>>>Run task { " + runnable.getClass().getName() + " } using " + duration + " ms"); } }catch (Exception e){ Log.e("RunnableMetrics", "afterHookedMethod failed " + e.getMessage()); } } }; public void start(){ try { Class<?> clazz = Class.forName("android.os.Handler"); DexposedBridge.findAndHookMethod(clazz, "handleCallback", Message.class, methodHook); }catch (Exception e){ Log.e("RunnableMetrics", "start failed " + e.getMessage()); } } } <file_sep>include ':app', ':patcha' <file_sep>package tools.haha.com.androidtools.utils; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; @SuppressWarnings("unused") public class SdcardLogger { private Handler mHandler; private static SdcardLogger mThis; private FileOutputStream mFile; private SdcardLogger(Context context, String filename){ HandlerThread thr = new HandlerThread("logger"); thr.start(); mHandler = new Handler(thr.getLooper()); // String path = CommonUtils.getInternalSdcardPath(context); // if (TextUtils.isEmpty(path)) { // path = CommonUtils.getExternalSdcardPath(context); // } // try { // mFile = new FileOutputStream(new File(path, filename)); // } catch (FileNotFoundException e) { // } } synchronized public static SdcardLogger getInstance(Context context, String filename) { if (mThis == null) mThis = new SdcardLogger(context, filename); return mThis; } public void Log(final String str){ mHandler.post(new Runnable(){ @Override public void run() { doPrint(str); } }); } private void doPrint(String str){ if(mFile != null) try { StringBuilder sb = new StringBuilder(); Date date=new Date(); SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String time=df.format(date); sb.append(time); sb.append(" "); sb.append(str); sb.append(System.getProperty("line.separator")); mFile.write(sb.toString().getBytes()); } catch (IOException e) { } } } <file_sep>package tools.haha.com.androidtools.ui; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.LayoutAnimationController; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import tools.haha.com.androidtools.utils.CommonUtils; @Deprecated @SuppressWarnings("unused") public class FlowLayout extends LinearLayout { private int mRowCount; private int mMaxCountEveryRow; private int mMinCountEveryRow; private int mMargin; private List<View> mViewList; private LayoutAnimationController mController; public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } public FlowLayout setRowCount(int count){ mRowCount = count; return this; } public FlowLayout setMaxCountEveryRow(int count){ mMaxCountEveryRow = count; return this; } public FlowLayout setMinCountEveryRow(int count){ mMinCountEveryRow = count; return this; } public FlowLayout setSpaceBetweenItem(int margin){ mMargin = margin; return this; } public void setLayoutAnimation(Animation animation){ mController = new LayoutAnimationController(animation); mController.setDelay(0); } public void build(){ mViewList = new ArrayList<>(); LinearLayout.LayoutParams firstRowParam = new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 0); LinearLayout.LayoutParams layoutParams= new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 0); int margin = CommonUtils.dp2px(getContext(), mMargin); layoutParams.setMargins(0, margin, 0, 0); layoutParams.weight = 1; firstRowParam.weight = 1; setOrientation(VERTICAL); for (int i = 0; i < mRowCount; ++i){ LinearLayout linearLayout = new LinearLayout(getContext()); if(i == 0){ linearLayout.setLayoutParams(firstRowParam); }else { linearLayout.setLayoutParams(layoutParams); } addView(linearLayout); } } public boolean addChild(View view){ if(mViewList.size() < mRowCount * mMaxCountEveryRow) { mViewList.add(view); return true; } return false; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int height; if(getChildCount() <= 0){ return; } View v0 = getChildAt(0); height = v0.getMeasuredHeight(); int heightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); int parentWidth = MeasureSpec.getSize(widthMeasureSpec); int viewIndex = 0; LinearLayout linearLayout; reset(); for(View view : mViewList){ int widthSpec = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST); view.measure(widthSpec, heightSpec); linearLayout = (LinearLayout)getChildAt(viewIndex); if(mController != null) { linearLayout.setLayoutAnimation(mController); } if(!addViewInLayout(linearLayout, view)){ if(viewIndex == mRowCount-1){ break; } viewIndex++; linearLayout = (LinearLayout)getChildAt(viewIndex); if(mController != null) { linearLayout.setLayoutAnimation(mController); } addViewInLayout(linearLayout, view); } } reMeasure(widthMeasureSpec, heightMeasureSpec); //super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private boolean addViewInLayout(LinearLayout linearLayout, View view){ LinearLayout.LayoutParams layoutParams = new LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); layoutParams.weight = 1; int margin = CommonUtils.dp2px(getContext(), mMargin); layoutParams.setMargins(margin, 0, 0, 0); LinearLayout.LayoutParams firstLayoutParams = new LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); firstLayoutParams.weight = 1; if(linearLayout.getChildCount() < mMinCountEveryRow){ if(0 == linearLayout.getChildCount()){ linearLayout.addView(view, firstLayoutParams); }else { linearLayout.addView(view, layoutParams); } return true; }else if(linearLayout.getChildCount() >= mMaxCountEveryRow){ return false; }else { int width = view.getMeasuredWidth(); int usedWidth = 0; for(int i = 0; i < linearLayout.getChildCount(); ++i){ View v = linearLayout.getChildAt(i); usedWidth += v.getMeasuredWidth(); usedWidth += (margin*i); } usedWidth += (getPaddingLeft() + getPaddingRight()); if(width + usedWidth + margin < linearLayout.getMeasuredWidth()){ linearLayout.addView(view, layoutParams); return true; } return false; } } private void reMeasure(int widthMeasureSpec, int heightMeasureSpec){ int count = getChildCount(); if(count <= 0){ return; } View v0 = getChildAt(0); int height = v0.getMeasuredHeight(); int heightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); int parentWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight(); float limit = 1.f/(float)mMaxCountEveryRow; for (int i = 0; i < count; ++i){ LinearLayout linearLayout = (LinearLayout)getChildAt(i); int childCount = linearLayout.getChildCount(); int leftWidth = parentWidth; for (int j = 0; j < childCount; ++j){ TextView tv = (TextView)linearLayout.getChildAt(j); int w = tv.getMeasuredWidth(); if(w < (int)Math.floor((float)parentWidth * limit)){ int actualWidth = (int)Math.ceil((float)parentWidth * limit); int widthSpec = MeasureSpec.makeMeasureSpec(actualWidth, MeasureSpec.EXACTLY); tv.measure(widthSpec, heightSpec); int margin = 0; if(j != 0){ margin = CommonUtils.dp2px(getContext(), mMargin); } leftWidth -= (tv.getMeasuredWidth() + margin); reMeasure(widthMeasureSpec, heightMeasureSpec); }else{ int widthSpec = MeasureSpec.makeMeasureSpec(leftWidth, MeasureSpec.AT_MOST); tv.measure(widthSpec, heightSpec); int margin = 0; if(j != 0){ margin = CommonUtils.dp2px(getContext(), mMargin); } leftWidth -= (tv.getMeasuredWidth() + margin); } } } } private void reset(){ for (int i = 0; i < getChildCount(); ++i){ LinearLayout linearLayout = (LinearLayout)getChildAt(i); linearLayout.removeAllViews(); } } }<file_sep>package tools.haha.com.androidtools.animator; import android.view.animation.Interpolator; /** * Bezier curve interpolator * #import from https//chromium.googlesource.com/chromium/src/+/22a0fbd00117465e9d451cc4d1758e8050052661/cc/animation/timing_function.cc */ @SuppressWarnings("unused") public class BezierCurveInterpolator implements Interpolator { private static final int MAX_STEPS = 30; private static final double BEZIER_EPSILON = 1e-7; private float mX1; private float mY1; private float mX2; private float mY2; public BezierCurveInterpolator(float x1, float y1, float x2, float y2){ mX1 = Math.min(Math.max(x1, 0.0f), 1.0f); mX2 = Math.min(Math.max(x2, 0.0f), 1.0f); mY1 = y1; mY2 = y2; } @Override public float getInterpolation(float x) { x = Math.min(Math.max(x, 0.0f), 1.0f); // Step 1. Find the t corresponding to the given x. I.e., we want t such that // eval_bezier(x1, x2, t) = x. There is a unique solution if x1 and x2 lie // within (0, 1). // // We're just going to do bisection for now (for simplicity), but we could // easily do some newton steps if this turns out to be a bottleneck. double t = 0.0; double step = 1.0; for (int i = 0; i < MAX_STEPS; ++i, step *= 0.5) { final double error = evalBezier(t, mX1, mX2) - x; if (Math.abs(error) < BEZIER_EPSILON) { break; } t += error > 0.0 ? -step : step; } // Step 2. Return the interpolated y values at the t we computed above. return (float)evalBezier(t, mY1, mY2); } private double evalBezier(double t, float v1, float v2) { final double x1_times_3 = 3.0 * v1; final double x2_times_3 = 3.0 * v2; final double h1 = x1_times_3 - x2_times_3 + 1.0; final double h2 = x2_times_3 - 6.0 * v1; return t * (t * (t * h1 + h2) + x1_times_3); } } <file_sep>package tools.haha.com.androidtools.demo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AbsListView; import android.widget.ListView; import android.widget.TextView; import tools.haha.com.androidtools.R; import tools.haha.com.androidtools.ui.ListViewAdapter; public class ListViewActivity extends Activity{ private ListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { Log.v("dexposed", "ListViewActivity::OnCreate was called"); super.onCreate(savedInstanceState); setContentView(R.layout.list_view_activity_layout); mListView = (ListView)findViewById(R.id.my_list_view); mListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // int extraCount = getRefreshableView().getHeaderViewsCount() + getRefreshableView().getFooterViewsCount(); // if (getChildCount() != extraCount // && mViewAnimator.getDisplayedChild() != NO_MORE_DATA_VIEW // && mViewAnimator.getDisplayedChild() != LOADING_VIEW // && getRefreshableView().getLastVisiblePosition() == view.getCount() - 1) { // waitForLoadingMoreData(); // } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // int scrollY; // int pos = firstVisibleItem - getRefreshableView().getHeaderViewsCount(); // if (pos >= 0) { // scrollY = mAdapter.getScrollY(pos); // if (scrollY >= SCREEN_HEIGHT3X) { // setUpButtonVisibility(true); // } else { // setUpButtonVisibility(false); // } // } else { // setUpButtonVisibility(false); // } } }); mListView.setAdapter(new ListViewAdapter(this)); } } <file_sep>package tools.haha.com.androidtools.demo; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; import tools.haha.com.androidtools.R; public class MyLocalService extends Service{ public static final String TAG = "_Plugin_"; private LocalBinder mBinder = new LocalBinder(); public class LocalBinder extends Binder { MyLocalService getService() { return MyLocalService.this; } } @Nullable @Override public IBinder onBind(Intent intent) { Log.v(TAG, "MyLocalService:onBind was called"); return mBinder; } @Override public void onDestroy() { super.onDestroy(); Log.v(TAG, "MyLocalService:onDestroyed was called"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.v(TAG, "MyLocalService:onStartCommand was called"); Toast.makeText(this, "service connected", Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onCreate() { super.onCreate(); Log.v(TAG, "MyLocalService:onCreate was called"); } public MyLocalService() { super(); } public void testService(){ Toast.makeText(this, getResources().getString(R.string.startLocalService), Toast.LENGTH_SHORT).show(); // Intent intent = new Intent(); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.setClassName(this, TestActivity.class.getName()); // startActivity(intent); } } <file_sep>package tools.haha.com.androidtools.demo; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; public class MyRemoteService extends Service{ public static final String TAG = "_Plugin_"; private RemoteBinder mBinder = new RemoteBinder(); public class RemoteBinder extends Binder { } @Nullable @Override public IBinder onBind(Intent intent) { Log.v(TAG, "MyRemoteService:onBind was called"); return mBinder; } @Override public void onDestroy() { super.onDestroy(); Log.v(TAG, "MyRemoteService:onDestroyed was called"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.v(TAG, "MyRemoteService:onStartCommand was called"); Toast.makeText(this, "service connected", Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onCreate() { super.onCreate(); Log.v(TAG, "MyRemoteService:onCreate was called"); } } <file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "tools.haha.com.androidtools" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { acdd { aaptOptions.additionalParameters '--ACDD-resoure-id', '0x5c', '--ACDD-shared-resources', rootProject.file("public.xml").getAbsolutePath() } normal { } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) //provided files('libs/android-support-v7.jar') compile 'com.android.support:appcompat-v7:23.1.0' compile 'com.facebook.stetho:stetho:1.2.0' debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3' //compile 'com.android.support:support-annotations:22.2.0' compile 'com.taobao.android:dexposed:0.1.1@aar' compile 'com.squareup:otto:1.3.8' } <file_sep>package tools.haha.com.androidtools.ui; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.LayoutAnimationController; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import tools.haha.com.androidtools.utils.CommonUtils; public class MyFlowLayout extends ViewGroup{ private static final float MIN_ITEM_WIDTH_RATIO = 0.333f; private int mRowCount; private int mMaxCountEveryRow; private int mMinCountEveryRow; private int mMargin; private List<TextView> mTmpList; private List<List<TextView>> mViewList; private LayoutAnimationController mController; private int mRowHeight; private boolean mHasAllocateRow; public MyFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public MyFlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } public MyFlowLayout(Context context) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int heightMode; heightMode = MeasureSpec.EXACTLY; int parentHeight = MeasureSpec.getSize(heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); widthMode = widthMode == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : widthMode; int parentWidth = MeasureSpec.getSize(widthMeasureSpec); if(mRowHeight == 0) { mRowHeight = parentHeight / mRowCount - mMargin * (mRowCount - 1); } widthMeasureSpec = MeasureSpec.makeMeasureSpec(parentWidth, widthMode); heightMeasureSpec = MeasureSpec.makeMeasureSpec(mRowHeight, heightMode); int leftWidth; if(!mHasAllocateRow){ for (int row = 0; row < mRowCount; ){ leftWidth = allocateRow(widthMeasureSpec, heightMeasureSpec, row); if(leftWidth > 0) { widthMeasureSpec = MeasureSpec.makeMeasureSpec(leftWidth, widthMode); }else{ //begin to measure next row leftWidth = parentWidth - getPaddingLeft() - getPaddingRight(); widthMeasureSpec = MeasureSpec.makeMeasureSpec(leftWidth, widthMode); measureRow(widthMeasureSpec, heightMeasureSpec, row); row++; } } } mHasAllocateRow = true; resizeViewInRow(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(parentWidth, parentHeight); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int oldLeft = left; for (List<TextView> list : mViewList){ left = oldLeft; for (TextView tv : list){ tv.layout(left, top, left + tv.getMeasuredWidth(), top + tv.getMeasuredHeight()); left += (tv.getMeasuredWidth() + mMargin); } top += (mRowHeight + mMargin); } } public MyFlowLayout setRowCount(int count){ mRowCount = count; return this; } public MyFlowLayout setMaxCountEveryRow(int count){ mMaxCountEveryRow = count; return this; } public MyFlowLayout setMinCountEveryRow(int count){ mMinCountEveryRow = count; return this; } public MyFlowLayout setSpaceBetweenItem(int margin){ mMargin = CommonUtils.dp2px(getContext(), margin); return this; } public void setLayoutAnimation(Animation animation){ mController = new LayoutAnimationController(animation); mController.setDelay(0); } public void create(){ mTmpList = new ArrayList<>(); mViewList = new ArrayList<>(); for (int i = 0; i < mRowCount; ++i){ List<TextView> viewList = new ArrayList<>(); mViewList.add(viewList); } } public void addTextView(TextView tv){ mTmpList.add(tv); addView(tv); } private int allocateRow(int widthMeasureSpec, int heightMeasureSpec, int row){ int parentWidth = MeasureSpec.getSize(widthMeasureSpec); //int parentHeight = MeasureSpec.getSize(heightMeasureSpec); TextView tv = mTmpList.get(0); List<TextView> listView = mViewList.get(row); tv.measure(widthMeasureSpec, heightMeasureSpec); if(listView.size() < mMinCountEveryRow){ listView.add(tv); mTmpList.remove(0); if(parentWidth - tv.getMeasuredWidth() - mMargin <= 0 && listView.size() < mMinCountEveryRow){ return 1; } }else if(listView.size() < mMaxCountEveryRow){ int usedWidth = 0; for (TextView v : listView){ usedWidth += v.getMeasuredWidth(); usedWidth += mMargin; } if(parentWidth - usedWidth > 0){ listView.add(tv); mTmpList.remove(0); }else { return -1; } }else { return -1; } return parentWidth - tv.getMeasuredWidth() - mMargin; } /** * ensure the width of every child view exceeds 1/3 of parent width */ private void resizeViewInRow(int widthMeasureSpec, int heightMeasureSpec){ // int parentWidth = MeasureSpec.getSize(widthMeasureSpec); // for (List<TextView> listView : mViewList){ // for (TextView tv : listView){ // int w = tv.getMeasuredWidth(); // if(w < (int)(float)parentWidth * MIN_ITEM_WIDTH_RATIO){ // w = (int)((float)parentWidth * MIN_ITEM_WIDTH_RATIO); // int widthSpec = MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY); // tv.measure(widthSpec, heightMeasureSpec); // } // } // } } private void measureRow(int widthMeasureSpec, int heightMeasureSpec, int row){ // int heightMode = MeasureSpec.getMode(heightMeasureSpec); // int parentHeight = MeasureSpec.getSize(heightMeasureSpec); // int widthMode = MeasureSpec.getMode(widthMeasureSpec); int parentWidth = MeasureSpec.getSize(widthMeasureSpec); List<TextView> listView = mViewList.get(row); int leftWidth = parentWidth; for (int i = 0; i < listView.size(); i++){ TextView tv = listView.get(i); leftWidth -= tv.getMeasuredWidth(); leftWidth -= mMargin; if(leftWidth <= 0){ if(i == 0){ int usedWidth = mMargin + getPaddingLeft() + getPaddingRight(); widthMeasureSpec = MeasureSpec.makeMeasureSpec((parentWidth - usedWidth)/2, MeasureSpec.EXACTLY); tv.measure(widthMeasureSpec, heightMeasureSpec); TextView secondView = listView.get(1); secondView.measure(widthMeasureSpec, heightMeasureSpec); return; }else { int totalWidth = 0; for(int j = 0; j <= i; ++j){ totalWidth += listView.get(j).getMeasuredWidth(); } int leftParentWidth = parentWidth - ((listView.size() - 1) * mMargin + getPaddingLeft() + getPaddingRight()); for(int j = 0; j <= i; ++j){ int w = listView.get(j).getMeasuredWidth(); w = (int)((float)leftParentWidth * ((float)w / (float)totalWidth)); widthMeasureSpec = MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY); TextView v = listView.get(j); v.measure(widthMeasureSpec, heightMeasureSpec); } return; } } } int totalWidth = 0; for(int j = 0; j < listView.size(); ++j){ totalWidth += listView.get(j).getMeasuredWidth(); } if(totalWidth < parentWidth){ int leftParentWidth = parentWidth - ((listView.size() - 1) * mMargin + getPaddingLeft() + getPaddingRight()); for(int j = 0; j < listView.size(); ++j){ int w = listView.get(j).getMeasuredWidth(); w = (int)((float)leftParentWidth * ((float)w / (float)totalWidth)); widthMeasureSpec = MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY); TextView v = listView.get(j); v.measure(widthMeasureSpec, heightMeasureSpec); } } } }
553789997d773789dfd92f7befe525b06f4d08cd
[ "Java", "Gradle" ]
13
Java
chriszheng124/haha
879f73402e784e14fd4610e00eaef20cb69217f9
d96a7211acd8e6f3cc350c2fc8570da8c21de305
refs/heads/master
<repo_name>ripburn/clash_block<file_sep>/Assets/Racket.cs using UnityEngine; using System.Collections; public class Racket : MonoBehaviour { private float accel = 1000.0f; private Vector3 pos; // Use this for initialization void Start () { } // Update is called once per frame void Update () { /*this.GetComponent<Rigidbody> ().AddForce ( transform.right * Input.GetAxisRaw ("Horizontal") * accel, ForceMode.Impulse);*/ App_Touch.TouchInfo touch = App_Touch.GetTouch (); if (touch == App_Touch.TouchInfo.Began) { } if (touch == App_Touch.TouchInfo.Moved) { pos = App_Touch.GetTouchPosition(); pos.y = 0.0f; pos.z = -6.0f; transform.position = pos; } if (touch == App_Touch.TouchInfo.Ended) { } } } <file_sep>/Assets/App_Touch.cs using UnityEngine; using System.Collections; public class App_Touch : MonoBehaviour { private static Vector3 TouchPosition = Vector3.zero; private static Vector3 Position; private static Vector3 Worldposition; public enum TouchInfo{ None = 99, Began = 0, Moved = 1, Stationary = 2, Ended = 3, Canceled = 4 } public static TouchInfo GetTouch(){ if (Application.isEditor) { if (Input.GetMouseButtonDown (0)) { return TouchInfo.Began; } if (Input.GetMouseButton (0)) { return TouchInfo.Moved; } if (Input.GetMouseButtonUp (0)) { return TouchInfo.Ended; } } else { if (Input.touchCount > 0) { return (TouchInfo)((int)Input.GetTouch (0).phase); } } return TouchInfo.None; } public static Vector3 GetTouchPosition(){ if (Application.isEditor) { TouchInfo touch = App_Touch.GetTouch (); if (touch != TouchInfo.None) { Position = Input.mousePosition; Position.z = 20.0f; Worldposition = Camera.main.ScreenToWorldPoint(Position); return Worldposition; } } else { if (Input.touchCount > 0) { Touch touch = Input.GetTouch (0); TouchPosition.x = touch.position.x; TouchPosition.y = touch.position.y; TouchPosition.z = 20.0f; Worldposition = Camera.main.ScreenToWorldPoint(TouchPosition); return Worldposition; } } return Vector3.zero; } }
20290821f2971c71239b5c2e448a8f71785581dd
[ "C#" ]
2
C#
ripburn/clash_block
e99e3da4ffb1b9c593416996d45b849ae5121fe9
506697fc648c8b09f20ece4692fe20e78beb475a
refs/heads/master
<repo_name>cjp4/cargo-ws<file_sep>/src/main/java/org/oltursa/cargows/cargo/service/IMenuService.java package org.oltursa.cargows.cargo.service; import org.oltursa.cargows.cargo.model.Menu; import org.oltursa.cargows.cargo.transport.menu.request.MenuRequest; import org.oltursa.cargows.cargo.transport.menu.response.MenuResponse; public interface IMenuService extends ICRUD<Menu>{ public MenuResponse RecoveryMenu(MenuRequest menuRequest); } <file_sep>/README.md # cargo-ws <file_sep>/src/main/java/org/oltursa/cargows/cargo/service/impl/MenuServiceImpl.java package org.oltursa.cargows.cargo.service.impl; import java.util.ArrayList; import java.util.List; import org.oltursa.cargows.cargo.model.Menu; import org.oltursa.cargows.cargo.repo.IMenuRepo; import org.oltursa.cargows.cargo.service.IMenuService; import org.oltursa.cargows.cargo.transport.menu.request.MenuRequest; import org.oltursa.cargows.cargo.transport.menu.response.MenuResponse; import org.oltursa.cargows.cargo.transport.menu.result.MenuResult; import org.oltursa.cargows.pax.model.User; import org.oltursa.cargows.pax.repo.IUserRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MenuServiceImpl implements IMenuService{ @Autowired private IMenuRepo menuRepo; @Autowired private IUserRepo userRepo; @Override public MenuResponse RecoveryMenu(MenuRequest menuRequest) { List<User> lstUsuario = new ArrayList<User>(); userRepo.GetPaxUsuario(menuRequest.getParameter().getSusuario()).forEach( x -> { User obj = new User(); obj.setCusuario(Integer.parseInt(String.valueOf(x[0]))); obj.setCempresa(Integer.parseInt(String.valueOf(x[1]))); obj.setCcanal(Integer.parseInt(String.valueOf(x[2]))); obj.setCoficina(Integer.parseInt(String.valueOf(x[3]))); obj.setDusuario(String.valueOf(x[4])); obj.setSusuario(String.valueOf(x[5])); lstUsuario.add(obj); }); List<MenuResult> lstmenuPadre = new ArrayList<MenuResult>(); if(lstUsuario.size() > 0) { menuRepo.GetMenuPadreXUsuario(lstUsuario.get(0).getCusuario()).forEach( x -> { MenuResult objPadre = new MenuResult(); objPadre.setCmenu(Integer.parseInt(String.valueOf(x[0]))); objPadre.setDmenu(String.valueOf(x[2])); objPadre.setIcon_name(String.valueOf(x[3])); objPadre.setUrl(String.valueOf(x[4])); objPadre.setIactivo(Integer.parseInt(String.valueOf(x[5]))); objPadre.setChildren(new ArrayList<Menu>()); menuRepo.GetMenuHijoXUsuario(lstUsuario.get(0).getCusuario()).forEach( a -> { Menu objHijo = new Menu(); objHijo.setCmenu(Integer.parseInt(String.valueOf(a[0]))); objHijo.setCmenu_padre(Integer.parseInt(String.valueOf(a[1]))); objHijo.setDmenu(String.valueOf(a[2])); objHijo.setIcon_name(String.valueOf(a[3])); objHijo.setUrl(String.valueOf(a[4])); objHijo.setIactivo(Integer.parseInt(String.valueOf(a[5]))); if(objPadre.getCmenu() == objHijo.getCmenu_padre()) { objPadre.getChildren().add(objHijo); } }); lstmenuPadre.add(objPadre); }); } MenuResponse result = new MenuResponse(); result.setResult(lstmenuPadre); return result; } @Override public Menu registrar(Menu obj) { // TODO Auto-generated method stub return null; } @Override public Menu modificar(Menu obj) { // TODO Auto-generated method stub return null; } @Override public Menu listarPorId(Integer id) { // TODO Auto-generated method stub return null; } @Override public List<Menu> listar() { // TODO Auto-generated method stub return null; } @Override public void eliminar(Integer id) { // TODO Auto-generated method stub } } <file_sep>/src/main/java/org/oltursa/cargows/cargo/controller/MenuController.java package org.oltursa.cargows.cargo.controller; import org.oltursa.cargows.cargo.service.IMenuService; import org.oltursa.cargows.cargo.transport.menu.request.MenuRequest; import org.oltursa.cargows.cargo.transport.menu.response.MenuResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/menu") public class MenuController { @Autowired private IMenuService service; @PostMapping(value = "/recoveryMenu", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<MenuResponse> validar(@RequestBody MenuRequest menuRequest) { return new ResponseEntity<MenuResponse>(service.RecoveryMenu(menuRequest), HttpStatus.OK); } }
5f365682b09082838aef2edfb9355abe4eb28f43
[ "Markdown", "Java" ]
4
Java
cjp4/cargo-ws
a8116b259a4ca79e698f959bba91c39cf58b09e8
377511980e24d1946b636015ebc93df4c85ce3ec
refs/heads/master
<repo_name>mdornfe1/thesis<file_sep>/fluid/fluid_figs/res_freqs.py from pylab import * plt.style.use('bmh') def calc_phi(x, kn): return sin(kn*x) L = 10 a = 1 k = arange(0, 0.7, 0.001) n = arange(0, 5, 1) kn_list = n*pi/(L+a/3/pi)/a fig, ax = subplots() ax.plot(k, tan(k*L/a)+2*k/3/pi, label='Characteristic equation ') ax.plot(kn_list, zeros(len(n)), 'o', label='End correction resonance frequencies ') ax.set_xlabel('ka') ax.set_ylim(-10,10) ax.set_xlim(-0.01,0.7) ax.legend() kn_list = n*pi/(L+a/3/pi)/2 x = np.arange(0, L, 0.1) fig, ax = subplots() for m, kn in enumerate(kn_list): phi = calc_phi(x, kn) ax.plot(x/L, phi, label='m='+str(m)) ax.set_title('Resonance Modes') ax.set_xlabel('xL') ax.legend(loc=3) <file_sep>/fluid/fluid_figs/plot_impedance.py from pylab import * from scipy.special import struve, jv plt.style.use('bmh') def X(x): return struve(1, x) / x def R(x): return 1 - jv(1, 2*x) / x x = np.arange(0.0001, 100, 0.01) fig, ax = subplots() ax.loglog(x, X(x), label='X(ka)') ax.loglog(x, R(x), label='R(ka)') ax.set_xlabel('ka')<file_sep>/anatomy/anatomy_figs/titze_model.py import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint def odefun(x, t): xdot = np.zeros(2) L = 0.014 tau = 0.001 ps = 10 k = 3e3 b = 1230 m = 476 a1 = 0.01 + x[0] + tau * x[1] a2 = 0.01 + x[0] - tau * x[1] pg = ps * (1 - a2 / a1) print(a1) xdot[0] = x[1] xdot[1] = - k/m * x[0] - b/m * x[1] + pg return xdot x0 = np.array([1, 1]) t = np.arange(0,1,0.001) x = odeint(odefun, x0, t) plot(x[:,0])
96c5bd8667d88358223aca4e63541ae25f074b49
[ "Python" ]
3
Python
mdornfe1/thesis
b5b03f04aa0376ab1d47fbb8c94075574d44d6c5
91fc1f3c335a3b7b6e66a8d5922fd9ff26cdfbc6
refs/heads/master
<file_sep>// Global Variables var allDocumentPages = new Array(); (function($) { $(document).ready(function() { $('#btn_reset').click(function() { allDocumentPages = new Array(); $('#documents_processed').html(""); $('#pages_printed').html(""); }); if (window.File && window.FileReader && window.FileList && window.Blob) { // Great, all the file APIs supported // Apply our own actions to dragover $('#drop_zone').bind('dragover', function (e) { e.stopPropagation(); e.preventDefault(); e.originalEvent.dataTransfer.dropEffect = 'copy'; // Explicitly show as copy }); // And to drop $('#drop_zone').bind('drop', function (e) { e.stopPropagation(); e.preventDefault(); var files = e.originalEvent.dataTransfer.files; // FileList object $.each(files, function() { var reader = new FileReader(); var documentPages = new Array(); reader.readAsText(this); reader.onload = (function (f) { return function (evt) { $.each(evt.target.result.split('\n'), function () { if (this != "" && this != null ) { tempArray = this.split('|'); documentPages.push(tempArray[1]); } }); }; })(this); reader.onloadend = function () { var twoSidedPages = 0; var oneSidedPages = 0; $.each(documentPages, function () { allDocumentPages.push(parseInt(this)); }); $.each(allDocumentPages, function () { var currentNumberOfPages = parseInt(this); twoSidedPages += parseInt(currentNumberOfPages / 2); oneSidedPages += currentNumberOfPages % 2; }); $('#documents_processed').html(allDocumentPages.length + " documents processed"); $('#pages_printed').html(twoSidedPages + " double sided pages, " + oneSidedPages + " single sided pages"); }; }); }); } else { // Uh oh, no file APIs supported alert('The file APIs are not fully supported in this browser.'); } }); })(jQuery)<file_sep>Page Helper Counts single and double sided pages printed, read from a pipe deliniated file Simply drag and drop desired files to be processed in to the noted area on the page
ab2909a1c6af5409f3390c9bb9f2a2cf0afd56c5
[ "JavaScript", "Markdown" ]
2
JavaScript
tinnvec/page_counter
3104c3956f097efd76344901e5308bd07e8cc6a6
639ce5d85bf2929d12ab852226626b49a88ae816
refs/heads/master
<repo_name>jesantana/ConcesionarioVirtual<file_sep>/Otros.cs using System; using System.Drawing.Imaging; using System.Drawing; using Tao.OpenGl; using System.Windows.Forms; public class Otros { public static int[] texture; public Otros() { // // TODO: Add constructor logic here // } public static void LoadTexture() { Bitmap bitmap=null; BitmapData bitmapData=null; string[] tx={"relojes.bmp","ford1.bmp","benz1.jpg","motor.bmp","acelera.bmp","papel1.jpg","piso.jpg","madera2.jpg","madera3.jpg","papel1.jpg","Focus.jpg","fordrunner.jpg","mbne.jpg","particle.bmp","benz.jpg"}; Gl.glEnable(Gl.GL_TEXTURE_2D); Gl.glEnable(Gl.GL_DEPTH_TEST); // Gl.gl.Gl.glEnable(Gl.gl.Gl.gl_BLEND); // Gl.gl.Gl.glBlendFunc(Gl.gl.Gl.gl_SRC_ALPHA,Gl.gl.Gl.gl_ONE_MINUS_SRC_ALPHA); Rectangle rect; texture=new int[tx.Length]; Gl.glGenTextures(tx.Length, texture); for(int i=0; i<tx.Length; i++) { bitmap = new Bitmap(Application.StartupPath + "\\" + "Textures\\"+tx[i]); rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); bitmapData =bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture[i]); Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D, (int) Gl.GL_RGB8, bitmap.Width, bitmap.Height, Gl.GL_BGR_EXT, Gl.GL_UNSIGNED_BYTE, bitmapData.Scan0); } Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_S, Gl.GL_REPEAT); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_T, Gl.GL_REPEAT); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR); Gl.glTexEnvf(Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_MODE, Gl.GL_DECAL); Gl.glBindTexture(Gl.GL_TEXTURE_2D, 0); bitmap.UnlockBits(bitmapData); bitmap.Dispose(); } } <file_sep>/IElement.cs using System; public interface IElement { void Draw(); void Recompile(); float Width{ get; set; } Point3D PuntoRotacion{ get; } void RotateX(int direction); void RotateY(int direction); void RotateZ(int direction); string GetObjName(int id); int Id{ get; } } <file_sep>/OGLConFlechita.cs using System; using System.ComponentModel; using System.Windows.Forms; public class OGLConFlechita:Tao.Platform.Windows.SimpleOpenGlControl { public OGLConFlechita():base() { // // TODO: Add constructor logic here // } protected override bool IsInputChar(char charCode) { if(charCode==(char)Keys.Up || charCode==(char)Keys.Down || charCode==(char)Keys.Left || charCode==(char)Keys.Right )return true; return base.IsInputChar (charCode); } } <file_sep>/RC.cs using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Materiales; public class RC : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.Button button5; private System.Windows.Forms.Button button6; private System.Windows.Forms.Button button7; private System.Windows.Forms.Button button8; private System.Windows.Forms.Button button9; private System.Windows.Forms.Button button10; Form1 form; /// <summary> /// Required designer variable. /// </summary> public RC(Form1 fo) { // // Required for Windows Form Designer support // InitializeComponent(); form=fo; // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.button5 = new System.Windows.Forms.Button(); this.button6 = new System.Windows.Forms.Button(); this.button7 = new System.Windows.Forms.Button(); this.button8 = new System.Windows.Forms.Button(); this.button9 = new System.Windows.Forms.Button(); this.button10 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label1.ForeColor = System.Drawing.Color.Aqua; this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(208, 32); this.label1.TabIndex = 0; this.label1.Text = "Control Remoto"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // button1 // this.button1.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button1.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button1.Location = new System.Drawing.Point(8, 80); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(208, 32); this.button1.TabIndex = 1; this.button1.Text = "Cambiar Color"; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button2.Location = new System.Drawing.Point(8, 112); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(208, 32); this.button2.TabIndex = 2; this.button2.Text = "Abrir Maletero"; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button3.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button3.Location = new System.Drawing.Point(8, 144); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(208, 32); this.button3.TabIndex = 3; this.button3.Text = "Abrir Capo"; this.button3.Click += new System.EventHandler(this.button3_Click); // // button4 // this.button4.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button4.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button4.Location = new System.Drawing.Point(8, 176); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(208, 32); this.button4.TabIndex = 4; this.button4.Text = "Quitar Techo"; this.button4.Click += new System.EventHandler(this.button4_Click); // // button5 // this.button5.Enabled = false; this.button5.Font = new System.Drawing.Font("Rockwell", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button5.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button5.Location = new System.Drawing.Point(8, 208); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(208, 32); this.button5.TabIndex = 5; this.button5.Text = "Para sentarse tiene que estar detenido"; this.button5.Click += new System.EventHandler(this.button5_Click); // // button6 // this.button6.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button6.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button6.Location = new System.Drawing.Point(8, 272); this.button6.Name = "button6"; this.button6.Size = new System.Drawing.Size(208, 32); this.button6.TabIndex = 6; this.button6.Text = "Encender Motor!!!"; this.button6.Click += new System.EventHandler(this.button6_Click); // // button7 // this.button7.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button7.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button7.Location = new System.Drawing.Point(8, 240); this.button7.Name = "button7"; this.button7.Size = new System.Drawing.Size(208, 32); this.button7.TabIndex = 7; this.button7.Text = "Detener Rotacion"; this.button7.Click += new System.EventHandler(this.button7_Click); // // button8 // this.button8.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button8.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button8.Location = new System.Drawing.Point(8, 304); this.button8.Name = "button8"; this.button8.Size = new System.Drawing.Size(208, 32); this.button8.TabIndex = 8; this.button8.Text = "LimpiaParabrisas/On"; this.button8.Click += new System.EventHandler(this.button8_Click); // // button9 // this.button9.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button9.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button9.Location = new System.Drawing.Point(8, 336); this.button9.Name = "button9"; this.button9.Size = new System.Drawing.Size(208, 40); this.button9.TabIndex = 9; this.button9.Text = "Cambiar oscuridad a los cristales"; this.button9.Click += new System.EventHandler(this.button9_Click); // // button10 // this.button10.Location = new System.Drawing.Point(8, 376); this.button10.Name = "button10"; this.button10.Size = new System.Drawing.Size(208, 32); this.button10.TabIndex = 10; this.button10.Text = "Ver Solo Interior"; this.button10.Click += new System.EventHandler(this.button10_Click); // // RC // this.AutoScaleBaseSize = new System.Drawing.Size(8, 18); this.BackColor = System.Drawing.Color.Maroon; this.ClientSize = new System.Drawing.Size(224, 496); this.Controls.Add(this.button10); this.Controls.Add(this.button9); this.Controls.Add(this.button8); this.Controls.Add(this.button7); this.Controls.Add(this.button6); this.Controls.Add(this.button5); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Location = new System.Drawing.Point(10, 10); this.Name = "RC"; this.Opacity = 0.5; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "RC"; this.TopMost = true; this.ResumeLayout(false); } #endregion private void button2_Click(object sender, System.EventArgs e) { if(button2.Text=="Abrir Maletero") { ((Lugar)form.scene.element).bas.car.actList.Add("maletero"); button2.Text="Cerrar Maletero"; } else { ((Lugar)form.scene.element).bas.car.actList.Remove("maletero"); button2.Text="Abrir Maletero"; } ((Lugar)form.scene.element).bas.car.Recompile(); form.Focus(); form.Refresh(); } private void button4_Click(object sender, System.EventArgs e) { if(button4.Text=="Quitar Techo") { ((Lugar)form.scene.element).bas.car.actList.Add("descapotable"); button4.Text="Poner Techo"; } else { ((Lugar)form.scene.element).bas.car.actList.Remove("descapotable"); button4.Text="Quitar Techo"; } ((Lugar)form.scene.element).bas.car.Recompile(); form.Focus(); form.Refresh(); } private void button3_Click(object sender, System.EventArgs e) { if(button3.Text=="Abrir Capo") { ((Lugar)form.scene.element).bas.car.actList.Add("capo"); button3.Text="Cerrar Capo"; } else { ((Lugar)form.scene.element).bas.car.actList.Remove("capo"); button3.Text="Abrir Capo"; } ((Lugar)form.scene.element).bas.car.Recompile(); form.Focus(); form.Refresh(); } private void button1_Click(object sender, System.EventArgs e) { Col c1=new Col(((Lugar)form.scene.element).bas.car.Colores); c1.ShowDialog(); int x=c1.selInd; c1.Close(); form.Focus(); ((Lugar)form.scene.element).bas.car.ChangeMaterialFrom3ds("body",new MiMetal(((Lugar)form.scene.element).bas.car.Colores[x].r,((Lugar)form.scene.element).bas.car.Colores[x].g,((Lugar)form.scene.element).bas.car.Colores[x].b)); ((Lugar)form.scene.element).bas.car.Recompile(); form.Focus(); form.Refresh(); } private void button5_Click(object sender, System.EventArgs e) { //form.scene.cam.SetPos(((Lugar)form.scene.element).bas.car.OrigenVistaInt(),((Lugar)form.scene.element).bas.car.ObjetivoVistaInt(((Lugar)form.scene.element).bas.crang),0,1,0); Lugar l=(Lugar)form.scene.element; Point3D p1=l.bas.car.ObjetivoVistaInt(l.bas.crang); Point3D p=l.bas.car.OrigenVistaInt(); form.scene.OrigCam=new Point3D(p.x,p.y,p.z); form.scene.ObjCam=new Point3D(p1.x,p1.y,p1.z); form.Focus(); //form.Refresh(); } private void button7_Click(object sender, System.EventArgs e) { if(button7.Text=="Detener Rotacion") { ((Lugar)form.scene.element).bas.rotando=false; button5.Font=new System.Drawing.Font("Rockwell", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); button5.Text="Sentarse Adentro"; button5.Enabled=true; button7.Text="Reanudar Rotacion"; } else { ((Lugar)form.scene.element).bas.rotando=true; button5.Font=new System.Drawing.Font("Rockwell", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));; button5.Text="Para sentarse tiene que estar detenido"; button5.Enabled=false; button7.Text="Detener Rotacion"; } form.Focus(); form.Refresh(); } private void button6_Click(object sender, System.EventArgs e) { if(button6.Text=="Encender Motor!!!") { ((Lugar)form.scene.element).bas.car.EnciendeTubEsc(true); button6.Text="Apagar Motor"; } else { ((Lugar)form.scene.element).bas.car.EnciendeTubEsc(false); button6.Text="Encender Motor!!!"; } form.Focus(); } private void button8_Click(object sender, System.EventArgs e) { if(button8.Text=="LimpiaParabrisas/On") { ((Lugar)form.scene.element).bas.car.EnciendeParabrisas(true); button8.Text="LimpiaParabrisas/Off"; } else { ((Lugar)form.scene.element).bas.car.EnciendeParabrisas(false); button8.Text="LimpiaParabrisas/On"; } form.Focus(); } private void button9_Click(object sender, System.EventArgs e) { calob calb=new calob(((Lugar)form.scene.element).bas.car.OscuridadCristal,form); calb.ShowDialog(); form.Focus(); } private void button10_Click(object sender, System.EventArgs e) { if(button10.Text=="Ver Solo Interior") { ((Lugar)form.scene.element).bas.car.todo=false; button10.Text="Ver Carro Completo"; } else { ((Lugar)form.scene.element).bas.car.todo=true; button10.Text="Ver Solo Interior"; } form.Focus(); } } <file_sep>/Asiento.cs using System; using Tao.OpenGl; using Tao.Glut; public class Asiento:Element { Point3D start; double largo; double ancho; double alto; float[] color; Ortoedro abaj; public Asiento(Point3D pst,double lar,double anc,double alt,float[] col) { this.start=pst; largo=lar; ancho=anc; alto=alt; color=col; abaj=new Ortoedro(new Point3D(pst.x,pst.y-alt/2+alt/3.0,pst.z+lar),anc,lar,alt/6.0,col); this.Recompile(); } public override void Recompile() { this.abaj.Recompile(); Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glDisable(Gl.GL_CULL_FACE); Glu.GLUquadric sph=Glu.gluNewQuadric(); Glu.gluQuadricOrientation(sph,Glu.GLU_OUTSIDE); Gl.glTranslated(start.x,start.y,start.z); Gl.glTranslated(-(Math.Sqrt(Math.Pow(this.alto,2)-Math.Pow(this.alto,2)/4)),0,0); Gl.glRotated(15,0,0,1); Gl.glColor3fv(color); Gl.glClipPlane(Gl.GL_CLIP_PLANE0,new double[]{1.0,0.0,0,-(Math.Sqrt(Math.Pow(this.alto,2)-Math.Pow(this.alto,2)/4))}); Gl.glEnable(Gl.GL_CLIP_PLANE0); Glu.gluQuadricNormals(sph,Glu.GLU_SMOOTH); Glu.gluCylinder(sph,this.alto,this.alto,this.largo,32,32); sph=Glu.gluNewQuadric(); Glu.gluQuadricNormals(sph,Glu.GLU_SMOOTH); Glu.gluDisk(sph,0,this.alto,32,32); sph=Glu.gluNewQuadric(); Glu.gluQuadricNormals(sph,Glu.GLU_SMOOTH); Gl.glTranslated(0,0,this.largo); Glu.gluDisk(sph,0,this.alto,32,32); Gl.glDisable(Gl.GL_CLIP_PLANE0); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glPopMatrix(); Gl.glEndList(); } public override Point3D PuntoRotacion { get { return start; } } public override void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); this.Rota(); abaj.Draw(); Gl.glCallList(idVisualizar); Gl.glPopMatrix(); } } } <file_sep>/Goma.cs using System; using Tao.OpenGl; using Materiales; public class Goma:Element { Point3D start; double rad; public Goma(Point3D pst,double radio) { start=pst; rad=radio; this.Recompile(); } public override void Recompile() { Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); CauchoNegro cn=new CauchoNegro(); Gl.glDisable(Gl.GL_CULL_FACE); Gl.glColor3d(cn.Ambient.r,cn.Ambient.g,cn.Ambient.b); cn.Set(); Gl.glTranslated(start.x,start.y,start.z); Glu.GLUquadric cil; cil=Glu.gluNewQuadric(); Glu.gluQuadricNormals(cil,Glu.GLU_SMOOTH); Glu.gluCylinder(cil,rad,rad,rad/2,32,32); cil=Glu.gluNewQuadric(); Glu.gluQuadricNormals(cil,Glu.GLU_SMOOTH); Glu.gluDisk(cil,0.55*rad,rad,32,32); Gl.glTranslated(0,0,rad/2); cil=Glu.gluNewQuadric(); Glu.gluQuadricNormals(cil,Glu.GLU_SMOOTH); Glu.gluDisk(cil,0.55*rad,rad,32,32); cn.UnSet(); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glPopMatrix(); Gl.glEndList(); } public override Point3D PuntoRotacion { get { return start; } } } <file_sep>/Pared.cs using System; using Tao.OpenGl; public class Pared:Element { double x,y,z; int text,mos; Point3D start; int ang; public Pared(Point3D pst,int angle,double larx) { start=pst; ang=angle; x=larx; y=15; z=2; text=5; mos=4; this.Recompile(); } public Pared(Point3D pst,int angle,double larx,double lary,double larz,int textur) { start=pst; ang=angle; x=larx; y=lary; z=larz; text=textur; mos=4; this.Recompile(); } public override void Recompile() { Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glDisable(Gl.GL_CULL_FACE); x=x/2; y=y/2; z=z/2; if(text != -1)Gl.glBindTexture(Gl.GL_TEXTURE_2D, Otros.texture[text]);//id textura segundo parametro Gl.glBegin(Gl.GL_QUAD_STRIP); // cuadrado Gl.glTexCoord2f(0, mos); Gl.glNormal3d( 0, 0,1); Gl.glVertex3d(-x, -y, z); Gl.glTexCoord2f(0, 0); Gl.glNormal3d( 0, 0,1); Gl.glVertex3d(-x, y, z); Gl.glTexCoord2f(mos, mos); Gl.glNormal3d( 0, 0,1); Gl.glVertex3d( x, -y, z); Gl.glTexCoord2f(mos, 0); Gl.glNormal3d( 0, 0, 1); Gl.glVertex3d( x, y, z); //lateral derecha Gl.glTexCoord2f(0, mos); Gl.glNormal3d( 0, 0,-1); Gl.glVertex3d(x, -y, -z); Gl.glTexCoord2f(0, 0); Gl.glNormal3d( 0, 0,-1); Gl.glVertex3d(x, y, -z); //lateral de atras Gl.glTexCoord2f(mos, mos); Gl.glNormal3d( 0, 0,-1); Gl.glVertex3d(-x, -y, -z); Gl.glTexCoord2f(mos, 0); Gl.glNormal3d( 0, 0,-1); Gl.glVertex3d(-x, y, -z); //lateral izquierda Gl.glTexCoord2f(0, mos); Gl.glNormal3d( -1, 0,0); Gl.glVertex3d(-x, -y, z); Gl.glTexCoord2f(0, 0); Gl.glNormal3d( -1, 0,0); Gl.glVertex3d(-x, y, z); Gl.glEnd(); Gl.glBegin(Gl.GL_QUADS); //horizontal superior Gl.glTexCoord2f(0, 0); Gl.glNormal3d( 0, 0, -1); Gl.glVertex3d(-x, y, z); Gl.glTexCoord2f(mos, 0); Gl.glNormal3d( 0, 0, -1); Gl.glVertex3d(x, y, z); Gl.glTexCoord2f(mos, mos); Gl.glNormal3d( 0, 0, -1); Gl.glVertex3d(x, y, -z); Gl.glTexCoord2f(0, mos); Gl.glNormal3d( 0, 0, -1); Gl.glVertex3d(-x, y, -z); Gl.glEnd(); Gl.glBegin(Gl.GL_QUADS); //horizontal inferior Gl.glTexCoord2f(0, 0); Gl.glNormal3d( 0, 0, -1); Gl.glVertex3d(-x, -y, z); Gl.glTexCoord2f(mos, 0); Gl.glNormal3d( 0, 0, -1); Gl.glVertex3d(x, -y, z); Gl.glTexCoord2f(mos, mos); Gl.glNormal3d( 0, 0, -1); Gl.glVertex3d(x, -y, -z); Gl.glTexCoord2f(0, mos); Gl.glNormal3d( 0, 0, -1); Gl.glVertex3d(-x, -y, -z); Gl.glEnd(); Gl.glBindTexture(Gl.GL_TEXTURE_2D, 0); Gl.glEnable(Gl.GL_CULL_FACE); x=x*2; y=y*2; z=z*2; Gl.glPopMatrix(); Gl.glEndList(); } public override Point3D PuntoRotacion { get { return start; } } public override void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); this.Rota(); Gl.glTranslated(start.x,start.y,start.z); Gl.glRotated(ang,0,1,0); Gl.glCallList(idVisualizar); Gl.glPopMatrix(); } } } <file_sep>/3dsLoader.cs using System; //using System.Collections; using System.Text; using System.IO; using Tao.OpenGl; using System.Collections; using Materiales; public struct vertex { public float x, y, z; } public struct vertex_type { public vertex point; public vertex normal; } // The polygon (trianGl.gle), 3 numbers that aim 3 vertices public struct polygon_type { public int a, b, c; public vertex normal; } // The mapcoord type, 2 texture coordinates for each vertex public struct mapcoord_type { public float u, v; } // The object type public class obj_type { public string name; public int vertices_qty; public int polygons_qty; public vertex_type[] vertex; public polygon_type[] polygon; public mapcoord_type[] mapcoord; public int id_texture = 0; public string mat_name = ""; public _3dsLoader loader; public void paint(bool _shadow, int[] rot, float[] trans, float[] scl) { Gl.glPushMatrix(); Gl.glTranslated(trans[0], trans[1], trans[2]); Gl.glRotated(rot[2], 0, 0, 1); Gl.glRotated(rot[1], 0, 1, 0); Gl.glRotated(rot[0], 1, 0, 0); Gl.glScaled(scl[0], scl[1], scl[2]); //Gl.glDisable(Gl.gl_COLOR_MATERIAL); color_typeF amb = (color_typeF)(loader.ambient[mat_name]); color_typeF dif = (color_typeF)(loader.diffuse[mat_name]); color_typeF spec = (color_typeF)(loader.specular[mat_name]); float shi = (float)(loader.shininess[mat_name]); float al=amb.a; if(al<1.0f){ Gl.glEnable(Gl.GL_BLEND); Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA); } Gl.glColor4f(amb.r, amb.g, amb.b, al); if (mapcoord != null) Gl.glEnable(Gl.GL_TEXTURE_2D); //Gl.gl.Gl.glBindTexture(Gl.gl.Gl.gl_TEXTURE_2D, Textures.idt[1]); //Gl.gl.Gl.glColor4f(1, 1, 1, alpha); Gl.glMaterialfv(Gl.GL_FRONT_AND_BACK, Gl.GL_AMBIENT, new float[] { amb.r, amb.g, amb.b }); Gl.glMaterialfv(Gl.GL_FRONT_AND_BACK, Gl.GL_DIFFUSE, new float[] { dif.r, dif.g, dif.b }); Gl.glMaterialfv(Gl.GL_FRONT_AND_BACK, Gl.GL_SPECULAR, new float[] { spec.r, spec.g, spec.b }); Gl.glMaterialf(Gl.GL_FRONT_AND_BACK, Gl.GL_SHININESS, shi); Gl.glBegin(Gl.GL_TRIANGLES); // Gl.glBegin and Gl.glEnd delimit the vertices that define a primitive (in our case trianGl.gles) for (int l_index = 0; l_index < polygons_qty; l_index++) { // Calculate normal vertor //----------------- FIRST VERTEX ----------------- // Texture coordinates of the first vertex if (mapcoord != null) Gl.glTexCoord2f(mapcoord[polygon[l_index].a].u, mapcoord[polygon[l_index].a].v); // Coordinates of the first vertex Gl.glNormal3d(vertex[polygon[l_index].a].normal.x*-1, vertex[polygon[l_index].a].normal.y * -1, vertex[polygon[l_index].a].normal.z * -1); //Normal definition Gl.glVertex3f(vertex[polygon[l_index].a].point.x, vertex[polygon[l_index].a].point.y, vertex[polygon[l_index].a].point.z); //Vertex definition //----------------- SECOND VERTEX ----------------- // Texture coordinates of the second vertex if (mapcoord != null) Gl.glTexCoord2f(mapcoord[polygon[l_index].b].u, mapcoord[polygon[l_index].b].v); // Coordinates of the second vertex Gl.glNormal3d(vertex[polygon[l_index].b].normal.x * -1, vertex[polygon[l_index].b].normal.y * -1, vertex[polygon[l_index].b].normal.z * -1); //Normal definition Gl.glVertex3f(vertex[polygon[l_index].b].point.x, vertex[polygon[l_index].b].point.y, vertex[polygon[l_index].b].point.z); //----------------- THIRD VERTEX ----------------- // Texture coordinates of the third vertex if (mapcoord != null) Gl.glTexCoord2f(mapcoord[polygon[l_index].c].u, mapcoord[polygon[l_index].c].v); // Coordinates of the Third vertex Gl.glNormal3d(vertex[polygon[l_index].c].normal.x * -1, vertex[polygon[l_index].c].normal.y * -1, vertex[polygon[l_index].c].normal.z * -1); //Normal definition Gl.glVertex3f(vertex[polygon[l_index].c].point.x, vertex[polygon[l_index].c].point.y, vertex[polygon[l_index].c].point.z); } Gl.glEnd(); if (mapcoord != null) Gl.glDisable(Gl.GL_TEXTURE_2D); if(al<1.0f) { Gl.glDisable(Gl.GL_BLEND); } //Gl.gl.Gl.glEnable(Gl.gl.Gl.gl_COLOR_MATERIAL); Gl.glPopMatrix(); } } class _3dsMath { public static vertex cross(vertex v1, vertex v2) { vertex v = new vertex(); v.x = v1.y * v2.z - v1.z * v2.y; v.y = v1.z * v2.x - v1.x * v2.z; v.z = v1.x * v2.y - v1.y * v2.x; return v; } public static vertex normalize(vertex v) { vertex nv = new vertex(); float l = (float)(Math.Sqrt(v.x * v.x + v.y * v.y + v.z * v.z)); if (l != 0.0) { nv.x = v.x / l; nv.y = v.y / l; nv.z = v.z / l; } else nv = v; return nv; } public static vertex sum(vertex v1, vertex v2) { vertex v = new vertex(); v.x = v1.x + v2.x; v.y = v1.y + v2.y; v.z = v1.z + v2.z; return v; } public static vertex dif(vertex v1, vertex v2) { vertex v = new vertex(); v.x = v1.x - v2.x; v.y = v1.y - v2.y; v.z = v1.z - v2.z; return v; } } public class _3dsLoader { /********************************************************** * * FUNCTION Load3DS (obj_type_ptr, char *) * * This function loads a mesh from a 3ds file. * Please note that we are loading only the vertices, polygons and mapping lists. * If you need to load meshes with advanced features as for example: * multi objects, materials, lights and so on, you must insert other chunk parsers. * *********************************************************/ public string ID; public string Name; public int[] Rot; public float[] Trans; public float[] Scl; public Hashtable objects = new Hashtable(); public Hashtable ambient = new Hashtable(); public Hashtable diffuse = new Hashtable(); public Hashtable specular = new Hashtable(); public Hashtable shininess = new Hashtable(); public Hashtable shininessST = new Hashtable(); public _3dsLoader(string id, string name, int[] rot, float[] trans, float[] scl) { ID = id; Name = name; Rot = rot; Trans = trans; Scl = scl; } private vertex normals(vertex v1, vertex v2, vertex v3) { vertex d1, d2, norm; d1 = _3dsMath.dif(v2, v1); d2 = _3dsMath.dif(v3, v1); norm = _3dsMath.cross(d1, d2); norm = _3dsMath.normalize(norm); return norm; } public void ComputeNormals() { foreach (DictionaryEntry di in objects) { obj_type o = (obj_type)(di.Value); for (int i = 0; i < o.polygons_qty; i++) o.polygon[i].normal = normals(o.vertex[o.polygon[i].c].point, o.vertex[o.polygon[i].b].point, o.vertex[o.polygon[i].a].point); for (int i = 0; i < o.vertices_qty; i++) { vertex temp = new vertex(); for (int j = 0; j < o.polygons_qty; j++) if (o.polygon[j].a == i || o.polygon[j].b == i || o.polygon[j].c == i) temp = _3dsMath.sum(temp, o.polygon[j].normal); //temp = o.polygon[j].normal; o.vertex[i].normal = _3dsMath.normalize(temp); } } } public int Load3DS(string p_filename) { int i; //Index variable objects = new Hashtable(); ambient = new Hashtable(); diffuse = new Hashtable(); specular = new Hashtable(); shininess = new Hashtable(); shininessST = new Hashtable(); obj_type p_object = null; BinaryReader l_file; //File pointer ushort l_chunk_id; //Chunk identifier uint l_chunk_lenght; //Chunk lenght char l_char; //Char variable ushort l_qty; //Number of elements in each chunk ushort l_face_flags; //Flag that stores some face information bool l_end = false; string l_mat_name = ""; color_typeF cl; float per; using (l_file = new BinaryReader(File.Open(p_filename, FileMode.Open, FileAccess.Read))) { while (!l_end) //Loop to scan the whole file { try { l_chunk_id = l_file.ReadUInt16(); l_chunk_lenght = l_file.ReadUInt32(); switch (l_chunk_id) { //----------------- MAIN3DS ----------------- // Description: Main chunk, contains all the other chunks // Chunk ID: 4d4d // Chunk Lenght: 0 + sub chunks //------------------------------------------- case 0x4d4d: break; //----------------- EDIT3DS ----------------- // Description: 3D Editor chunk, objects layout info // Chunk ID: 3d3d (hex) // Chunk Lenght: 0 + sub chunks //------------------------------------------- case 0x3d3d: break; //--------------- EDIT_OBJECT --------------- // Description: Object block, info for each object // Chunk ID: 4000 (hex) // Chunk Lenght: len(object name) + sub chunks //------------------------------------------- case 0x4000: p_object = new obj_type(); p_object.name = ""; p_object.loader = this; do { l_char = l_file.ReadChar(); if (l_char > 0) p_object.name = p_object.name + l_char; } while (l_char != 0); objects.Add(p_object.name, p_object); break; //--------------- OBJ_TRIMESH --------------- // Description: Triangular mesh, contains chunks for 3d mesh info // Chunk ID: 4100 (hex) // Chunk Lenght: 0 + sub chunks //------------------------------------------- case 0x4100: break; //--------------- TRI_VERTEXL --------------- // Description: Vertices list // Chunk ID: 4110 (hex) // Chunk Lenght: 1 x unsigned short (number of vertices) // + 3 x float (vertex coordinates) x (number of vertices) // + sub chunks //------------------------------------------- case 0x4110: l_qty = l_file.ReadUInt16(); p_object.vertices_qty = l_qty; p_object.vertex = new vertex_type[l_qty]; for (i = 0; i < l_qty; i++) { p_object.vertex[i].point.x = l_file.ReadSingle(); p_object.vertex[i].point.y = l_file.ReadSingle(); p_object.vertex[i].point.z = l_file.ReadSingle(); } break; //--------------- TRI_FACEL1 ---------------- // Description: Polygons (faces) list // Chunk ID: 4120 (hex) // Chunk Lenght: 1 x unsigned short (number of polygons) // + 3 x unsigned short (polygon points) x (number of polygons) // + sub chunks //------------------------------------------- case 0x4120: l_qty = l_file.ReadUInt16(); p_object.polygons_qty = l_qty; p_object.polygon = new polygon_type[l_qty]; for (i = 0; i < l_qty; i++) { p_object.polygon[i].a = l_file.ReadUInt16(); p_object.polygon[i].b = l_file.ReadUInt16(); p_object.polygon[i].c = l_file.ReadUInt16(); l_face_flags = l_file.ReadUInt16(); } break; //------------------- MATERIAL ID ----------------- // Description: Material name asigned to the object // Chunk ID: 4130 (hex) // Chunk Length: len(mat_name) // + 2 x unsigned short //------------------------------------------------- case 0x4130: p_object.mat_name = ""; do { l_char = l_file.ReadChar(); if (l_char > 0) p_object.mat_name = p_object.mat_name + l_char; } while (l_char != 0); int entr = l_file.ReadUInt16(); int face; for (i = 0; i < entr; i++) face = l_file.ReadUInt16(); break; //------------- TRI_MAPPINGCOORS ------------ // Description: Vertices list // Chunk ID: 4140 (hex) // Chunk Lenght: 1 x unsigned short (number of mapping points) // + 2 x float (mapping coordinates) x (number of mapping points) // + sub chunks //------------------------------------------- case 0x4140: l_qty = l_file.ReadUInt16(); p_object.mapcoord = new mapcoord_type[l_qty]; for (i = 0; i < l_qty; i++) { p_object.mapcoord[i].u = l_file.ReadSingle(); p_object.mapcoord[i].v = l_file.ReadSingle(); } break; case 0xAFFF: break; case 0xA000: l_mat_name = ""; do { l_char = l_file.ReadChar(); if (l_char > 0) l_mat_name = l_mat_name + l_char; } while (l_char != 0); break; case 0xA010: l_chunk_id = l_file.ReadUInt16(); l_chunk_lenght = l_file.ReadUInt32(); cl = new color_typeF(); cl.r = (l_file.ReadByte())/255.0f; cl.g = (l_file.ReadByte())/255.0f; cl.b = (l_file.ReadByte())/255.0f; cl.a=1.0f; ambient.Add(l_mat_name, cl); break; case 0xA020: l_chunk_id = l_file.ReadUInt16(); l_chunk_lenght = l_file.ReadUInt32(); cl = new color_typeF(); cl.r = (l_file.ReadByte())/255.0f; cl.g = (l_file.ReadByte())/255.0f; cl.b = (l_file.ReadByte())/255.0f; cl.a=1.0f; diffuse.Add(l_mat_name, cl); break; case 0xA030: l_chunk_id = l_file.ReadUInt16(); l_chunk_lenght = l_file.ReadUInt32(); cl = new color_typeF(); cl.r = (l_file.ReadByte())/255.0f; cl.g = (l_file.ReadByte())/255.0f; cl.b = (l_file.ReadByte())/255.0f; cl.a=1.0f; specular.Add(l_mat_name, cl); break; case 0xA040: l_chunk_id = l_file.ReadUInt16(); l_chunk_lenght = l_file.ReadUInt32(); per = (l_file.ReadUInt16())/255.0f; shininess.Add(l_mat_name, (float)per); break; case 0xA041: l_chunk_id = l_file.ReadUInt16(); l_chunk_lenght = l_file.ReadUInt32(); per = (l_file.ReadUInt16())/255.0f; shininessST.Add(l_mat_name,(float) per); break; //----------- Skip unknow chunks ------------ //We need to skip all the chunks that currently we don't use //We use the chunk lenght information to set the file pointer //to the same level next chunk //------------------------------------------- default: l_file.BaseStream.Seek(l_chunk_lenght - 6, SeekOrigin.Current); break; } } catch (EndOfStreamException e) { l_end = true; } } } return (1); // Returns ok } public void paint(bool shadow,I3dsTaken c) { obj_type aux=null; foreach (obj_type o in objects.Values) { if(o.name=="glass") { aux=o; } else if(c.Actions(o,shadow, Rot, Trans, Scl)) { } else o.paint(shadow, Rot, Trans, Scl); } if(aux!=null) { if(c.Actions(aux,shadow, Rot, Trans, Scl)) { } else aux.paint(shadow, Rot, Trans, Scl); } } } <file_sep>/LimpParab.cs using System; using Tao.OpenGl; public class LimpParab:Element { Point3D start; Ortoedro[] p; double largo; public LimpParab(Point3D pst,double lar) { start=pst; p=new Ortoedro[4]; largo=lar; p[0]=new Ortoedro(pst,lar,lar/20.0,lar/20.0,new float[]{0.9f,0.6f,0.6f}); p[1]=new Ortoedro(new Point3D(pst.x+lar,pst.y,pst.z),lar/6.0,lar/30.0,lar/30.0,new float[]{0.9f,0.6f,0.6f}); p[2]=new Ortoedro(new Point3D(pst.x+lar,pst.y,pst.z),lar/6.0,lar/30.0,lar/30.0,new float[]{0.9f,0.6f,0.6f}); p[3]=new Ortoedro(new Point3D(pst.x+8*lar/10.0,pst.y,pst.z-Math.Sqrt(lar/60)),lar,lar/20.0,lar/20.0,new float[]{0.6f,0.6f,0.6f}); this.Recompile(); } public override void Recompile() { foreach(Ortoedro o in p) o.Recompile(); Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glPopMatrix(); Gl.glEndList(); } public override Point3D PuntoRotacion { get { return start; } } public override void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); this.Rota(); p[0].Draw(); p[1].Rota(45,0,1,0); p[1].Draw(); p[1].Rota(-45,0,1,0); Gl.glTranslated(-0.1,0,-largo/30); p[2].Rota(135,0,1,0); p[2].Draw(); p[2].Rota(-135,0,1,0); Gl.glTranslated(-0.1,0,largo/30); p[3].Draw(); Gl.glCallList(idVisualizar); Gl.glPopMatrix(); } } } <file_sep>/Element.cs using System; using Tao.OpenGl; public abstract class Element:IElement { public int idVisualizar; protected float width; protected double rx; // angulo de rotacion sobre el eje x protected double ry; // angulo de rotacion sobre el eje y protected double rz; // angulo de rotacion sobre el eje z public Element(float width) { this.width = width; idVisualizar = Gl.glGenLists(1); } public virtual int Id { get{return idVisualizar;} } public virtual string GetObjName(int id) { int i=idVisualizar; return ""; } public Element() : this(1.0f){} public virtual void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); this.Rota(); Gl.glCallList(idVisualizar); Gl.glPopMatrix(); } } public virtual void Rota() { Gl.glTranslated(this.PuntoRotacion.x, this.PuntoRotacion.y, this.PuntoRotacion.z); Gl.glRotated(rx, 1, 0, 0); Gl.glRotated(ry, 0, 1, 0); Gl.glRotated(rz, 0, 0, 1); Gl.glTranslated(-this.PuntoRotacion.x, -this.PuntoRotacion.y, -this.PuntoRotacion.z); } public virtual void Rota(double angle,int x,int y,int z) { Gl.glTranslated(this.PuntoRotacion.x, this.PuntoRotacion.y, this.PuntoRotacion.z); Gl.glRotated(angle, x, y, z); Gl.glTranslated(-this.PuntoRotacion.x, -this.PuntoRotacion.y, -this.PuntoRotacion.z); } public void RotateX(int direction) { rx += Math.Sign(direction)*5; } public void RotateY(int direction) { ry += Math.Sign(direction)*5; } public void RotateZ(int direction) { rz += Math.Sign(direction)*5; } public float Width { get { return width; } set { width = value; Recompile(); } } public abstract void Recompile(); public abstract Point3D PuntoRotacion{ get; } public virtual void Destroy() { Gl.glDeleteLists(idVisualizar, 1); } } public struct Point3D { public double x, y, z; public Point3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public double[] Coords { get{ return new double[]{x, y, z}; } } } <file_sep>/mb380.cs using System; using Materiales; using Tao.OpenGl; public class mb380:Carro { public mb380():base("mb_380sl.3DS",new InteriorMB(new Point3D(0,0,-20))) { } public override void InitMyMaterial() { ChangeMaterialFrom3ds("flred rlights",new MiPlasticoRojo()); ChangeMaterialFrom3ds("florange signal",new MiCrisLater()); ChangeMaterialFrom3ds("glass_fari",new Plata()); ChangeMaterialFrom3ds("Metal_Chrome",new Plata()); ChangeMaterialFrom3ds("tyre",new CauchoNegro()); ChangeMaterialFrom3ds("glass",new MiCristalCalobar()); ChangeMaterialFrom3ds("black under",new PlasticoNegro()); ChangeMaterialFrom3ds("body",new MiMetal(0.5f,1.0f,0f)); } public override bool Actions(obj_type o,bool _shadow, int[] rot, float[] trans, float[] scl) { if(actList.Contains("maletero") && o.name=="trunk") { Gl.glPushMatrix(); Gl.glTranslated((trans[0]-0.4),trans[1]-1.5,trans[2]); Gl.glRotated(-45,0,0,1); Gl.glTranslated(-(trans[0]+0.4),- (trans[1]+1.5),-trans[2]); o.paint(_shadow, rot, trans, scl); Gl.glPopMatrix(); return true; } else if(actList.Contains("capo") && o.name=="hood") { Gl.glPushMatrix(); Gl.glTranslated((trans[0]+0.2),trans[1]-1.2,trans[2]); Gl.glRotated(45,0,0,1); Gl.glTranslated(-(trans[0]-0.2),- (trans[1]+1.2),-trans[2]); o.paint(_shadow, rot, trans, scl); Gl.glPopMatrix(); return true; } else if(actList.Contains("descapotable") && o.name=="glass") { Gl.glPushMatrix(); Gl.glClipPlane(Gl.GL_CLIP_PLANE0,new double[]{1,1,0,-2}); Gl.glEnable(Gl.GL_CLIP_PLANE0); o.paint(_shadow, rot, trans, scl); Gl.glDisable(Gl.GL_CLIP_PLANE0); Gl.glPopMatrix(); return true; } else if(actList.Contains("descapotable") && o.name=="trim") { Gl.glPushMatrix(); Gl.glClipPlane(Gl.GL_CLIP_PLANE1,new double[]{0,-1,0,0.5}); Gl.glEnable(Gl.GL_CLIP_PLANE1); o.paint(_shadow, rot, trans, scl); Gl.glDisable(Gl.GL_CLIP_PLANE1); Gl.glPopMatrix(); return true; } else if(actList.Contains("descapotable") && o.name=="roof") { Gl.glPushMatrix(); Gl.glClipPlane(Gl.GL_CLIP_PLANE0,new double[]{1,0,0,3.5}); Gl.glClipPlane(Gl.GL_CLIP_PLANE1,new double[]{-1,0,0,-2.0}); Gl.glEnable(Gl.GL_CLIP_PLANE0); Gl.glEnable(Gl.GL_CLIP_PLANE1); Gl.glTranslated(-1.0,-0.7,0); o.paint(_shadow, rot, trans, scl); Gl.glDisable(Gl.GL_CLIP_PLANE1); Gl.glDisable(Gl.GL_CLIP_PLANE0); Gl.glPopMatrix(); return true; } return false; } public override float OscuridadCristal { get { return ((color_typeF)car.ambient["glass"]).r*255; } set { color_typeF c; if(value<256 && value>=0) { c=(color_typeF)car.ambient["glass"]; c.r=(float)(value/255.0); c.g=(float)(value/255.0); c.b=(float)(value/255.0); car.ambient["glass"]=c; } } } public override void EnciendeTubEsc(bool on) { if(on) this.tubodeescape=new Particula(new Point3D(-6,-1.7,-18.5)); else this.tubodeescape=null; } public override Point3D ObjetivoVistaInt(int angle) { return new Point3D(3*Math.Cos(Math.PI*angle/180.0)-center.x,center.y,center.z-(3*Math.Sin(Math.PI*angle/180.0))); } public override Point3D OrigenVistaInt() { return new Point3D(center.x-1.0,center.y+2.7,center.z); } } <file_sep>/Carro.cs using System; using Tao.OpenGl; using System.Windows.Forms; using System.Xml; using Materiales; using System.Collections; /// <summary> /// Summary description for Carro. /// </summary> public abstract class Carro:Element,I3dsTaken { public _3dsLoader car; protected Point3D center; protected Interior inter; public ArrayList actList; protected color_typeF[] colores; public Particula tubodeescape; public bool todo=true; public Carro(string path,Interior interior) { car=load3ds(path); car.ComputeNormals(); colores=new color_typeF[]{new color_typeF(0.5f,1.0f,0f),new color_typeF(1f,1f,0.4f),new color_typeF(1f,0.5f,1f),new color_typeF(0.5f,0.5f,1f),new color_typeF(0.7f,0f,0f)}; InitMyMaterial(); inter=interior; actList=new ArrayList(); // this.actList.Add("capo"); // this.actList.Add("maletero"); this.Recompile(); } public virtual color_typeF[] Colores { get{return colores;} } public abstract void EnciendeTubEsc(bool on); public abstract bool Actions(obj_type o,bool _shadow, int[] rot, float[] trans, float[] scl); public abstract float OscuridadCristal { get; set; } public virtual void EnciendeParabrisas(bool on) { this.inter.onlp=on; } public override void Recompile() { inter.Recompile(); Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glDisable(Gl.GL_CULL_FACE); car.paint(false,this); // // Glu.GLUquadric sph=Glu.gluNewQuadric(); // Glu.gluQuadricOrientation(sph,Glu.GLU_OUTSIDE); // Gl.glTranslated(0,0,-20); // Glu.gluSphere(sph,3,32,32); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glPopMatrix(); Gl.glEndList(); } public abstract void InitMyMaterial(); public abstract Point3D ObjetivoVistaInt(int angle); public abstract Point3D OrigenVistaInt(); public override void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); this.Rota(); inter.Draw(); if(todo) Gl.glCallList(idVisualizar); if(this.tubodeescape!=null) this.tubodeescape.Draw(); Gl.glPopMatrix(); } } public override Point3D PuntoRotacion { get { return center; } } public virtual void ChangeMaterialFrom3ds(string mat3dsname,Material nuevo) { this.car.ambient[mat3dsname]=nuevo.Ambient; this.car.diffuse[mat3dsname]=nuevo.Diffuse; this.car.specular[mat3dsname]=nuevo.Specular; this.car.shininess[mat3dsname]=nuevo.Shininess; } private _3dsLoader load3ds(string path) { XmlTextReader doc = new XmlTextReader(Application.StartupPath + "\\" + "Models\\" + "models.xml"); string id = ""; _3dsLoader temp = null; string name = ""; int[] rot = null; float[] trans = null; float[] scl = null; bool notdone=true; while (doc.Read() && notdone) { switch (doc.NodeType) { case XmlNodeType.Element: switch (doc.Name) { case "model": if(doc.GetAttribute("id")!=path) doc.Skip(); else id = doc.GetAttribute("id"); break; case "name": name = (string)(doc.GetAttribute("id")); break; case "rot": rot = new int[3]; rot[0] = Int32.Parse(doc.GetAttribute("x")); rot[1] = Int32.Parse(doc.GetAttribute("y")); rot[2] = Int32.Parse(doc.GetAttribute("z")); break; case "trans": trans = new float[3]; trans[0] = Single.Parse(doc.GetAttribute("x")); trans[1] = Single.Parse(doc.GetAttribute("y")); trans[2] = Single.Parse(doc.GetAttribute("z")); break; case "scl": scl = new float[3]; scl[0] = Single.Parse(doc.GetAttribute("x")); scl[1] = Single.Parse(doc.GetAttribute("y")); scl[2] = Single.Parse(doc.GetAttribute("z")); break; } break; case XmlNodeType.EndElement: switch (doc.Name) { case "model": temp = new _3dsLoader(id, name, rot, trans, scl); center=new Point3D(trans[0],trans[1],trans[2]); temp.Load3DS(Application.StartupPath + "\\" + "Models\\" + temp.ID); notdone=false; return temp; } break; } } return null; } } <file_sep>/Buro.cs using System; using Tao.OpenGl; public class Buro:Element { Point3D start; Pared[] partes; public Buro(Point3D pst,double largo,double ancho,int text) { start=pst; partes=new Pared[4]; partes[0]=new Pared(start,0,largo,0.4,ancho,text); partes[1]=new Pared(new Point3D(start.x-largo/2.0+largo/8.0,start.y-0.15-largo/6.0,start.z+ancho/2.0-ancho/6.0),0,0.25,largo/3.0,0.25,text); partes[2]=new Pared(new Point3D(start.x-largo/2.0+largo/8.0,start.y-0.15-largo/6.0,start.z+ancho/2.0-5*ancho/6.0),0,0.25,largo/3.0,0.25,text); partes[3]=new Pared(new Point3D(start.x+largo/2.0-largo/6.0,start.y-0.15-largo/6.0,start.z),0,largo/3,largo/3.0,ancho,text); } public override void Recompile() { foreach(Pared p in partes) p.Recompile(); } public override Point3D PuntoRotacion { get { return start; } } public override void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); this.Rota(); foreach(Pared p in partes) p.Draw(); Gl.glPopMatrix(); } } } <file_sep>/Col.cs using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Materiales; public class Col : System.Windows.Forms.Form { private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.Button button1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; color_typeF[] colores; public int selInd; public Col(color_typeF[] c) { // // Required for Windows Form Designer support // colores=c; selInd=0; InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.Location = new System.Drawing.Point(16, 16); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(24, 200); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click); this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint); this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown); // // pictureBox2 // this.pictureBox2.Location = new System.Drawing.Point(72, 120); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(128, 88); this.pictureBox2.TabIndex = 1; this.pictureBox2.TabStop = false; this.pictureBox2.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox2_Paint); // // button1 // this.button1.Font = new System.Drawing.Font("Plump MT", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button1.ForeColor = System.Drawing.Color.Aqua; this.button1.Location = new System.Drawing.Point(64, 32); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(136, 40); this.button1.TabIndex = 2; this.button1.Text = "Aceptar"; this.button1.Click += new System.EventHandler(this.button1_Click); // // Col // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.Color.Maroon; this.ClientSize = new System.Drawing.Size(224, 224); this.Controls.Add(this.button1); this.Controls.Add(this.pictureBox2); this.Controls.Add(this.pictureBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Location = new System.Drawing.Point(10, 506); this.Name = "Col"; this.Opacity = 0.5; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Col"; this.ResumeLayout(false); } #endregion private void pictureBox1_Click(object sender, System.EventArgs e) { } private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g=e.Graphics; for(int i=0;i<colores.Length;i++) { SolidBrush b=new SolidBrush(Color.FromArgb((int)colores[i].r*255,(int)colores[i].g*255,(int)colores[i].b*255)); g.FillRectangle(b,0,i*40,this.Width,40); } } private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { selInd=e.Y/40; pictureBox2.Refresh(); } private void pictureBox2_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g=e.Graphics; SolidBrush b=new SolidBrush(Color.FromArgb((int)colores[selInd].r*255,(int)colores[selInd].g*255,(int)colores[selInd].b*255)); g.FillRectangle(b,0,0,this.Width,this.Height); } private void button1_Click(object sender, System.EventArgs e) { this.Visible=false; } } <file_sep>/I3dsTaken.cs using System; public interface I3dsTaken { bool Actions(obj_type o,bool _shadow, int[] rot, float[] trans, float[] scl); } <file_sep>/Lugar.cs using System; using Tao.OpenGl; public class Lugar:Element { Pared[] par; public Base111 bas; Cuadro[] cuad; Buro bur; Silla sil; Mata m; Sofa sof; public Lugar() { par=new Pared[7]; par[0]=new Pared(new Point3D(0,7.5,-40),0,40); par[1]=new Pared(new Point3D(-20,7.5,-20),90,40); par[2]=new Pared(new Point3D(20,7.5,-20),90,40); par[3]=new Pared(new Point3D(0,15,-20),0,50,1,42,7); par[4]=new Pared(new Point3D(0,0,-20),0,42,1,42,6); par[5]=new Pared(new Point3D(-14.5,3.5,0),0,2.5,0.3,1,8); par[6]=new Pared(new Point3D(-11.5,3.5,0),0,2.5,0.3,1,8); cuad=new Cuadro[3]; cuad[0]=new Cuadro(new Point3D(-18.5,7,-25),5,3,90,10,7); cuad[1]=new Cuadro(new Point3D(-10,7,-38.5),7,4,0,11,8); cuad[2]=new Cuadro(new Point3D(10,7,-38.5),7,3,0,12,7); bur=new Buro(new Point3D(-13,3,-22),6,3.5,8); sil=new Silla(new Point3D(-16,4,-21),2,2,2,new float[]{0.3f,0.2f,0f},new float[]{0.4f,0f,0f}); m=new Mata(); sof=new Sofa(); bas=new Base111(new Point3D(0,-1.3,-20),7,new float[]{1.0f,0.4f,0.2f,1.0f}); this.Recompile(); } public override void Recompile() { foreach(Pared p in par) p.Recompile(); foreach(Cuadro c in cuad) c.Recompile(); sof.Recompile(); sil.Recompile(); bur.Recompile(); bas.Recompile(); m.Recompile(); Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glDisable(Gl.GL_CULL_FACE); Gl.glColor4d(0.6,0.6,0.9,0.85); Gl.glEnable(Gl.GL_BLEND); Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA); Gl.glBegin(Gl.GL_POLYGON); Gl.glVertex3d(-20,15,0); Gl.glVertex3d(20,15,0); Gl.glVertex3d(20,9,0); Gl.glVertex3d(-20,9,0); Gl.glEnd(); Gl.glBindTexture(Gl.GL_TEXTURE_2D,Otros.texture[14]); Gl.glTexEnvf(Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_MODE, Gl.GL_BLEND); Gl.glTexEnvfv(Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_COLOR, new float[]{0.6f,0.6f,0.9f,0.85f}); Gl.glBegin(Gl.GL_POLYGON); Gl.glTexCoord2d(0,0);Gl.glVertex3d(-20,9,0); Gl.glTexCoord2d(8,0);Gl.glVertex3d(20,9,0); Gl.glTexCoord2d(8,1);Gl.glVertex3d(20,7,0); Gl.glTexCoord2d(0,1);Gl.glVertex3d(-20,7,0); Gl.glEnd(); Gl.glTexEnvf(Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_MODE, Gl.GL_DECAL); Gl.glBindTexture(Gl.GL_TEXTURE_2D,0); Gl.glBegin(Gl.GL_POLYGON); Gl.glVertex3d(-20,7,0); Gl.glVertex3d(-16,7,0); Gl.glVertex3d(-16,0,0); Gl.glVertex3d(-20,0,0); Gl.glEnd(); Gl.glBegin(Gl.GL_POLYGON); Gl.glVertex3d(-10,7,0); Gl.glVertex3d(20,7,0); Gl.glVertex3d(20,0,0); Gl.glVertex3d(-10,0,0); Gl.glEnd(); #region Puertas Gl.glBegin(Gl.GL_POLYGON); Gl.glVertex3d(-15.95,6.95,0); Gl.glVertex3d(-13.05,6.95,0); Gl.glVertex3d(-13.05,0,0); Gl.glVertex3d(-15.95,0,0); Gl.glEnd(); Gl.glBegin(Gl.GL_POLYGON); Gl.glVertex3d(-12.95,6.95,0); Gl.glVertex3d(-10.05,6.95,0); Gl.glVertex3d(-10.05,0,0); Gl.glVertex3d(-12.95,0,0); Gl.glEnd(); #endregion Puertas Gl.glEnable(Gl.GL_CULL_FACE); Gl.glPopMatrix(); Gl.glEndList(); } public override void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); this.Rota(); Gl.glTranslated(-8,-3.9,4); foreach(Cuadro c in cuad) c.Draw(); sil.Draw(); bur.Rota(90,0,1,0); bur.Draw(); bur.Rota(-90,0,1,0); foreach(Pared p in par) p.Draw(); Gl.glTranslated(8,3.9,-4); bas.Draw(); Gl.glTranslated(-8,-3.9,4); //m.Draw(); //sof.Draw(); Gl.glCallList(idVisualizar); Gl.glPopMatrix(); } } public override Point3D PuntoRotacion { get { return new Point3D(0,7.5,-20); } } } <file_sep>/Silla.cs using System; using Tao.OpenGl; public class Silla:Element { Ortoedro[] patas; Ortoedro asient; Ortoedro[] madesp; public Silla(Point3D pcom,double larmesp,double lasi,double lpat,float[] colmad,float[] coltap) { patas=new Ortoedro[4]; double apat=lpat/30.0; for(int i=0;i<patas.Length;i++) { patas[i]=new Ortoedro(new Point3D(pcom.x+(lasi/8.0)+((int)(i/2))*lasi*6/8,pcom.y-larmesp,pcom.z-((int)(i%2))*lasi*6/8.0-lasi/8.0),2*apat,apat,lpat,colmad); } madesp=new Ortoedro[2]; double anchmesp=larmesp/25.0; for(int i=0;i<madesp.Length;i++) { madesp[i]=new Ortoedro(new Point3D(pcom.x,pcom.y,pcom.z-((i%2)*(lasi-anchmesp))),3*anchmesp,anchmesp,larmesp,colmad); } double aasi=lasi/12.0; asient=new Ortoedro(new Point3D(pcom.x,pcom.y-larmesp+aasi,pcom.z),lasi,lasi,aasi,coltap); this.Recompile(); } public override void Recompile() { asient.Recompile(); foreach(Ortoedro o in patas) o.Recompile(); foreach(Ortoedro o in madesp) o.Recompile(); Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glDisable(Gl.GL_CULL_FACE); Glu.GLUquadric sph=Glu.gluNewQuadric(); Glu.gluQuadricOrientation(sph,Glu.GLU_OUTSIDE); Gl.glTranslated(madesp[0].Inicio.x,madesp[0].Inicio.y-madesp[0].Alto/5.0,madesp[0].Inicio.z-asient.Largo+madesp[0].Largo); Gl.glColor3fv(asient.Color); Gl.glClipPlane(Gl.GL_CLIP_PLANE0,new double[]{1.0,0.0,0,0.0}); Gl.glEnable(Gl.GL_CLIP_PLANE0); Glu.gluCylinder(sph,madesp[0].Alto/5,madesp[0].Alto/5,asient.Ancho-2*madesp[0].Largo,32,32); sph=Glu.gluNewQuadric(); Glu.gluDisk(sph,0,madesp[0].Alto/5,32,32); sph=Glu.gluNewQuadric(); Gl.glTranslated(0,0,asient.Largo-2*madesp[0].Largo); Glu.gluDisk(sph,0,madesp[0].Alto/5,32,32); Gl.glPopMatrix(); Gl.glBegin(Gl.GL_POLYGON); Gl.glTexCoord2d(0,0);Gl.glVertex3d(madesp[0].Inicio.x+0.05,madesp[0].Inicio.y,madesp[0].Inicio.z-madesp[0].Largo); Gl.glTexCoord2d(1,0);Gl.glVertex3d(madesp[0].Inicio.x+0.05,madesp[0].Inicio.y-2*madesp[0].Alto/5,madesp[0].Inicio.z-madesp[0].Largo); Gl.glTexCoord2d(1,1);Gl.glVertex3d(madesp[0].Inicio.x+0.05,madesp[0].Inicio.y-2*madesp[0].Alto/5,madesp[0].Inicio.z-asient.Largo+madesp[0].Largo); Gl.glTexCoord2d(0,1);Gl.glVertex3d(madesp[0].Inicio.x+0.05,madesp[0].Inicio.y,madesp[0].Inicio.z-asient.Largo+madesp[0].Largo); Gl.glEnd(); Gl.glDisable(Gl.GL_CLIP_PLANE0); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glEndList(); } public override void Draw() { Gl.glPushMatrix(); this.Rota(); asient.Draw(); foreach(Ortoedro o in patas) o.Draw(); foreach(Ortoedro o in madesp) o.Draw(); Gl.glCallList(idVisualizar); Gl.glPopMatrix(); } public override Point3D PuntoRotacion { get { return asient.PuntoRotacion; } } } <file_sep>/Timon.cs using System; using Tao.OpenGl; using Tao.Glut; public class Timon:Element { Point3D start; double radio; float[] color; public Timon(Point3D pst,double radius,float[] col) { start=pst; radio=radius; color=col; this.Recompile(); } public override void Recompile() { Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glColor3fv(color); Gl.glTranslated(start.x,start.y,start.z); Glut.glutSolidTorus(radio/8.0,radio,32,32); Glu.GLUquadric sph; sph=Glu.gluNewQuadric(); Glu.gluSphere(sph,radio/6.0,32,32); for(int i=0;i<3;i++) { Gl.glPushMatrix(); Gl.glRotated(120*i,0,0,1); Gl.glRotated(-90,1,0,0); sph=Glu.gluNewQuadric(); Glu.gluCylinder(sph,radio/8.0,radio/8.0,radio,32,32); Gl.glPopMatrix(); } Gl.glPopMatrix(); Gl.glEndList(); } public override Point3D PuntoRotacion { get { return start; } } } <file_sep>/Scene.cs using System; using Tao.OpenGl; using System.Windows.Forms; using Tao.Glut; /// <summary> /// Summary description for Scene. /// </summary> public class Scene { #region fields public IElement element; private float[] color; public double[] activeRotateVector; private bool bomon,ambon; public string nombre; public Camara cam; public double cz,cx,cy,incx,incy,incz; public bool first; #endregion public Scene() { color = new float[] { 1.0f, 0.0f, 0.0f }; activeRotateVector = new double[3]{1, 0, 0}; bomon=true; ambon=true; cam=new Camara(); cz=0; cy=2; cx=0; incz=-2; incy=0; incx=0; first=true; // Glut.glutIdleFunc(new Glut.IdleCallback(Draw)); Gl.glEnable(Gl.GL_LIGHTING); Gl.glEnable(Gl.GL_COLOR_MATERIAL); SituaBomb(); SituaLuzAmb(); } #region methods public void ProcessInput(int key) { switch(key) { case (int)Keys.I: // increment Rotate(1); break; case (int)Keys.D: // decrement Rotate(-1); break; case (int)Keys.X: activeRotateVector = new double[3]{1, 0, 0}; // if(rotateVectorChanged != null) // rotateVectorChanged(this, null); break; case (int)Keys.Y: activeRotateVector = new double[3]{0, 1, 0}; // if(rotateVectorChanged != null) // rotateVectorChanged(this, null); break; case (int)Keys.Z: activeRotateVector = new double[3]{0, 0, 1}; // if(rotateVectorChanged != null) // rotateVectorChanged(this, null); break; case (int)Keys.M: cz-=2; cam.SetPos(new Point3D(cx,cy,cz),new Point3D(cx+incx,cy+incy,cz+incz),0,1,0); // this.EncenderBomb(false); // this.SituaBomb(); // this.EncenderBomb(true); break; case (int)Keys.V: cx-=2; cam.SetPos(new Point3D(cx,cy,cz),new Point3D(cx+incx,cy+incy,cz+incz),0,1,0); // this.EncenderBomb(false); // this.SituaBomb(); // this.EncenderBomb(true); break; case (int)Keys.B: cx+=2; cam.SetPos(new Point3D(cx,cy,cz),new Point3D(cx+incx,cy+incy,cz+incz),0,1,0); // this.EncenderBomb(false); // this.SituaBomb(); // this.EncenderBomb(true); break; case (int)Keys.K: cy-=2; cam.SetPos(new Point3D(cx,cy,cz),new Point3D(cx+incx,cy+incy,cz+incz),0,1,0); // this.EncenderBomb(false); // this.SituaBomb(); // this.EncenderBomb(true); break; case (int)Keys.J: cy+=2; cam.SetPos(new Point3D(cx,cy,cz),new Point3D(cx+incx,cy+incy,cz+incz),0,1,0); // this.EncenderBomb(false); // this.SituaBomb(); // this.EncenderBomb(true); break; case (int)Keys.N: cz+=2; cam.SetPos(new Point3D(cx,cy,cz),new Point3D(cx+incx,cy+incy,cz+incz),0,1,0); // this.EncenderBomb(false); // this.SituaBomb(); // this.EncenderBomb(true); break; } } private void Rotate(int direction) { if(activeRotateVector[0] == 1 && activeRotateVector[1] == 0 && activeRotateVector[2] == 0) element.RotateX(direction); else if(activeRotateVector[0] == 0 && activeRotateVector[1] == 1 && activeRotateVector[2] == 0) element.RotateY(direction); else if(activeRotateVector[0] == 0 && activeRotateVector[1] == 0 && activeRotateVector[2] == 1) element.RotateZ(direction); } public Point3D OrigCam { get{return new Point3D(cx,cy,cz);} set{cx=value.x; cy=value.y; cz=value.z; } } public Point3D ObjCam { get{return new Point3D(incx,incy,incz);} set { incx=value.x; incy=value.y; incz=value.z; } } public void Draw() { Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT| Gl.GL_STENCIL_BUFFER_BIT); Gl.glColor3fv(color); if(first) { Gl.glEnable(Gl.GL_LIGHTING); Gl.glEnable(Gl.GL_COLOR_MATERIAL); SituaBomb(); SituaLuzAmb(); SituaLuzNum2(); first=false; } EncenderBomb(this.BombiOn); EncenderLuzAmb(this.ambon); EncenderLuzNum2(true); cam.SetPos(new Point3D(cx,cy,cz),new Point3D(cx+incx,cy+incy,cz+incz),0,1,0); if(element!=null) element.Draw(); Gl.glFlush(); } #region Luces public void SituaLuzAmb() { Gl.glLightfv(Gl.GL_LIGHT1,Gl.GL_AMBIENT,new float[]{0.1f,0.1f,0.1f,1.0f}); Gl.glLightfv(Gl.GL_LIGHT1,Gl.GL_DIFFUSE,new float[]{0.1f,0.1f,0.1f,1.0f}); Gl.glLightfv(Gl.GL_LIGHT1,Gl.GL_SPECULAR,new float[]{0.1f,0.1f,0.1f,1.0f}); } public void SituaBomb() { Gl.glLightfv(Gl.GL_LIGHT0,Gl.GL_AMBIENT,new float[]{0.1f,0.1f,0.1f,1.0f}); Gl.glLightfv(Gl.GL_LIGHT0,Gl.GL_DIFFUSE,new float[]{0.1f,0.1f,0.1f,1.0f}); Gl.glLightfv(Gl.GL_LIGHT0,Gl.GL_SPECULAR,new float[]{0.1f,0.1f,0.1f,1.0f}); Gl.glLightfv(Gl.GL_LIGHT0,Gl.GL_POSITION,new float[]{0f,0f,0f,1.0f}); Gl.glLightf(Gl.GL_LIGHT0,Gl.GL_SPOT_CUTOFF,60); Gl.glLightfv(Gl.GL_LIGHT0,Gl.GL_SPOT_DIRECTION,new float[]{0f,0f,-1.0f}); } public void SituaLuzNum2() { Gl.glLightfv(Gl.GL_LIGHT2,Gl.GL_AMBIENT,new float[]{0.3f,0.3f,0.3f,1.0f}); Gl.glLightfv(Gl.GL_LIGHT2,Gl.GL_DIFFUSE,new float[]{0.3f,0.3f,0.3f,1.0f}); Gl.glLightfv(Gl.GL_LIGHT2,Gl.GL_SPECULAR,new float[]{0.3f,0.3f,0.3f,1.0f}); Gl.glLightfv(Gl.GL_LIGHT2,Gl.GL_POSITION,new float[]{0f,12f,-15f,1.0f}); Gl.glLightf(Gl.GL_LIGHT2,Gl.GL_SPOT_CUTOFF,60); Gl.glLightfv(Gl.GL_LIGHT2,Gl.GL_SPOT_DIRECTION,new float[]{0f,-1f,0.0f}); } public void EncenderLuzAmb(bool on) { if(on) { Gl.glEnable(Gl.GL_LIGHT1); } else Gl.glDisable(Gl.GL_LIGHT1); } public void EncenderLuzNum2(bool on) { if(on) { Gl.glEnable(Gl.GL_LIGHT2); } else Gl.glDisable(Gl.GL_LIGHT2); } public void EncenderBomb(bool on) { if(on) {// si el ultimo elemento del arreglo es 1 la luz es puntual Gl.glEnable(Gl.GL_LIGHT0); } else Gl.glDisable(Gl.GL_LIGHT0); } #endregion #region Seleccion de Objetos public int[] StartPicking(int cursorX, int cursorY) { int[] viewport = new int[4]; int[] selectBuf = new int[512]; Gl.glSelectBuffer(512, selectBuf); Gl.glRenderMode(Gl.GL_SELECT); Gl.glMatrixMode(Gl.GL_PROJECTION); Gl.glPushMatrix(); Gl.glLoadIdentity(); Gl.glGetIntegerv(Gl.GL_VIEWPORT,viewport); Glu.gluPickMatrix(cursorX, viewport[3]-cursorY, 5, 5, viewport); Glu.gluPerspective(45.0, (double)viewport[2] / (double)viewport[3], 0.1, 1500); Gl.glMatrixMode(Gl.GL_MODELVIEW); Gl.glInitNames(); Gl.glPushName(0); return selectBuf; } /// <summary> /// Metodo que se utiliza para parar la seleccion. /// </summary> public int StopPicking() { int hits; // restoring the original projection matrix Gl.glMatrixMode(Gl.GL_PROJECTION); Gl.glPopMatrix(); Gl.glMatrixMode(Gl.GL_MODELVIEW); Gl.glFlush(); // returning to normal rendering mode hits = Gl.glRenderMode(Gl.GL_RENDER); return hits; } /// <summary> /// Procesa cada hits /// </summary> public int ProcessHits(int hits, int[] buffer) { int i; int[] ptr; int minz = Int32.MaxValue; int name = 0; ptr = buffer; for(i = 0; i < hits*4; i+=4) if(ptr[i+1] < minz) { minz = ptr[i+1]; name = ptr[i+3]; } return name; } /// <summary> /// Dibuja los elementos para la seleccion. /// </summary> public void DrawElementsName() { //cada vez que se le ponga un nombre en la pila habra algo diferente en los hits element.Draw(); } public bool SelectElement(int xp, int yp) { int[] selectBuf = StartPicking(xp, yp); DrawElementsName(); int hits = StopPicking(); int id = ProcessHits(hits, selectBuf); if(id > 0) { nombre=element.GetObjName(id); if(nombre!="")return true; else return false; } return false; } #endregion #region Manipular Escena public void Redraw() { if (redraw != null) redraw(this, EventArgs.Empty); } public virtual void Reshape(int width, int height) { if (height == 0) height = 1; Gl.glViewport(0, 0, width, height); Gl.glMatrixMode(Gl.GL_PROJECTION); Gl.glLoadIdentity(); Glu.gluPerspective(45.0, (double)width / (double)height, 0.1, 1500); Gl.glMatrixMode(Gl.GL_MODELVIEW); Gl.glLoadIdentity(); } public void Initialize() { Gl.glShadeModel(Gl.GL_SMOOTH); Gl.glClearColor(0f, 0.5f, 0.5f, 1.0f); Gl.glClearDepth(1.0f); Gl.glClearStencil(0); Gl.glEnable(Gl.GL_DEPTH_TEST); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glCullFace(Gl.GL_BACK); // //Glut.glutTimerFunc( 300,new Glut.TimerCallback(Arrollando),1); Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST); Reshape(640, 480); } #endregion #endregion #region properties public bool BombiOn { get{return this.bomon;} set{bomon=value;} } public bool AmbiOn { get{return this.ambon;} set{ambon=value;} } public float[] Color { get { return color; } set { color = value; Redraw(); } } #endregion #region eventos /// <summary> /// evento para mandar a dibujar. /// </summary> public event EventHandler redraw; #endregion eventos } <file_sep>/InteriorMB.cs using System; using Materiales; using Tao.OpenGl; public class InteriorMB:Interior { Asiento[] delant; Timon t; Goma respuesto; LimpParab[] lp; int lpang=21; int lpincf=1; public InteriorMB(Point3D pst):base(pst) { delant=new Asiento[2]; lp=new LimpParab[2]; lp[0]=new LimpParab(new Point3D(pst.x+1,pst.y+0.5,pst.z+0.25),1); lp[1]=new LimpParab(new Point3D(pst.x-1,pst.y+0.4,pst.z+0.17),1); for(int i=0;i<2;i++) { delant[i]=new Asiento(new Point3D(start.x-1.5,start.y-0.5,start.z+0.3-i*2),1.5,1.5,2.5,new float[]{0.55f,0.55f,0.55f}); } t=new Timon(new Point3D(start.x+1.7,start.y+0.2,start.z-1),0.6,new float[]{0.3f,0.3f,0.2f}); respuesto=new Goma(new Point3D(start.x-5,start.y-0.5,start.z),0.8); Recompile(); } public override void Recompile() { foreach(Asiento a in delant) a.Recompile(); foreach(LimpParab a in lp) a.Recompile(); t.Recompile(); respuesto.Recompile(); Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glDisable(Gl.GL_CULL_FACE); Material pn=new PlasticoNegro(); Gl.glColor3d(pn.Ambient.r,pn.Ambient.g,pn.Ambient.b); pn.Set(); Gl.glBegin(Gl.GL_POLYGON); Gl.glNormal3d(0,-1,0); Gl.glVertex3d(start.x-1.7,start.y-1.9,start.z-2.5); Gl.glVertex3d(start.x+3.35,start.y-1.9,start.z-2.5); Gl.glVertex3d(start.x+3.35,start.y-1.9,start.z+2.5); Gl.glVertex3d(start.x-1.7,start.y-1.9,start.z+2.5); Gl.glEnd(); Gl.glBegin(Gl.GL_POLYGON); Gl.glVertex3d(start.x-1.7,start.y-1.9,start.z-2.4); Gl.glVertex3d(start.x-1.7,start.y-1.9,start.z+2.4); Gl.glVertex3d(start.x-3.7,start.y+0.1,start.z+2.4); Gl.glVertex3d(start.x-3.7,start.y+0.1,start.z-2.4); Gl.glEnd(); Gl.glBegin(Gl.GL_POLYGON); Gl.glNormal3d(0,1,0); Gl.glVertex3d(start.x+7,start.y-0.2,start.z-2.4); Gl.glVertex3d(start.x+7,start.y-0.9,start.z-2.4); Gl.glVertex3d(start.x+7,start.y-0.9,start.z+2.4); Gl.glVertex3d(start.x+7,start.y-0.2,start.z+2.4); Gl.glEnd(); Gl.glBindTexture(Gl.GL_TEXTURE_2D,Otros.texture[4]); Gl.glBegin(Gl.GL_POLYGON); Gl.glNormal3d(0,1,0); Gl.glTexCoord2d(0,0); Gl.glVertex3d(start.x+3,start.y-0.2,start.z-2.4); Gl.glTexCoord2d(1,0); Gl.glVertex3d(start.x+3,start.y-0.2,start.z+2.4); Gl.glTexCoord2d(1,1); Gl.glVertex3d(start.x+2,start.y-1.9,start.z+2.4); Gl.glTexCoord2d(0,1); Gl.glVertex3d(start.x+2,start.y-1.9,start.z-2.4); Gl.glEnd(); Gl.glBindTexture(Gl.GL_TEXTURE_2D,0); pn.UnSet(); pn=new Plata(); Gl.glColor3d(pn.Ambient.r,pn.Ambient.g,pn.Ambient.b); pn.Set(); Gl.glBegin(Gl.GL_POLYGON); Gl.glNormal3d(0,1,0); Gl.glVertex3d(start.x-6,start.y-1,start.z-2); Gl.glVertex3d(start.x-4,start.y-1,start.z-2); Gl.glVertex3d(start.x-4,start.y-1,start.z+2); Gl.glVertex3d(start.x-6,start.y-1,start.z+2); Gl.glEnd(); pn.UnSet(); Gl.glBindTexture(Gl.GL_TEXTURE_2D,Otros.texture[3]); Gl.glBegin(Gl.GL_POLYGON); Gl.glNormal3d(0,1,0); Gl.glTexCoord2d(1,0);Gl.glVertex3d(start.x+7,start.y-0.2,start.z-2.4); Gl.glTexCoord2d(1,1);Gl.glVertex3d(start.x+3,start.y-0.2,start.z-2.4); Gl.glTexCoord2d(0,1);Gl.glVertex3d(start.x+3,start.y-0.2,start.z+2.4); Gl.glTexCoord2d(0,0);Gl.glVertex3d(start.x+7,start.y-0.2,start.z+2.4); Gl.glEnd(); Gl.glBindTexture(Gl.GL_TEXTURE_2D,0); Gl.glColor3d(0.7,0.7,0.5); Gl.glBindTexture(Gl.GL_TEXTURE_2D,Otros.texture[0]); Gl.glBegin(Gl.GL_POLYGON); Gl.glNormal3d(0,-1,0); Gl.glTexCoord2d(0,0);Gl.glVertex3d(start.x+2.3,start.y+0.2,start.z-2.45); Gl.glTexCoord2d(1,0);Gl.glVertex3d(start.x+2.3,start.y+0.2,start.z+2.45); Gl.glTexCoord2d(1,1);Gl.glVertex3d(start.x+2,start.y-0.5,start.z+2.45); Gl.glTexCoord2d(0,1);Gl.glVertex3d(start.x+2,start.y-0.5,start.z-2.45); Gl.glEnd(); Gl.glBindTexture(Gl.GL_TEXTURE_2D,0); Gl.glColor3d(0,0,0); Gl.glBegin(Gl.GL_POLYGON); Gl.glNormal3d(0,1,0); Gl.glVertex3d(start.x+2.35,start.y+0.2,start.z-2.45); Gl.glVertex3d(start.x+2.35,start.y+0.2,start.z+2.45); Gl.glVertex3d(start.x+2.05,start.y-0.5,start.z+2.45); Gl.glVertex3d(start.x+2.05,start.y-0.5,start.z-2.45); Gl.glEnd(); Gl.glBegin(Gl.GL_POLYGON); Gl.glNormal3d(0,1,0); Gl.glVertex3d(start.x+2.35,start.y+0.4,start.z-1); Gl.glVertex3d(start.x+2.35,start.y+0.4,start.z+1); Gl.glVertex3d(start.x+2.25,start.y,start.z+1); Gl.glVertex3d(start.x+2.25,start.y,start.z-1); Gl.glEnd(); Gl.glBegin(Gl.GL_TRIANGLE_STRIP); Gl.glNormal3d(0,1,0); Gl.glVertex3d(start.x+2.35,start.y+0.4,start.z+1); Gl.glVertex3d(start.x+2.25,start.y,start.z+2.3); Gl.glVertex3d(start.x+2.25,start.y,start.z+1); Gl.glEnd(); Gl.glBegin(Gl.GL_TRIANGLE_STRIP); Gl.glNormal3d(0,1,0); Gl.glVertex3d(start.x+2.35,start.y+0.4,start.z-1); Gl.glVertex3d(start.x+2.25,start.y,start.z-2.3); Gl.glVertex3d(start.x+2.25,start.y,start.z-1); Gl.glEnd(); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glPopMatrix(); Gl.glEndList(); } public override void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); this.Rota(); t.Rota(90,0,1,0); t.Draw(); if(onlp) { lpang+=lpincf; if(lpang>=90 || lpang<=20) lpincf=-lpincf; } lp[1].Rota(-10,0,1,0); Gl.glPushMatrix(); lp[1].Rota(56,-1,0,0); lp[1].Rota(lpang,0,0,1); lp[1].Draw(); Gl.glPopMatrix(); lp[1].Rota(10,0,1,0); lp[0].Rota(10,0,1,0); Gl.glPushMatrix(); lp[0].Rota(55,-1,0,0); lp[0].Rota(lpang,0,0,1); lp[0].Draw(); Gl.glPopMatrix(); lp[0].Rota(-10,0,1,0); t.Rota(-90,0,1,0); respuesto.Rota(90,1,0,0); respuesto.Draw(); respuesto.Rota(-90,1,0,0); foreach(Asiento a in delant) a.Draw(); Gl.glCallList(idVisualizar); Gl.glPopMatrix(); } } } <file_sep>/Ortoedro.cs using System; using Tao.OpenGl; using Tao.Glut; public class Ortoedro:Element { Point3D start; double ancho,alto,largo; float[] col; public Ortoedro(Point3D inicio,double anch,double lar,double alt,float[] color):base() { start=inicio; ancho=anch; largo=lar; alto=alt; col=color; this.Recompile(); } public override void Recompile() { Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glTranslated(start.x+ancho/2.0,start.y-alto/2.0,start.z-largo/2.0); Gl.glScaled(this.ancho,this.alto,this.largo); Gl.glColor3fv(col); Glut.glutSolidCube(1); // Gl.glColor3d(1.0,1.0,0.2); // Gl.glBegin(Gl.gl.Gl.gl_POINTS); // Gl.glVertex3d(0,0,0); // Gl.glVertex3d(-0.5,0.5,0.5); // Gl.glEnd(); Gl.glPopMatrix(); Gl.glEndList(); } public override void Draw() { Gl.glPushMatrix(); this.Rota(); Gl.glCallList(idVisualizar); Gl.glPopMatrix(); // Gl.glBegin(Gl.gl.Gl.gl_POINTS); // Gl.glVertex3d(this.PuntoRotacion.x,this.PuntoRotacion.y,this.PuntoRotacion.z); // Gl.glEnd(); } public override Point3D PuntoRotacion { get { return new Point3D(start.x,start.y,start.z); } } public Point3D Inicio{ get{return this.start;} } public double Alto{ get{return this.alto;} } public double Ancho { get{return this.ancho;} } public float[] Color{ get{return this.col;} } public double Largo { get{return this.largo;} } } <file_sep>/Sofa.cs using System; using Tao.OpenGl; using System.Xml; using Materiales; using System.Collections; using System.Windows.Forms; public class Sofa:Element,I3dsTaken { public _3dsLoader sof; protected Point3D center; public Sofa() { sof=this.load3ds("sofa.3ds"); sof.ComputeNormals(); this.Recompile(); } public override void Recompile() { Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glDisable(Gl.GL_CULL_FACE); sof.paint(false,this); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glPopMatrix(); Gl.glEndList(); } public override Point3D PuntoRotacion { get { return center; } } public bool Actions(obj_type o,bool _shadow, int[] rot, float[] trans, float[] scl) { return false; } private _3dsLoader load3ds(string path) { XmlTextReader doc = new XmlTextReader(Application.StartupPath + "\\" + "Models\\" + "models.xml"); string id = ""; _3dsLoader temp = null; string name = ""; int[] rot = null; float[] trans = null; float[] scl = null; bool notdone=true; while (doc.Read() && notdone) { switch (doc.NodeType) { case XmlNodeType.Element: switch (doc.Name) { case "model": if(doc.GetAttribute("id")!=path) doc.Skip(); else id = doc.GetAttribute("id"); break; case "name": name = (string)(doc.GetAttribute("id")); break; case "rot": rot = new int[3]; rot[0] = Int32.Parse(doc.GetAttribute("x")); rot[1] = Int32.Parse(doc.GetAttribute("y")); rot[2] = Int32.Parse(doc.GetAttribute("z")); break; case "trans": trans = new float[3]; trans[0] = Single.Parse(doc.GetAttribute("x")); trans[1] = Single.Parse(doc.GetAttribute("y")); trans[2] = Single.Parse(doc.GetAttribute("z")); break; case "scl": scl = new float[3]; scl[0] = Single.Parse(doc.GetAttribute("x")); scl[1] = Single.Parse(doc.GetAttribute("y")); scl[2] = Single.Parse(doc.GetAttribute("z")); break; } break; case XmlNodeType.EndElement: switch (doc.Name) { case "model": temp = new _3dsLoader(id, name, rot, trans, scl); center=new Point3D(trans[0],trans[1],trans[2]); temp.Load3DS(Application.StartupPath + "\\" + "Models\\" + temp.ID); notdone=false; return temp; } break; } } return null; } } <file_sep>/Interior.cs using System; public abstract class Interior:Element { protected Point3D start; public bool onlp=false; public Interior(Point3D pst) { start=pst; } public override Point3D PuntoRotacion { get { return start; } } } <file_sep>/calob.cs using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; public class calob : System.Windows.Forms.Form { Form1 form1; private System.Windows.Forms.TrackBar trackBar1; private System.Windows.Forms.Button button1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public calob(float initVal,Form1 form) { // // Required for Windows Form Designer support // InitializeComponent(); form1=form; this.trackBar1.Value=(int)initVal; // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.trackBar1 = new System.Windows.Forms.TrackBar(); this.button1 = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit(); this.SuspendLayout(); // // trackBar1 // this.trackBar1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBar1.Location = new System.Drawing.Point(24, 16); this.trackBar1.Maximum = 255; this.trackBar1.Name = "trackBar1"; this.trackBar1.Orientation = System.Windows.Forms.Orientation.Vertical; this.trackBar1.Size = new System.Drawing.Size(45, 152); this.trackBar1.SmallChange = 5; this.trackBar1.TabIndex = 1; this.trackBar1.TickFrequency = 5; this.trackBar1.Value = 1; this.trackBar1.ValueChanged += new System.EventHandler(this.trackBar1_ValueChanged); this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll_1); // // button1 // this.button1.Font = new System.Drawing.Font("Rockwell", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button1.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(255)), ((System.Byte)(255))); this.button1.Location = new System.Drawing.Point(8, 200); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(208, 40); this.button1.TabIndex = 2; this.button1.Text = "Poner Este Color"; this.button1.Click += new System.EventHandler(this.button1_Click); // // calob // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.Color.Maroon; this.ClientSize = new System.Drawing.Size(224, 256); this.Controls.Add(this.button1); this.Controls.Add(this.trackBar1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Location = new System.Drawing.Point(10, 506); this.Name = "calob"; this.Opacity = 0.5; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "calob"; this.TopMost = true; ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit(); this.ResumeLayout(false); } #endregion private void trackBar1_Scroll(object sender, System.EventArgs e) { ((Lugar)form1.scene.element).bas.car.OscuridadCristal=trackBar1.Value; ((Lugar)form1.scene.element).bas.car.Recompile(); form1.Refresh(); } private void button1_Click(object sender, System.EventArgs e) { this.Close(); } private void trackBar1_Scroll_1(object sender, System.EventArgs e) { } private void trackBar1_ValueChanged(object sender, System.EventArgs e) { ((Lugar)form1.scene.element).bas.car.OscuridadCristal=trackBar1.Value; ((Lugar)form1.scene.element).bas.car.Recompile(); form1.Refresh(); } } <file_sep>/README.md ConcesionarioVirtual ==================== Concesionario virtual implementado en C# usando OpenGL y el framework TAO. ![Imagen](/img/captura.png "Imagen") El coche es un archivo creado en 3dStudio Max y cargado en la aplicacion mediante su descomposición en poligonos. A los diferentes objetos que componen el modelo 3ds se les realizan cambios en los materiales, asi como transformaciones como rotar y trasladar, ademas de otras acciones como cliping , para conseguir lograr representar el modelo de diversas maneras. Tambien se usan otras posibilidades como un pequeño sistema de particulas para el humo del motor y el stencil buffer para el reflejo del mismo en la supericie que lo sostiene. La escena cuenta con tres luces: una ambiental, una direccional ubicada cerca de la camara, en el origen y una tercera sobre el vehiculo para permitir la mejor visualizacion del interior del mismo. De la misma forma se usan varias texturas para modelar el lugar y el interior del coche. Para manipular la exposición se brinda una ventana hija “control remoto” que es bastante autoexplicativa. Ademas hay un conjunto de teclas a las que la aplicación respondera. Estas son: R: Oculta o/ Muestra el Control Remoto X,y,z: Seleccionan un eje. I,d: Incrementan y decrementan la rotacion para el eje seleccionado N,m: Mueven la camara adelante/atrás en el eje Z : Mueven la camara adelante/atrás en el eje X : Mueven la camara adelante/atrás en el eje Y q:Enciende/Apaga la luz del bombillo que acompa;a la camara w:Enciende/Apaga la luz ambiental <file_sep>/Particula.cs using System; using Tao.OpenGl; public class Particula:Element { public static int MaxParticles = 500; // Number of particles to create public bool rainbow = true; // Rainbow Mode? public bool sp = false; // Spacebar Pressed? public bool rp = false; // Enter Key Pressed? public float slowdown = 2.0f; // Slow Down Particles public float xspeed = 0.0f; // Base X Speed (To Allow Keyboard Direction Of Tail) public float yspeed = 0.0f; // Base Y Speed (To Allow Keyboard Direction Of Tail) public float zoom = -140.0f; // Used To Zoom Out public uint col = 0; // Current Color Selection public uint delay = 0; // Rainbow Effect Delay public Random rand = null; // Random number generator Particle[] particle = null; // Particle Array (Room For Particle Info) Point3D start; public static float[][] colors = new float[12][] { // Rainbow Of Colors new float[3] {1.0f,0.5f,0.5f}, new float[3] {1.0f,0.75f,0.5f}, new float[3] {1.0f,1.0f,0.5f}, new float[3] {0.75f,1.0f,0.5f}, new float[3] {0.5f,1.0f,0.5f}, new float[3] {0.5f,1.0f,0.75f}, new float[3] {0.5f,1.0f,1.0f}, new float[3] {0.5f,0.75f,1.0f}, new float[3] {0.5f,0.5f,1.0f}, new float[3] {0.75f,0.5f,1.0f}, new float[3] {1.0f,0.5f,1.0f}, new float[3] {1.0f,0.5f,0.75f} }; public bool finished; public class Particle // Create A Structure For Particle { public bool active; // Active (Yes/No) public float life; // Particle Life public float fade; // Fade Speed public float r, g, b; // Color public float x, y, z; // Position public float xi, yi, zi; // Direction public float xg, yg, zg; // Gravity } public Particula(Point3D pst) { this.finished = false; this.particle = new Particle[Particula.MaxParticles]; for (int i=0; i < Particula.MaxParticles; i++) this.particle[i] = new Particle(); start=pst; this.rand = new Random(); for (int loop=0; loop < Particula.MaxParticles; loop++) // Initials All The Textures { this.particle[loop].active = true; // Make All The Particles Active this.particle[loop].life = 0.5f; // Give All The this.particles Full Life this.particle[loop].fade = (float)(this.rand.Next(100))/1000.0f+0.003f; // Random Fade Speed this.particle[loop].r = Particula.colors[loop*(12/Particula.MaxParticles)][0]; // Select Red Rainbow Color this.particle[loop].g = Particula.colors[loop*(12/Particula.MaxParticles)][1]; // Select Red Rainbow Color this.particle[loop].b = Particula.colors[loop*(12/Particula.MaxParticles)][2]; // Select Red Rainbow Color this.particle[loop].xi = (float)(this.rand.Next(50)*-10.0f); // Random Speed On X Axis this.particle[loop].yi = (float)((this.rand.Next(50))-25.0f)*5.0f; // Random Speed On Y Axis this.particle[loop].zi = (float)((this.rand.Next(50))-25.0f)*5.0f; // Random Speed On Z Axis this.particle[loop].xg = 0.1f; // Set Horizontal Pull To Zero this.particle[loop].yg = 0.3f; // Set Vertical Pull Downward this.particle[loop].zg = 0.0f; // Set Pull On Z Axis To Zero this.particle[loop].x=(float)pst.x; this.particle[loop].y=(float)pst.y; this.particle[loop].y=(float)pst.z; } } public override void Recompile() { } public override void Draw() { //Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT); Gl.glBindTexture(Gl.GL_TEXTURE_2D,Otros.texture[13]); //Gl.glDisable(Gl.GL_DEPTH_TEST); // Enables Depth Testing Gl.glEnable(Gl.GL_BLEND); // Enable Blending Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE); // Type Of Blending To Perform Gl.glHint(Gl.GL_POINT_SMOOTH_HINT, Gl.GL_NICEST); Gl.glDisable(Gl.GL_CULL_FACE); for (int loop=0; loop < Particula.MaxParticles; loop++) // Loop Through All The Particles { if (this.particle[loop].active) // If The Particle Is Active { float x = this.particle[loop].x; // Grab Our Particle X Position float y = this.particle[loop].y; // Grab Our Particle Y Position float z = this.particle[loop].z; // Particle Z Pos + Zoom // Draw The Particle Using Our RGB Values, Fade The Particle Based On It's Life Gl.glColor4f(this.particle[loop].r, this.particle[loop].g, this.particle[loop].b, this.particle[loop].life); Gl.glBegin(Gl.GL_TRIANGLE_STRIP); // Build Quad From A TrianGL.gle Strip Gl.glTexCoord2d(1, 1); Gl.glVertex3f(x+0.05f, y+0.05f, z); // Top Right Gl.glTexCoord2d(0, 1); Gl.glVertex3f(x-0.05f, y+0.05f, z); // Top Left Gl.glTexCoord2d(1, 0); Gl.glVertex3f(x+0.05f, y-0.05f, z); // Bottom Right Gl.glTexCoord2d(0, 0); Gl.glVertex3f(x-0.05f, y-0.05f, z); // Bottom Left Gl.glEnd(); // Done Building TrianGL.gle Strip this.particle[loop].x += this.particle[loop].xi/(slowdown*1000);// Move On The X Axis By X Speed this.particle[loop].y += this.particle[loop].yi/(slowdown*1000);// Move On The Y Axis By Y Speed this.particle[loop].z += this.particle[loop].zi/(slowdown*1000);// Move On The Z Axis By Z Speed this.particle[loop].xi += this.particle[loop].xg; // Take Pull On X Axis Into Account this.particle[loop].yi += this.particle[loop].yg; // Take Pull On Y Axis Into Account this.particle[loop].zi += this.particle[loop].zg; // Take Pull On Z Axis Into Account this.particle[loop].life -= this.particle[loop].fade; // Reduce Particles Life By 'Fade' if (this.particle[loop].life < 0.0f) // If Particle Is Burned Out { this.particle[loop].life = 0.5f; // Give It New Life this.particle[loop].fade = (float)(this.rand.Next(100))/1000.0f+0.003f; // Random Fade Value this.particle[loop].x = (float)start.x; // Center On X Axis this.particle[loop].y = (float)start.y; // Center On Y Axis this.particle[loop].z = (float)start.z; // Center On Z Axis this.particle[loop].xi = this.xspeed+(float)(-1*this.rand.Next(50)); // X Axis Speed And Direction this.particle[loop].yi = this.yspeed+(float)((this.rand.Next(60)-30.0f)/2.0f); // Y Axis Speed And Direction this.particle[loop].zi = (float)((this.rand.Next(60)-30.0f)/2.0f); // Z Axis Speed And Direction this.particle[loop].r = Particula.colors[this.col][0]; // Select Red From Color Table this.particle[loop].g = Particula.colors[this.col][1]; // Select Green From Color Table this.particle[loop].b = Particula.colors[this.col][2]; // Select Blue From Color Table } } } if (this.rainbow && (this.delay > 25)) { this.delay = 0; // Reset The Rainbow Color Cycling Delay this.col = (this.col + 1) % 12; // Change The Particle Color } delay++; // Increase Rainbow Mode Color Cycling Delay Counter Gl.glBindTexture(Gl.GL_TEXTURE_2D,0); Gl.glEnable(Gl.GL_DEPTH_TEST); // Enables Depth Testing Gl.glDisable(Gl.GL_BLEND); // Enable Blending Gl.glEnable(Gl.GL_CULL_FACE); // Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE); // Type Of Blending To Perform // Gl.glHint(Gl.GL_POINT_SMOOTH_HINT, Gl.GL_NICEST); } public override Point3D PuntoRotacion { get { return new Point3D (0,0,0); } } } <file_sep>/Base111.cs using System; using Tao.OpenGl; using Materiales; using Tao.Glut; public class Base111:Element { public Carro car; int rad; Point3D start; float[] col; public int crang; public bool rotando=true; int inc =2; Glu.GLUquadric q; // Quadratic For Drawing A Sphere float zoom = -4.0f; // Depth Into The Screen float height = 2.7f; public Base111(Point3D pst,int radio,float[] color) { start=pst; col=color; rad=radio; car=new mb380(); crang=0; this.Recompile(); } void DrawFloor() // Draws The Floor { Gl.glBindTexture(Gl.GL_TEXTURE_2D,Otros.texture[9]); Gl.glPushMatrix(); Gl.glDisable(Gl.GL_CULL_FACE); q=Glu.gluNewQuadric(); Glu.gluQuadricOrientation(q,Glu.GLU_OUTSIDE); Glu.gluQuadricTexture(q,Glu.GLU_TRUE); Glu.gluQuadricNormals(q,Glu.GLU_SMOOTH); Glu.gluDisk(q,0,7,32,32); Gl.glBindTexture(Gl.GL_TEXTURE_2D,0); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glPopMatrix(); } public override void Recompile() { car.Recompile(); idVisualizar=Gl.glGenLists(3); #region Lista 1 Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); // Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT | Gl.GL_STENCIL_BUFFER_BIT); //double[] eqr = {0,-1,0,0}; Gl.glDisable(Gl.GL_CULL_FACE); Gl.glTranslated(start.x,start.y,start.z); Gl.glRotated(90,1,0,0); Material m=new Jade(); Gl.glColor3d(0.2,0.4,0.8); m.Set(); Glu.GLUquadric cil; cil=Glu.gluNewQuadric(); Gl.glBindTexture(Gl.GL_TEXTURE_2D,Otros.texture[2]); Glu.gluQuadricOrientation(cil,Glu.GLU_INSIDE); Glu.gluQuadricTexture(cil,Otros.texture[1]); Glu.gluCylinder(cil,rad,rad,rad/3,32,32); Gl.glBindTexture(Gl.GL_TEXTURE_2D,0); double[] eqr = {0.0f,-1.0f, 0.0f, 0.0f}; // Plane Equation To Use For The Reflected Objects //Gl.glLoadIdentity(); // Reset The Modelview Matrix //Gl.glTranslatef(0.0f, -0.6f, zoom); // Zoom And Raise Camera Above The Floor (Up 0.6 Units) //Gl.glColorMask(0,0,0,0); // Set Color Mask Gl.glEnable(Gl.GL_STENCIL_TEST); // Enable Stencil Buffer For "marking" The Floor Gl.glStencilFunc(Gl.GL_ALWAYS, 1, 1); // Always Passes, 1 Bit Plane, 1 As Mask Gl.glStencilOp(Gl.GL_KEEP, Gl.GL_KEEP, Gl.GL_REPLACE); // We Set The Stencil Buffer To 1 Where We Draw Any Polygon // Keep If Test Fails, Keep If Test Passes But Buffer Test Fails // Replace If Test Passes Gl.glDisable(Gl.GL_DEPTH_TEST); // Disable Depth Testing DrawFloor(); // Draw The Floor (Draws To The Stencil Buffer) // We Only Want To Mark It In The Stencil Buffer Gl.glEnable(Gl.GL_DEPTH_TEST); // Enable Depth Testing Gl.glColorMask(1,1,1,1); // Set Color Mask to TRUE, TRUE, TRUE, TRUE Gl.glStencilFunc(Gl.GL_EQUAL, 1, 1); // We Draw Only Where The Stencil Is 1 // (I.E. Where The Floor Was Drawn) Gl.glStencilOp(Gl.GL_KEEP, Gl.GL_KEEP, Gl.GL_KEEP); // Don't Change The Stencil Buffer Gl.glEnable(Gl.GL_CLIP_PLANE0); // Enable Clip Plane For Removing Artifacts // (When The Object Crosses The Floor) Gl.glClipPlane(Gl.GL_CLIP_PLANE0, eqr); // Equation For Reflected Objects Gl.glPushMatrix(); // Push The Matrix Onto The Stack Gl.glScalef(1.0f, 1.0f, -1.0f); // Mirror Y Axis Gl.glTranslatef(0.0f, 0.0f,-height); // Position The Object Gl.glEndList(); #endregion Lista1 DrawObject(); // Draw The Sphere (Reflection) #region Lista 2 Gl.glNewList(idVisualizar+1,Gl.GL_COMPILE); Gl.glPopMatrix(); // Pop The Matrix Off The Stack Gl.glDisable(Gl.GL_CLIP_PLANE0); // Disable Clip Plane For Drawing The Floor Gl.glDisable(Gl.GL_STENCIL_TEST); // We Don't Need The Stencil Buffer Any More (Disable) Gl.glEnable(Gl.GL_BLEND); // Enable Blending (Otherwise The Reflected Object Wont Show) Gl.glColor4f(0f, 0f, 0f, 0.6f); // Set Color To White With 80% Alpha Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA); // Blending Base111d On Source Alpha And 1 Minus Dest Alpha Gl.glRotated(180,1,0,0); DrawFloor(); // Draw The Floor To The Screen Gl.glRotated(180,1,0,0); Gl.glEnable(Gl.GL_LIGHTING); // Enable Lighting Gl.glDisable(Gl.GL_BLEND); // Disable Blending Gl.glTranslatef(0.0f, 0.0f,-height); // Position The Ball At Proper Height Gl.glEndList(); #endregion Lista 2 DrawObject(); // Draw The Ball #region Lista 3 Gl.glNewList(idVisualizar+2,Gl.GL_COMPILE); m.UnSet(); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glPopMatrix(); Gl.glEndList(); #endregion Lista 3 } public override Point3D PuntoRotacion { get { return start; } } void DrawObject() // Draw Our Ball { Gl.glColor3f(1.0f, 1.0f, 1.0f); // Set Color To White Gl.glBindTexture(Gl.GL_TEXTURE_2D, Otros.texture[1]); // Select Texture 2 (1) Glu.GLUquadric q; q = Glu.gluNewQuadric(); // Create A New Quadratic Glu.gluQuadricNormals(q,Gl.GL_SMOOTH); // Generate Smooth Normals For The Quad Glu.gluQuadricTexture(q,Gl.GL_TRUE); Glu.gluSphere(q, 0.35f, 32, 16); // Draw First Sphere Gl.glBindTexture(Gl.GL_TEXTURE_2D, Otros.texture[0]); // Select Texture 3 (2) Gl.glColor4f(1.0f, 1.0f, 1.0f, 0.4f); // Set Color To White With 40% Alpha Gl.glEnable(Gl.GL_BLEND); // Enable Blending Gl.glBlendFunc(Gl.GL_SRC_ALPHA,Gl.GL_ONE); // Set Blending Mode To Mix Base111d On SRC Alpha Gl.glEnable(Gl.GL_TEXTURE_GEN_S); // Enable Sphere Mapping Gl.glEnable(Gl.GL_TEXTURE_GEN_T); // Enable Sphere Mapping Glu.gluSphere(q, 0.35f, 32, 16); // Draw Another Sphere Using New Texture // Textures Will Mix Creating A MultiTexture Effect (Reflection) Gl.glDisable(Gl.GL_TEXTURE_GEN_S); // Disable Sphere Mapping Gl.glDisable(Gl.GL_TEXTURE_GEN_T); // Disable Sphere Mapping Gl.glDisable(Gl.GL_BLEND); // Disable Blending } public override void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); if(rotando) crang=(crang+this.inc); if(Math.Abs(crang)>=90) inc=-inc; this.Rota(); this.Rota(crang,0,1,0); //car.Draw(); // Gl.glCallList(idVisualizar); Gl.glPushMatrix(); Gl.glRotated(-90,1,0,0); Gl.glTranslated(-car.car.Trans[0],-car.car.Trans[1],-car.car.Trans[2]); car.Draw(); Gl.glPopMatrix(); Gl.glCallList(idVisualizar+1); Gl.glPushMatrix(); // Gl.glTranslated(car.car.Trans[0],car.car.Trans[1],car.car.Trans[2]); // Gl.glRotated(car.car.Rot[2], 0, 0, 1); // Gl.glRotated(car.car.Rot[1], 0, 1, 0); // Gl.glRotated(car.car.Rot[0], 1, 0, 0); // Gl.glScaled(car.car.Scl[0], car.car.Scl[1],car.car.Scl[2]); // Gl.glScaled(-car.car.Scl[0], -car.car.Scl[1],-car.car.Scl[2]); // Gl.glRotated(-car.car.Rot[0], 1, 0, 0); // Gl.glRotated(-car.car.Rot[1], 0, 1, 0); // Gl.glRotated(-car.car.Rot[2], 0, 0, 1); Gl.glRotated(-90,1,0,0); Gl.glTranslated(-car.car.Trans[0],-car.car.Trans[1],-car.car.Trans[2]); car.Draw(); Gl.glPopMatrix(); Gl.glCallList(idVisualizar+2); Gl.glPopMatrix(); } } } <file_sep>/Cuadro.cs using System; using Tao.OpenGl; public class Cuadro:Element { Point3D start; double lar,anch; int pint,marc; Pared[] tab; int ang; public Cuadro(Point3D pst,double largo,double ancho,int angle,int text,int mtext) { start=pst; lar=largo; anch=ancho; ang=angle; pint=text; marc=mtext; tab=new Pared[4]; tab[0]=new Pared(new Point3D(start.x+largo/2,start.y-0.1,start.z),0,largo,0.2,0.3,mtext); tab[1]=new Pared(new Point3D(start.x+largo,start.y-ancho/2,start.z),0,0.2,ancho,0.3,mtext); tab[2]=new Pared(new Point3D(start.x+largo/2,start.y-ancho+0.1,start.z),0,largo,0.2,0.3,mtext); tab[3]=new Pared(new Point3D(start.x,start.y-ancho/2,start.z),0,0.2,ancho,0.3,mtext); this.Recompile(); } public override void Recompile() { foreach(Pared p in tab) p.Recompile(); Gl.glNewList(idVisualizar,Gl.GL_COMPILE); Gl.glPushMatrix(); Gl.glDisable(Gl.GL_CULL_FACE); Gl.glBindTexture(Gl.GL_TEXTURE_2D,Otros.texture[pint]); Gl.glBegin(Gl.GL_POLYGON); Gl.glTexCoord2d(0,0); Gl.glVertex3d(start.x,start.y,start.z); Gl.glTexCoord2d(1,0); Gl.glVertex3d(start.x+lar,start.y,start.z); Gl.glTexCoord2d(1,1); Gl.glVertex3d(start.x+lar,start.y-anch,start.z); Gl.glTexCoord2d(0,1); Gl.glVertex3d(start.x,start.y-anch,start.z); Gl.glEnd(); Gl.glBindTexture(Gl.GL_TEXTURE_2D,0); Gl.glEnable(Gl.GL_CULL_FACE); Gl.glPopMatrix(); Gl.glEndList(); } public override Point3D PuntoRotacion { get { return start; } } public override void Draw() { if(idVisualizar != 0) { Gl.glPushMatrix(); this.Rota(); this.Rota(ang,0,1,0); foreach(Pared p in tab) p.Draw(); Gl.glCallList(idVisualizar); Gl.glPopMatrix(); } } } <file_sep>/Camara.cs using System; using Tao.OpenGl; public class Camara { public Camara() { } //SetPos(new Point3D(0,0,cz),new Point3D(0,0,-17),0,1,0); public void SetPos(Point3D start,Point3D obj,double vecx,double vecy,double vecz) { Gl.glLoadIdentity(); Glu.gluLookAt(start.x,start.y,start.z,obj.x,obj.y,obj.z,vecx,vecy,vecz); } } <file_sep>/Form1.cs using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Xml; /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private OGLConFlechita simpleOpenglControl1; public Scene scene; private System.ComponentModel.IContainer components; private System.Windows.Forms.Timer timer1; RC rc; public Form1() { scene = new Scene(); scene.redraw += new EventHandler(scene_redraw); InitializeComponent(); simpleOpenglControl1.InitializeContexts(); scene.Initialize(); Otros.LoadTexture(); scene.element=new Lugar();//new Base111(new Point3D(0,-2.6,-20),7,new float[]{1.0f,0.4f,0.2f,1.0f}); rc=new RC(this); rc.Show(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); rc.Close(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.simpleOpenglControl1 = new OGLConFlechita(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // // simpleOpenglControl1 // this.simpleOpenglControl1.AccumBits = ((System.Byte)(0)); this.simpleOpenglControl1.AutoCheckErrors = false; this.simpleOpenglControl1.AutoFinish = false; this.simpleOpenglControl1.AutoMakeCurrent = true; this.simpleOpenglControl1.AutoSwapBuffers = true; this.simpleOpenglControl1.BackColor = System.Drawing.Color.Black; this.simpleOpenglControl1.ColorBits = ((System.Byte)(32)); this.simpleOpenglControl1.DepthBits = ((System.Byte)(16)); this.simpleOpenglControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.simpleOpenglControl1.Location = new System.Drawing.Point(0, 0); this.simpleOpenglControl1.Name = "simpleOpenglControl1"; this.simpleOpenglControl1.Size = new System.Drawing.Size(792, 566); this.simpleOpenglControl1.StencilBits = ((System.Byte)(1)); this.simpleOpenglControl1.TabIndex = 0; this.simpleOpenglControl1.Resize += new System.EventHandler(this.simpleOpenglControl1_Resize); this.simpleOpenglControl1.Load += new System.EventHandler(this.simpleOpenglControl1_Load); this.simpleOpenglControl1.Paint += new System.Windows.Forms.PaintEventHandler(this.simpleOpenglControl1_Paint); this.simpleOpenglControl1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.simpleOpenglControl1_KeyDown); // // timer1 // this.timer1.Enabled = true; this.timer1.Interval = 5; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(792, 566); this.Controls.Add(this.simpleOpenglControl1); this.Name = "Form1"; this.Text = "Form1"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Closed += new System.EventHandler(this.Form1_Closed); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Form1 f=new Form1(); Application.Run(f); while(!f.IsDisposed) { f.Refresh(); } } private void simpleOpenglControl1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { this.scene.Draw(); } private void simpleOpenglControl1_Resize(object sender, System.EventArgs e) { scene.Reshape(simpleOpenglControl1.Width, simpleOpenglControl1.Height); } private void scene_redraw(object sender, EventArgs e) { this.Refresh(); } private void simpleOpenglControl1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if(!DesignMode) { if(e.KeyValue==(int)Keys.R) { rc.Visible=!rc.Visible; } else if(e.KeyValue==(int)Keys.Q) { this.scene.BombiOn=!this.scene.BombiOn; this.scene.EncenderBomb(this.scene.BombiOn); } else if(e.KeyValue==(int)Keys.W) { this.scene.AmbiOn=!this.scene.AmbiOn; this.scene.EncenderLuzAmb(this.scene.AmbiOn); } scene.ProcessInput(e.KeyValue); base.OnKeyDown(e); this.Refresh(); } } private void simpleOpenglControl1_Load(object sender, System.EventArgs e) { } private void Form1_Closed(object sender, System.EventArgs e) { rc.Close(); } private void timer1_Tick(object sender, System.EventArgs e) { this.Refresh(); } }
abc439bbc6355aa03ce78f2d9a2ab7d1bc2c931f
[ "Markdown", "C#" ]
30
C#
jesantana/ConcesionarioVirtual
a0f965edbd68a0d3d02c057a9495613d697628bf
f00b5da59f04e280511055f03e6e99e4c436163d
refs/heads/master
<repo_name>Sheefa96/To-Do-List<file_sep>/src/ListItems.js import React from 'react'; import './ListItems.css'; function ListItems(props){ const items = props.items; const ListItems = items.map((item)=> { return <div className="list" key={item.key}> <p> <input className="checkBox" type = "checkBox"/> <input className="textArea" id = {item.tex} value = {item.text} onChange ={ (e) =>{ props.setUpdate(e.target.value, item.key) } } /> <span className="deleteIcon" onClick={ () => props.deleteItem(item.key)}>X</span> </p> </div> }) return( <div> {ListItems} </div> ) } export default ListItems;
a7dfdf9d0ce04c681d302ba6cefc38bc23a40bb9
[ "JavaScript" ]
1
JavaScript
Sheefa96/To-Do-List
46dfe2784ca034b9a0bafde2f1ae2c2004166449
8812dce1beb213dce557ec95b25b8d7424aef49a
refs/heads/master
<repo_name>PabloCabrera/mkosmos<file_sep>/doc/RemoteArea.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>Clase RemoteArea: μ-κosmos</title> <link rel="stylesheet" type="text/css" href="/shared.css" /> <link rel="stylesheet" type="text/css" href="/desarrolladores.css" /> <script src="/jquery-3.1.1.min.js"></script> </head> <body> <?php include "../nav.php"; ?> <section id="desarrolladores_section"> <h1>Librería javascript</h1> <h2>Métodos de clase RemoteArea</h2> <h3>getSurfaceAtPosition</h3> <p>Obtener el tipo de superficie en las coordenadas dadas <h4>Parámetros:</h4> <dl> <dt>position</dt> <dd class="array">Posición en formato array [x, y]</dd> </dl> <h3>getSurfaceAt</h3> <p>Obtener el tipo de superficie en las coordenadas dadas</p> <h4>Parámetros:</h4> <dl> <dt>x</dt> <dd class="numerico">Coordenada X</dd> <dt>y</dt> <dd class="numerico">Coordenada Y</dd> </dl> <h3>setSurfaceAtPosition</h3> <p>Establecer el tipo de superficie en un punto especifico</p> <h4>Parámetros:</h4> <dl> <dt>position</dt> <dd class="array">Posición en formato array [x, y]</dd> <dt>surface</dt> <dd class="terreno">Tipo de terreno</dd> </dl> <h3>getSurfaceRect</h3> <p>Obtener el tipo de superficie en un rectangulo</p> <h4>Parámetros:</h4> <dl> <dt>left</dt> <dd class="numerico">Límite izquierdo</dd> <dt>top</dt> <dd class="numerico">Límite superior</dd> <dt>right</dt> <dd class="numerico">Límite derecho</dd> <dt>bottom</dt> <dd class="numerico">Límite inferior</dd> </dl> <h3>execOnSurfaceRect</h3> <p>Ejecutar un callback asincrónicamente sobre una región rectangular</p> <h4>Parámetros:</h4> <dl> <dt>left</dt> <dd class="numerico">Límite izquierdo</dd> <dt>top</dt> <dd class="numerico">Límite superior</dd> <dt>right</dt> <dd class="numerico">Límite derecho</dd> <dt>bottom</dt> <dd class="numerico">Límite inferior</dd> <dt>handler</dt> <dd class="callback">Callback</dd> </dl> <h3>setSurfaceAt</h3> <p>Establecer el tipo de superficie en un punto especifico</p> <h4>Parámetros:</h4> <dl> <dt>x</dt> <dd class="numerico">Coordenada X</dd> <dt>y</dt> <dd class="numerico">Coordenada Y</dd> <dt>surface</dt> <dd class=""></dd> </dl> <h3>setSurfaceRect</h3> <p>Establecer el tipo de superficie en un area rectangular</p> <h4>Parámetros:</h4> <dl> <dt>left</dt> <dd class="numerico">Límite izquierdo</dd> <dt>top</dt> <dd class="numerico">Límite superior</dd> <dt>right</dt> <dd class="numerico">Límite derecho</dd> <dt>bottom</dt> <dd class="numerico">Límite inferior</dd> <dt>surface</dt> <dd class="terreno">Tipo de terreno</dd> </dl> <h3>setSurfaceCirclePosition</h3> <p>Establecer el tipo de superficie en un area circular</p> <dl> <dt>position</dt> <dd class="Array">Centro del círculo en formato array [x, y]</dd> <dt>radius</dt> <dd class="numerico">Radio</dd> <dt>surface</dt> <dd class="terreno">Tipo de terreno</dd> </dl> <h3>setSurfaceCircle</h3> <p>Establecer el tipo de superficie en un area circular</p> <h4>Parámetros:</h4> <dl> <dt>x</dt> <dd class="numerico">Coordenada X del centro del círculo</dd> <dt>y</dt> <dd class="numerico">Coordenada Y del centro del círculo</dd> <dt>radius</dt> <dd class="numerico">Radio</dd> <dt>surface</dt> <dd class="terreno">Tipo de terreno</dd> </dl> <h3>createObject</h3> <p>Crear un objeto. Se llamara al callback cuando se haya creado correctamente</p> <h4>Parámetros:</h4> <dl> <dt>x</dt> <dd class="numerico">Coordenada X</dd> <dt>y</dt> <dd class="numerico">Coordenada Y</dd> <dt>speed_x</dt> <dd class="numerico">Velocidad inicial del objeto en coordenada X</dd> <dt>speed_y</dt> <dd class="nuerico">Velocidad inicial del objeto en coordenada Y</dd> <dt>radius</dt> <dd class="numerico">Radio del objeto</dd> <dt>archetype_url</dt> <dd class="url">URL del arquetipo del objeto</dd> <dt>callback</dt> <dd class="callback">callback</dd> </dl> <h3>destroyObject</h3> <p>Destruir un objeto.</p> <h4>Parámetros:</h4> <dl> <dt>object</dt> <dd class="objeto">Objeto</dd> </dl> <h3>setRenderer</h3> <h4>Parámetros:</h4> <dl> <dt>renderer</dt> <dd class="Renderer">Establecer renderizador</dd> </dl> </section> <?php include "../footer.php"; ?> </body> <file_sep>/src/server/WorldObject.php <?php class WorldObject { public $entity = "object"; public $id; public $archetype_url; public $radius; public $x; public $y; public $speed_x; public $speed_y; private $owner; public $current_sprite; public $attribs; private static $object_last_id = 0; public function __construct($msg, $conn) { $this-> id = ++WorldObject::$object_last_id; $this-> request_id = $msg-> request_id; $this-> x = $msg-> x; $this-> y = $msg-> y; $this-> radius = $msg-> radius; $this-> speed_x = $msg-> speed_x; $this-> speed_y = $msg-> speed_y; if (isset ($msg-> archetype_url)) { $this-> archetype_url = $msg-> archetype_url; } $this-> owner = $conn; } public function getOwner () { return $this-> owner; } } <file_sep>/juego_allosaurus.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>μ-κosmos: Juego Allosaurus</title> <link rel="stylesheet" type="text/css" href="shared.css" /> <link rel="stylesheet" type="text/css" href="juegos.css" /> <script type="application/javascript" src="config.js"></script> <script type="application/javascript" src="jquery-3.1.1.min.js"></script> <script type="application/javascript" src="src/RemoteArea.js"></script> <script type="application/javascript" src="src/ObjectUpdater.js"></script> <script type="application/javascript" src="src/CanvasRenderer.js"></script> <script type="application/javascript" src="src/Surface.js"></script> <script type="application/javascript" src="src/TileFactory.js"></script> <script type="application/javascript" src="src/ResourceHandler.js"></script> <script type="application/javascript" src="src/CollisionChecker.js"></script> <script type="application/javascript" src="juego_allosaurus.js"></script> <script src="jquery-3.1.1.min.js"></script> </head> <body> <?php include "nav.php"; ?> <section id="game_container"> </section> <?php include "footer.php"; ?> </body> <file_sep>/src/server/WorldGenerator.php <?php require_once "WorldServer.php"; require_once "Surface.php"; const MIN_NUM_ISLANDS = 28; const MAX_NUM_ISLANDS = 40; const MIN_RADIUS_ISLAND = 8; const MAX_RADIUS_ISLAND = 16; const MIN_RECURSION = 0; const MAX_RECURSION = 8; class WorldGenerator { public static function generateIslands ($width, $height) { $world = new WorldServer ($width, $height); $numIslands = rand (MIN_NUM_ISLANDS, MAX_NUM_ISLANDS); for ($i = 0; $i < $numIslands; $i++) { $radius = rand (MIN_RADIUS_ISLAND, MAX_RADIUS_ISLAND); $x = rand ($radius, $width-$radius); $y = rand ($radius, $height-$radius); $world-> setSurfaceCircle ($x, $y, $radius, SURFACE_GRASS); } WorldGenerator::makeSandBorders($world); return $world; } private static function makeSandBorders ($world) { for ($x=1; $x < ($world->width)-1; $x++) { for ($y=1; $y < ($world->height)-1; $y++) { $surface = $world-> getSurfaceAt ($x, $y); if ($surface == SURFACE_GRASS && WorldGenerator::isWaterAround ($world, $x, $y)) { $world-> setSurfaceAt ($x, $y, SURFACE_SAND); } } } } private static function isWaterAround ($world, $x, $y) { return ( ($world-> getSurfaceAt($x-1, $y) == SURFACE_WATER) ||($world-> getSurfaceAt($x-1, $y) == SURFACE_WATER) ||($world-> getSurfaceAt($x+1, $y) == SURFACE_WATER) ||($world-> getSurfaceAt($x, $y-1) == SURFACE_WATER) ||($world-> getSurfaceAt($x, $y+1) == SURFACE_WATER) ); } } <file_sep>/src/server/SurfaceRect.php <?php class SurfaceRect { public $entity = "surface"; public $left; public $top; public $right; public $bottom; public $data; public function __construct ($left, $top, $right, $bottom, $data) { $this-> left = $left; $this-> top = $top; $this-> right = $right; $this-> bottom = $bottom; $this-> data = $data; } } <file_sep>/src/server/config.php <?php const SERVER_PORT = 443; ?> <file_sep>/desarrolladores.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>μ-κosmos: Información para desarrolladores</title> <link rel="stylesheet" type="text/css" href="shared.css" /> <link rel="stylesheet" type="text/css" href="desarrolladores.css" /> <script src="jquery-3.1.1.min.js"></script> </head> <body> <?php include "nav.php"; ?> <section id="desarrolladores_section"> <h2>Introducción</h2> <p>μ-κosmos permite a desarrolladores crear juegos e integrarlos en el mundo virtual compartido. Para ello se provee un conjunto de archivos fuente JavaScript que pueden utilizarse como base para el juego. Estos archivos proveen funcionalidades comunes a todos los juegos, como el renderizado, movimiento de personajes, y la comuniación asincrónica con el servidor.</p> <p>Además, en este documento se detallan los mensajes que el servidor puede enviar y recibir. Con esta información es posible desarrollar otras implementaciones diferentes, y aún asi mantener la compatibilidad.</p> <h2>Arquitectura</h2> <p>μ-κosmos utiliza una arquitectura cliente-servidor, donde el servidor se encarga de sincronizar el terreno y la posicion de los objetos, y los clientes que se encargan de la lógica del juego, de la interacción con el usuario, y la presentación visual (renderizado).</p> <p>El objetivo es soportar la mayor cantidad de clientes posibles, por lo que se ha intentado quitar responsabilidades al servidor y transferirlas a los clientes, para de esta manera reducir la carga del servidor. Por esta razón son los clientes los responsables de calcular la posición de los objetos en movimiento y detectar colisiones.</p> <h2>Tecnologías utilizadas</h2> <p>Para la comunicación entre los clientes y el servidor se utiliza la tecnología <a href="https://developer.mozilla.org/es/docs/Web/API/WebSocket">WebSocket</a> por lo que es necesario utilizar un navegador actualizado.</p> <p>Para el renderizado se utiliza el elemento <a href="https://developer.mozilla.org/es/docs/Web/HTML/Canvas">Canvas</a> de HTML 5.<p> <p>Los recursos externos como <em>sprites</em> se cargan mediante Ajax, utilizando la librería <a href="https://jquery.com/">jQuery</a>.</p> <h2>Especificacion de Mensajes</h2> <p>El formato de los mensajes que utilizan el cliente y el servidor para comunicarse esta especificado en <a href="/doc/mensajes.php">Referencia de mensajes cliente-servidor</a> <h2>Librería Javascript</h2> <p>Las librerías javascript de μ-κosmos proveen funcionalidades comunes a multiples juegos, como el renderizado, movimiento de personajes, y la comuniación asincrónica con el servidor.</p> <p>La documentación de referencia para cada una de las clases se encuentra en los enlaces a continuación</p> <ul> <li><a href="doc/RemoteArea.php">RemoteArea</a></li> <li><a href="doc/CanvasRenderer.php">CanvasRenderer</a></li> <li><a href="doc/Surface.php">Surface</a></li> <li><a href="doc/CollisionChecker.php">CollisionChecker</a></li> <li><a href="doc/ObjectUpdater.php">ObjectUpdater</a></li> <li><a href="doc/ResourceHandler.php">ResourceHandler</a></li> </ul> </section> <?php include "footer.php"; ?> </body> <file_sep>/src/server/Controller.php <?php use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; /* Esta clase tiene la funcion de recibir los mensajes enviados por los clientes y hacer las llamadas correspondientes en los objetos */ class Controller implements MessageComponentInterface { private $messageHandlers; private $worldServer; public function __construct () { $this-> messageHandlers = [ "surface" => [ "get" => "onMsgSurfaceGet", "set" => "onMsgSurfaceSet", "subscribe" => "onMsgSurfaceSuscribe" ], "object" => [ "create" => "onMsgObjectCreate", "subscribe" => "onMsgObjectSuscribe", "update status" => "onMsgObjectUpdate", "destroy" => "OnMsgObjectDestroy" ] ]; echo "Servidor iniciado\n"; } private function onMsgSurfaceGet ($conn, $msg) { if (isset ($msg->x)) { $send = $this-> worldServer-> getSurfaceAt($msg->x, $msg->y); } elseif (isset ($msg-> left)) { $send = $this-> worldServer-> getSurfaceRect($msg->left, $msg->top, $msg->right, $msg->bottom); } else { $send = $this-> worldServer-> getMap(); } $this-> sendMessage ($conn, $send); } private function sendMessage ($conn, $msg) { $conn-> send (json_encode($msg)); } private function onMsgSurfaceSet ($conn, $msg) { echo "Recibido mensaje setSurface\n"; if (isset ($msg-> shape)) { switch ($msg-> shape) { case "rectangle": $this-> worldServer-> setSurfaceRect ($msg->left, $msg->top, $msg->right, $msg->bottom, chr ((int) $msg->surface)); break; case "circle": $this-> worldServer-> setSurfaceCircle ($msg->x, $msg->y, $msg->radius, chr ((int) $msg->surface)); break; } } else { $this-> worldServer-> setSurfaceAt ($msg->x, $msg->y, chr((int) $msg->surface)); } } private function onMsgSurfaceSuscribe($conn, $msg) { $this-> worldServer-> subscribeToSurface ($msg-> left, $msg-> top, $msg-> right, $msg-> bottom, $conn); } private function onMsgObjectCreate ($conn, $msg) { $this-> worldServer-> createObject ($msg, $conn); } private function onMsgObjectSuscribe($conn, $msg) { $this-> worldServer-> subscribeToObjects ($msg-> left, $msg-> top, $msg-> right, $msg-> bottom, $conn); } private function onMsgObjectUpdate ($conn, $msg) { $this-> worldServer-> updateObject ($msg, $conn); } private function onMsgObjectDestroy ($conn, $msg) { $this-> worldServer-> destroyObject ($msg, $conn); } public function onOpen (ConnectionInterface $conn) { echo "Usuario conectado\n"; } public function onMessage (ConnectionInterface $conn, $msgText) { $msg = json_decode ($msgText); if (isset ($this-> messageHandlers[$msg->entity][$msg->action])) { $methodName = $this-> messageHandlers[$msg->entity][$msg->action]; $this-> $methodName ($conn, $msg); } else { echo "No se ha encontrado un handler para procesar el mensaje recibido\n"; } } public function onClose (ConnectionInterface $conn) { echo "Usuario desconectado\n"; $this-> worldServer-> unsubscribeToObjects ($conn); $this-> worldServer-> unsubscribeToSurface ($conn); $this-> worldServer-> removeObjectsByOwner ($conn); } public function onError (ConnectionInterface $conn, \Exception $e) { echo "Error: {$e->getMessage()}\n"; $this-> worldServer-> unsubscribeToSurface ($conn); $conn->close(); } public function setWorldServer ($worldServer) { $this-> worldServer = $worldServer; } } <file_sep>/index.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>μ-κosmos</title> <link rel="stylesheet" type="text/css" href="shared.css" /> <script src="jquery-3.1.1.min.js"></script> </head> <body> <?php include "nav.php"; ?> <section id="sectionJugar"> <a href="/minijuegos.php"> <div id="preview">Empezar a jugar!</div> </a> <p>Un mundo totalmente dinámico con multiples mini-juegos desarrollandose al mismo tiempo.</p> <p>En este mundo se crean y destruyen todo el tiempo personajes y objetos, los cuales pueden interactuar entre si, y con el terreno.</p> <p>El terreno esta en constante cambio como consecuencia de la actividad de los habitantes. Un bosque puede convertirse en desierto si se talan sus arboles, un desierto puede convertirse en ciudad si se construyen edificios, y una ciudad puede desaparecer tras una explosión nuclear.</p> </section> <?php include "footer.php"; ?> </body> <file_sep>/doc/ResourceHandler.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>Clase ResourceHandler: μ-κosmos</title> <link rel="stylesheet" type="text/css" href="/shared.css" /> <link rel="stylesheet" type="text/css" href="/desarrolladores.css" /> <script src="/jquery-3.1.1.min.js"></script> </head> <body> <?php include "../nav.php"; ?> <section id="desarrolladores_section"> <h1>Clase ResourceHandler</h1> <p>La clase ResourceHandler es la encargada de cargar y gestionar los recursos externos como imagenes y definiciones de arquetipos</p> <p>Una instancia de esta clase es creada automáticamente por RemoteArea, y puede accederse a través de la propiedad resourceHandler del objeto RemoteArea</p> <code> var area = new RemoteArea (...);<br> area.resourceHandler.preloadArchetype (...); </code> <h2>Métodos de clase ResourceHandler</h2> <h3>preloadArchetype</h3> <p>Pre-cargar arquetipo</p> <h4>Parámetros:</h4> <dl> <dt>url</dt> <dd class="url">URL del arquetipo</dd> </dl> </section> <?php include "../footer.php"; ?> </body> <file_sep>/propuesta-integrador/wireframe.js var init = function () { showTab('Jugar'); } var showElement = function (id) { document.getElementById(id).style.display = "block"; } var hideElement = function (id) { document.getElementById(id).style.display = "none"; } var tabs = [ "sectionJugar", "sectionNoticias", "sectionComoJugar", "sectionDesarrolladores", "sectionMiPerfil" ]; var showTab = function (tab) { hideTabs(); showElement("section" + tab); } var hideTabs = function () { tabs.forEach(function (tab) { hideElement(tab); }); } window.onload = init; <file_sep>/src/server/WorldServer.php <?php require_once "SurfaceRect.php"; require_once "Subscription.php"; require_once "WorldObject.php"; require_once "DestroyObjectMessage.php"; require_once "ObjectControl.php"; class WorldServer { public $map; public $width; public $height; private $surfaceSubscriptors = array(); private $objectSubscriptors = array(); private $objects = null; private $objectsById = array(); private $objectsByOwner = null; public function __construct ($width, $height) { $this-> width = $width; $this-> height = $height; $this-> map = str_repeat (chr(0), $width*$height); $this-> objects = new SplObjectStorage(); $this-> objectsByOwner = new SplObjectStorage(); } public static function loadFile ($filename) { $worldserver = new WorldServer (1, 1); $worldserver-> load ($filename); return $worldserver; } public function getMap () { return $this-> getSurfaceRect (0, 0, $this-> width -1, $this-> height -1); } public function getSurfaceAt ($x, $y) { return $this-> map [($x* $this-> width) + $y]; } public function getSurfaceRect ($left, $top, $right, $bottom) { $data = array(); for ($x=$left; $x<=$right; $x++) { $data[] = $this-> stringToByteArray (substr ($this->map, ($x * $this->width) + $top, 1+$bottom-$top)); } return new SurfaceRect ($left, $top, $right, $bottom, $data); } private function stringToByteArray ($str) { $arr = array(); $length = strlen ($str); for ($index = 0; $index < $length; $index++) { $arr[$index] = ord($str[$index]); } return $arr; } public function setSurfaceAt ($x, $y, $surface) { $this-> map [$x* $this-> width + $y] = $surface; $updatedRect = ($this-> getSurfaceRect ($x, $y, $x, $y)); $this-> notifySurfaceChange ($updatedRect); } public function setSurfaceRect ($left, $top, $right, $bottom, $surface) { for ($x=$left; $x<=$right; $x++) { for ($y=$top; $y<=$bottom; $y++) { $this-> map [$x* $this-> width + $y] = $surface; } } $updatedRect = ($this-> getSurfaceRect ($left, $top, $right, $bottom)); $this-> notifySurfaceChange ($updatedRect); } public function setSurfaceCircle ($x, $y, $radius, $surface) { for ($xt = $x-$radius; $xt <= ($x+$radius); $xt++) { $hip2 = pow($radius, 2); $b2 = pow (($x-$xt), 2); $yLimit = (int) (sqrt ($hip2 - $b2)); for ($yt = $y-$yLimit; $yt <= ($y+$yLimit); $yt++) { $this-> map [(int) (($xt* $this-> width) + $yt)] = $surface; } } $updatedRect = $this-> getSurfaceRect (($x-$radius), ($y-$radius), ($x+$radius), ($y+$radius)); $this-> notifySurfaceChange ($updatedRect); } public function subscribeToSurface ($left, $top, $right, $bottom, $conn) { echo "Cliente subscripto a cambios de superficie.\n"; $this-> unsubscribeToSurface ($conn); $this-> surfaceSubscriptors[] = new Subscription ($left, $top, $right, $bottom, $conn); } public function unsubscribeToSurface ($conn) { // FIXME: esto deberia estar sincronizado como seccion critica $num_subscriptors = count($this-> surfaceSubscriptors); for ($i = 0; $i<$num_subscriptors; $i++) { if ($conn = $this-> surfaceSubscriptors[$i]-> conn) { array_slice ($this-> surfaceSubscriptors, $i, 1); } } } public function notifySurfaceChange ($surfaceRect) { $json = null; foreach ($this->surfaceSubscriptors as $subscriptor) { if (WorldServer::rectsIntersect ($subscriptor, $surfaceRect)) { if ($json == null) { $json = json_encode ($surfaceRect); } $subscriptor-> send ($json); } } } private static function rectsIntersect ($rect1, $rect2) { if ($rect1->left <= $rect2->left) { $leftMost = $rect1; $rightMost = $rect2; } else { $leftMost = $rect2; $rightMost = $rect1; } if ($rect1->top <= $rect2->top) { $upperMost = $rect1; $lowerMost = $rect2; } else { $upperMost = $rect2; $lowerMost = $rect1; } return ($rightMost->left <= $leftMost->right) && ($lowerMost->top <= $upperMost->bottom); } public function subscribeToObjects ($left, $top, $right, $bottom, $conn) { echo "Cliente subscripto a objetos.\n"; $this-> unsubscribeToObjects ($conn); $subscription = new Subscription ($left, $top, $right, $bottom, $conn); $this-> objectSubscriptors[] = $subscription; $this-> sendCurrentObjects ($subscription); } public function unsubscribeToObjects ($conn) { // FIXME: esto deberia estar sincronizado como seccion critica $num_subscriptors = count($this-> objectSubscriptors); for ($i = 0; $i<$num_subscriptors; $i++) { if ($conn = $this-> objectSubscriptors[$i]-> conn) { array_slice ($this-> objectSubscriptors, $i, 1); } } } private function sendCurrentObjects ($subscriptor) { foreach ($this-> objects as $object) { if (WorldServer::objectInsideBounds ($object, $subscriptor)) { $json = json_encode ($object); $subscriptor-> conn-> send ($json); } } } public static function objectInsideBounds ($object, $rect) { return true; //FIXME } public function createObject ($msg, $conn) { $object = new WorldObject($msg, $conn); $this-> objects-> attach ($object); $this-> objectsById [$object-> id] = $object; if ($this-> objectsByOwner-> offsetExists ($conn)) { $ownedObjects = $this-> objectsByOwner-> offsetGet ($conn); $ownedObjects-> attach ($object); } else { $ownedObjects = new SplObjectStorage(); $ownedObjects-> attach ($object); $this-> objectsByOwner-> attach ($conn, $ownedObjects); } $this-> notifyObjectStatus ($object); $this-> giveObjectControl ($object, $msg-> request_id, $conn); echo "Objeto creado [id: $object->id]\n"; } private function notifyObjectStatus ($object) { $json = json_encode ($object); foreach ($this-> objectSubscriptors as $subscriptor) { if (WorldServer::objectInsideBounds ($object, $subscriptor)) { $subscriptor-> send ($json); } } } private function giveObjectControl ($object, $req_id, $conn) { $msg = new ObjectControl ($object-> id, $req_id, $conn); $json = json_encode ($msg); $conn-> send ($json); } public function updateObject ($msg, $conn) { if (isset ($this-> objectsById [$msg-> id])) { $object = $this-> objectsById [$msg-> id]; if (isset ($msg-> x)) { $object-> x = $msg-> x; } if (isset ($msg-> y)) { $object-> y = $msg-> y; } if (isset ($msg-> speed_x)) { $object-> speed_x = $msg-> speed_x; } if (isset ($msg-> speed_y)) { $object-> speed_y = $msg-> speed_y; } if (isset ($msg-> current_sprite)) { $object-> current_sprite = $msg-> current_sprite; } $this-> notifyObjectStatus ($object); } } public function destroyObject ($msg, $conn) { if (isset ($this-> objectsById[$msg-> id])) { echo "Objeto destruido [id: $msg->id]\n"; $this-> removeObject ($this-> objectsById[$msg-> id], $conn); } } public function removeObject ($object, $conn) { $this-> objects-> offsetUnset ($object); unset ($this-> objectsById [$object->id]); $ownedObjects = $this-> objectsByOwner-> offsetGet ($conn); $ownedObjects-> offsetUnset ($object); $this-> notifyObjectDestruction ($object); } public function removeObjectsByOwner ($conn) { $ownedObjects = $this-> objectsByOwner-> offsetGet ($conn); foreach ($ownedObjects as $object) { $this-> objects-> offsetUnset ($object); $this-> notifyObjectDestruction ($object); } $this-> objectsByOwner-> offsetUnset ($conn); } public function notifyObjectDestruction ($object) { $msg = new DestroyObjectMessage ($object); $json = json_encode ($msg); foreach ($this-> objectSubscriptors as $subscriptor) { if (WorldServer::objectInsideBounds ($object, $subscriptor)) { $subscriptor-> send ($json); } } } public function save ($filename) { $json = json_encode ($this); file_put_contents ($filename, $json); } public function load ($filename) { $json = file_get_contents ($filename); $loaded = json_decode ($json); $this-> width = $loaded-> width; $this-> height = $loaded-> height; $this-> map = $loaded-> map; } } <file_sep>/doc/ObjectUpdater.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>Clase ObjectUpdater: μ-κosmos</title> <link rel="stylesheet" type="text/css" href="/shared.css" /> <link rel="stylesheet" type="text/css" href="/desarrolladores.css" /> <script src="/jquery-3.1.1.min.js"></script> </head> <body> <?php include "../nav.php"; ?> <section id="desarrolladores_section"> <h1>Clase ObjectUpdater</h1> <p>La clase ObjectUpdater es la encargada de actualizar la posición de los objetos en movimiento, y enviar estas actualizaciones al servidor.</p> <p>Una instancia de ObjectUpdater se crea automáticamente para cada objeto gestionado por RemoteArea, y puede accederse mediante la propiedad updater</p> <h4>Ejemplo</h4> <code> var player = remote_area.objects[3];<br> player.speed_x = 2.5;<br> player.updater.update();<br> </code> <h2>Métodos de clase ObjectUpdater</h2> <h3>update</h3> <p>Forzar la actualización</p> </section> <?php include "../footer.php"; ?> </body> <file_sep>/src/Surface.js /* * Tipos de superficie * 0-15 Agua * 16-31 Barro * 32-47 Tierra con vegetacion * 48-63 Tierra arida * 64-95 Roca * 96-127 Construido por humanos * 128-143 Hielo * 144-159 Metal * 160-175 * 176-191 * 192-207 * 208-223 * 224-239 Gaseoso * 240-255 Extranio */ Surface = { WATER: 0, SHALLOW: 6, MUD: 16, QUICKSAND: 20, GRASS: 32, EARTH: 48, SAND: 49, RED_EARTH: 50, ROCK: 64, MOUNTAIN: 65, BUILDING: 96, COBBLE: 97, BRICK: 98, ICE: 128, SNOW: 129, METAL: 144, GOLD: 145, AIR: 224, CLOUD: 225, VOID: 255 }; SurfaceColor = []; SurfaceColor[Surface.WATER]="#44f"; SurfaceColor[Surface.SHALLOW]="#48f"; SurfaceColor[Surface.MUD]="#864"; SurfaceColor[Surface.QUICKSAND]="#cc8"; SurfaceColor[Surface.GRASS]="#4f4"; SurfaceColor[Surface.EARTH]="#621"; SurfaceColor[Surface.SAND]="#ff6"; SurfaceColor[Surface.RED_EARTH]="#a32"; SurfaceColor[Surface.ROCK]="#866"; SurfaceColor[Surface.MOUNTAIN]="#666"; SurfaceColor[Surface.BUILDING]="#777"; SurfaceColor[Surface.COBBLE]="#555"; SurfaceColor[Surface.BRICK]="#a40"; SurfaceColor[Surface.ICE]="#ccf"; SurfaceColor[Surface.SNOW]="#eef"; SurfaceColor[Surface.METAL]="#888"; SurfaceColor[Surface.GOLD]="#fe0"; SurfaceColor[Surface.AIR]="#0cf"; SurfaceColor[Surface.CLOUD]="#eef"; SurfaceColor[Surface.VOID]="#000"; Surface.isSolid = function (surface) { return (surface>31 && surface<224); }<file_sep>/doc/mensajes.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>Mensajes cliente-servidor μ-κosmos</title> <link rel="stylesheet" type="text/css" href="/shared.css" /> <link rel="stylesheet" type="text/css" href="/desarrolladores.css" /> <script src="/jquery-3.1.1.min.js"></script> </head> <body> <?php include "../nav.php"; ?> <section id="desarrolladores_section"> <h1>Mensajes cliente-servidor</h1> <p>Para la comunicación entre los clientes y el servidor se utiliza el envío de mensajes asíncronos mediante la tecnología <a href="https://developer.mozilla.org/es/docs/Web/API/WebSocket">WebSocket</a></p> <p>El desarrollador que utilice las librerías javascript de μ-κosmos no necesita conocer estos mensajes, ya que dichas librerías abstraen este trabajo.</p> <p>Conocer el formato de estos mensajes es necesario para desarrollar implementaciones alternativas, que no utilicen las librerías javascript.</p> <h2>Mensajes enviados por el cliente</h2> <h3>Surface Get</h3> <p>Solicita al servidor datos del terreno</p> <dl> <dt>entity</dt> <dd>"surface"</dd> <dt>action</dt> <dd>"get"</dd> </dl> <h3>Surface Subscribe</h3> <p>Solicita subscripción a un area rectangular. Esto significa que el servidor deberá notificarle cuando se produzcan cambios en el terreno dentro de dicha area.</p> <dl> <dt>entity</dt> <dd>"surface"</dd> <dt>action</dt> <dd>"subscribe"</dd> <dt>left</dt> <dd class="numerico">Valor numérico. Límite izquierdo.</dd> <dt>top</dt> <dd class="numerico">Valor numérico. Límite superior.</dd> <dt>right</dt> <dd class="numerico">Valor numérico. Límite derecho.</dd> <dt>bottom</dt> <dd class="numerico">Valor numérico. Límite inferior.</dd> </dl> <h3>Surface Set (X, Y)</h3> <p>Solicita reemplazar el terreno en unas coordenadas dadas.</p> <dl> <dt>entity</dt> <dd>"surface"</dd> <dt>action</dt> <dd>"set"</dd> <dt>x</dt> <dd class="numerico">Valor numérico. Coordenada en el eje X (longitud).</dd> <dt>y</dt> <dd class="numerico">Valor numérico. Coordenada en el eje Y (latitud)</dd> <dt>surface</dt> <dd class="terreno">Tipo de terreno.</dd> </dl> <h3>Surface Set (Rectangle)</h3> <p>Solicita reemplazar el terreno en un area rectangular.</p> <dl> <dt>entity</dt> <dd>"surface"</dd> <dt>action</dt> <dd>"set"</dd> <dt>shape</dt> <dd>"rectangle"</dd> <dt>left</dt> <dd class="numerico">Valor numérico. Límite izquierdo.</dd> <dt>top</dt> <dd class="numerico">Valor numérico. Límite superior.</dd> <dt>right</dt> <dd class="numerico">Valor numérico. Límite derecho.</dd> <dt>bottom</dt> <dd class="numerico">Valor numérico. Límite inferior.</dd> <dt>surface</dt> <dd class="terreno">Tipo de terreno.</dd> </dl> <h3>Surface Set (Circle)</h3> <p>Solicita reemplazar el terreno en un area rectangular.</p> <dl> <dt>entity</dt> <dd>"surface"</dd> <dt>action</dt> <dd>"set"</dd> <dt>shape</dt> <dd>"circle"</dd> <dt>x</dt> <dd class="numerico">Valor numérico. Coordenada en el eje X (longitud).</dd> <dt>y</dt> <dd class="numerico">Valor numérico. Coordenada en el eje Y (latitud).</dd> <dt>radius</dt> <dd class="numerico">Valor numérico. Radio del círculo.</dd> <dt>surface</dt> <dd class="terreno">Tipo de terreno.</dd> </dl> <h3>Object Subscribe</h3> <p>Solicita subscripción a un area rectangular. Esto significa que el servidor deberá notificarle cuando se produzcan cambios en objetos dentro de dicha area.</p> <dl> <dt>entity</dt> <dd>"object"</dd> <dt>action</dt> <dd>"subscribe"</dd> <dt>left</dt> <dd class="numerico">Valor numérico. Límite izquierdo.</dd> <dt>top</dt> <dd class="numerico">Valor numérico. Límite superior.</dd> <dt>right</dt> <dd class="numerico">Valor numérico. Límite derecho.</dd> <dt>bottom</dt> <dd class="numerico">Valor numérico. Límite inferior.</dd> </dl> <h3>Object Create</h3> <p>Solicita la creación de un objeto.</p> <dl> <dt>entity</dt> <dd>"object"</dd> <dt>action</dt> <dd>"create"</dd> <dt>request_id</dt> <dd class="entero">Valor entero. Identificador de la solicitud.</dd> <dt>archetype_url</dt> <dd class="url">URL</dd> <dt>radius</dt> <dd class="numerico">Valor numérico. Radio que se aproxime al tamaño del objeto.</dd> <dt>x</dt> <dd class="numerico">Valor numérico. Coordenada en eje X (longitud).</dd> <dt>y</dt> <dd class="numerico">Valor numérico. Coordenada en eje Y (latitud).</dd> <dt>speed_x</dt> <dd class="numerico">Valor numérico. Velocidad hacia eje X positivo (derecha).</dd> <dt>speed_y</dt> <dd class="numerico">Valor numérico. Velocidad hacia eje Y positivo (abajo).</dd> </dl> <h3>Object Update Status</h3> <p>Informa sobre el estado de un objeto bajo el control del cliente.</p> <dl> <dt>entity</dt> <dd>"object"</dd> <dt>action</dt> <dd>"update status"</dd> <dt>x</dt> <dd class="numerico">Valor numérico. Coordenada en eje X (longitud).</dd> <dt>y</dt> <dd class="numerico">Valor numérico. Coordenada en eje Y (latitud).</dd> <dt>speed_x</dt> <dd class="numerico">Valor numérico. Velocidad hacia eje X positivo (derecha).</dd> <dt>speed_y</dt> <dd class="numerico">Valor numérico. Velocidad hacia eje Y positivo (abajo).</dd> <dt>current_sprite</dt> <dd class="texto">Texto. Nombre del sprite.</dd> </dl> <h3>Object Destroy</h3> <p>Informa sobre la destrucción de un objeto bajo el control del cliente.</p> <dl> <dt>entity</dt> <dd>"object"</dd> <dt>action</dt> <dd>"destroy"</dd> <dt>id</dt> <dd class="entero">Valor entero. Identificador del objeto<dd> </dl> <h2>Mensajes enviados por el servidor</h2> <h3>Surface</h3> <p>Informa sobre el estado del terreno en un area rectangular</p> <dl> <dt>entity</dt> <dd>"surface"</dd> <dt>left</dt> <dd class="numerico">Valor numérico. Límite izquierdo.</dd> <dt>top</dt> <dd class="numerico">Valor numérico. Límite superior.</dd> <dt>right</dt> <dd class="numerico">Valor numérico. Límite derecho.</dd> <dt>bottom</dt> <dd class="numerico">Valor numérico. Límite inferior.</dd> <dt>data</dt> <dd class="terreno">Tipo de terreno (array).</dd> </dl> <h3>Object</h3> <p>Informa sobre el estado de un objeto.</p> <dl> <dt>entity</dt> <dd>"object"</dd> <dt>object_id</dt> <dd class="entero">Valor entero</dd> <dt>archetype_url</dt> <dd class="url">URL</dd> <dt>radius</dt> <dd class="numerico">Valor numérico. Radio que se aproxime al tamaño del objeto.</dd> <dt>x</dt> <dd class="numerico">Valor numérico. Coordenada en eje X (longitud).</dd> <dt>y</dt> <dd class="numerico">Valor numérico. Coordenada en eje Y (latitud).</dd> <dt>speed_x</dt> <dd class="numerico">Valor numérico. Velocidad hacia eje X positivo (derecha).</dd> <dt>speed_y</dt> <dd class="numerico">Valor numérico. Velocidad hacia eje Y positivo (abajo).</dd> </dl> <h3>Object Destroy</h3> <p>Informa sobre la destrucción de un objeto</p> <dl> <dt>entity</dt> <dd>"object"</dd> <dt>action</dt> <dd>"destroy"</dd> <dt>id</dt> <dd class="numerico">Valor numérico. Identificador del objeto.</dd> </dl> <h3>Object Grant Control</h3> <p>Informa a un cliente que posee el control sobre un objeto. Esto significa que el cliente tiene permiso para cambiar el estado del objeto.</p> <dl> <dt>entity</dt> <dd>"object"</dd> <dt>action</dt> <dd>"grant control"</dd> <dt>object_id</dt> <dd class="numerico">Valor numérico. Identificador del objeto.</dd> <dt>request_id</dt> <dd class="numerico">Valor numérico. Identificador de la solicitud de creación del objeto.</dd> </dl> </section> <?php include "../footer.php"; ?> </body> <file_sep>/minijuegos.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>μ-κosmos: MiniJuegos</title> <link rel="stylesheet" type="text/css" href="shared.css" /> <link rel="stylesheet" type="text/css" href="minijuegos.css" /> <script src="jquery-3.1.1.min.js"></script> </head> <body> <?php include "nav.php"; ?> <section id="minijuegos"> <article class="minigame"> <h2>Un detective en apuros</h2> <img src="juego_detective.png"> <p>Tu misión es encontrar las joyas robadas. ¡Pero cuidado! Otros detectives estan buscandote para asesinarte.</p> <h3>Teclas</h3> <stroke>Flecha Arriba:</stroke> Caminar hacia arriba<br> <stroke>Flecha Abajo:</stroke> Caminar hacia abajo<br> <stroke>Flecha izquierda:</stroke> Caminar hacia la izquierda<br> <stroke>Flecha derecha:</stroke> Caminar hacia la derecha<br> <stroke>Barra espaciadora:</stroke> Disparar<br> <stroke>B:</stroke> Poner bomba<br> <a class="playButton" href="juego_detective.php">Jugar!</a> </article> <article class="minigame"> <h2>Comer Prehistórico</h2> <img src="juego_allosaurus.png"> <p>Come todo a tu paso</p> <h3>Teclas</h3> <stroke>Flecha Arriba:</stroke> Correr hacia arriba<br> <stroke>Flecha Abajo:</stroke> Correr hacia abajo<br> <stroke>Flecha izquierda:</stroke> Correr hacia la izquierda<br> <stroke>Flecha derecha:</stroke> Correr hacia la derecha<br> <a class="playButton" href="juego_allosaurus.php">Jugar!</a> </article> </section> <?php include "footer.php"; ?> </body> <file_sep>/global.js window.onload = function() { area = new RemoteArea (CONFIG_SERVER_ADDRESS); renderer = new CanvasRenderer (area); renderer.drawImages = false; renderer.setViewSize([128, 128]); renderer.setRenderSize([600, 600]); var container = document.getElementById ('global_map_section'); window.setTimeout (function(){ renderer.render (container, 20); initClickHandler(); }, 1000); initSurfaceSelect(); } initSurfaceSelect = function () { var select = document.querySelector ("select[name=surface_type]"); for (surf in Surface) { if ( Surface.hasOwnProperty (surf) && typeof (Surface[surf]) != "function" ) { var opt = document.createElement ("OPTION"); opt.innerText = surf; opt.value = Surface[surf]; select.appendChild (opt); } } select.onchange = updateSurfaceExample; updateSurfaceExample (); } updateSurfaceExample = function () { var srf = document.querySelector ("select[name=surface_type]").value; var color = SurfaceColor[srf] document.getElementById("surface_example").style.background = color; } initClickHandler = function () { var canvas = document.querySelector("#global_map_section canvas"); var rect = canvas.getBoundingClientRect() canvas.addEventListener ("click", function (event) { var click_x = event.pageX-rect.left; var click_y = event.pageY-rect.top; var tile_x = Math.floor((click_x / area.renderer.tileScale[0]) - area.renderer.viewOrigin[0]); var tile_y = Math.floor((click_y / area.renderer.tileScale[1]) - area.renderer.viewOrigin[1]); changeTile (tile_x, tile_y); }); } changeTile = function (tile_x, tile_y) { var surface_type = document.querySelector ("select[name=surface_type]").value; var brush_shape = document.querySelector ("select[name=brush_shape").value; var brush_size = document.querySelector ("input[name=brush_size]").value; switch (brush_shape) { case "square": drawSquare (tile_x, tile_y, surface_type, parseInt(brush_size)); break; case "circle": drawCircle (tile_x, tile_y, surface_type, parseInt(brush_size)); break; } } drawCircle = function (x, y, surface, brush_size) { area.setSurfaceCircle (x, y, Math.floor(brush_size/2), surface); } drawSquare = function (x, y, surface, brush_size) { var left = Math.floor (x-(brush_size/2)); var top = Math.floor (y-(brush_size/2)); var right = (left + brush_size) -1; var bottom = (top + brush_size) -1; area.setSurfaceRect (left, top, right, bottom, surface); } <file_sep>/src/CollisionChecker.js CollisionChecker = function (existingObjects) { this.existingObjects = existingObjects; this.checks = []; this.rules = []; this.intervalHandler = null; this.cps = 10; //Chequeos por segundo this.start(); } CollisionChecker.prototype.addCheck = function (one, other, callback) { this.checks.push ({ one: one, other: other, callback: callback }); } CollisionChecker.prototype.addCheckByAttribute = function (object, atr_name, atr_value, callback) { var rule = { object: object, atr_name: atr_name, atr_value: atr_value, callback: callback }; this.rules.push (rule); this.generateChecksFromRule (rule); } CollisionChecker.prototype.generateChecksFromRule = function (rule) { var self = this; this.existingObjects.forEach (function (target) { if ( self.objectMatchesRule (target, rule) && (rule.object.id != target.id) ) { self.addCheck (rule.object, target, rule.callback); } }); } CollisionChecker.prototype.objectMatchesRule = function (object, rule) { return ( object.attribs && object.attribs.hasOwnProperty (rule.atr_name) && (object.attribs[rule.atr_name] == rule.atr_value) ); } CollisionChecker.prototype.notifyObjectAttributes = function (object) { var self = this; this.rules.forEach (function (rule) { if ( self.objectMatchesRule (object, rule) && rule.object != object ) { self.addCheck (rule.object, object, rule.callback); } }); } CollisionChecker.prototype.removeChecksForObject = function (object) { //FIXME: esto deberia estar sincronizado como seccion critica for (var i=0; i<this.checks.length; i++) { if ( (this.checks[i].one.id == object.id) || (this.checks[i].other.id == object.id) ) { this.checks.splice(i, 1); } } } CollisionChecker.prototype.removeCheck = function (one, other) { //FIXME: esto deberia estar sincronizado como seccion critica for (var i=0; i<this.checks.length; i++) { if (this.checks[i].one.id == one.id && this.checks[i].other.id == other.id) { this.checks.splice(i, 1); } } } CollisionChecker.prototype.checkAll = function () { var self = this; this.checks.forEach (function (record) { if (self.collide (record.one, record.other)) { record.callback (record.one, record.other); } }); } CollisionChecker.prototype.collide = function (one, another) { var min_distance = one.radius + another.radius; if ( (Math.abs (one.x - another.x) < min_distance) && (Math.abs (one.y - another.y) < min_distance) && (Math.sqrt (Math.pow (one.x - another.x, 2) + Math.pow (one.y - another.y, 2)) < min_distance) ) { return true; } else { return false; } } CollisionChecker.prototype.start = function () { var self = this; this.intervalHandler = window.setInterval (function () { self.checkAll(); }, 1000/this.cps); } CollisionChecker.prototype.stop = function () { if (this.intervalHandler != null) { window.clearInterval (this.intervalHandler); this.intervalHandler = null; } }<file_sep>/src/server/ObjectControl.php <?php class ObjectControl { public $entity = "object"; public $action = "grant control"; public $object_id; public $request_id; public function __construct ($object_id, $request_id) { $this-> object_id = $object_id; $this-> request_id = $request_id; } } <file_sep>/doc/CanvasRenderer.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>Clase CanvasRenderer: μ-κosmos</title> <link rel="stylesheet" type="text/css" href="/shared.css" /> <link rel="stylesheet" type="text/css" href="/desarrolladores.css" /> <script src="/jquery-3.1.1.min.js"></script> </head> <body> <?php include "../nav.php"; ?> <section id="desarrolladores_section"> <h1>Clase CanvasRenderer</h1> <p>La clase CanvasRenderer es la encargada de renderizar el mundo y los personajes en un objeto Canvas de HTML.</p> <h3>Constructor</h3> <h4>Parámetros:</h4> <dl> <dt>area</dt> <dd class="objeto">Objeto RemoteArea que será renderizado.</dd> </dl> <h2>Métodos de clase CanvasRenderer</h2> <h3>setZoomLevel</h3> <p>Establecer un nivel de zoom</p> <h4>Parámetros:</h4> <dl> <dt>zoomLevel</dt> <dd class="entero">Valor entero. Nivel de zoom.</dd> </dl> <h3>renderStep</h3> <h3>render</h3> <p>Crear elemento canvas y poner en container</p> <h4>Parámetros:</h4> <dl> <dt>container</dt> <dd class="">Elemento DOM HTML.</dd> <dt>maxFps</dt> <dd class="entero">Valor entero. Cuadros máximos por segundo.</dd> </dl> <h3>adjust</h3> <p>Ajustar posicion y tamaño</p> <h3>refresh</h3> <p>Actualizar imagen</p> <h3>drawSurfaceRect</h3> <p>Dibujar un area rectangular</p> <h4>Parámetros:</h4> <dl> <dt>rect</dt> <dd class="">Objeto con propiedades left, top, right y bottom</dd> </dl> <h3>drawTile</h3> <p>Dibujar un tile particular</p> <h4>Parámetros:</h4> <dl> <dt>surface</dt> <dd class="terreno">Tipo de terreno</dd> <dt>x</dt> <dd class="numerico">Coordenada X</dd> <dt>y</dt> <dd class="numerico">Coordenada Y</dd> </dl> <h3>goToPosition</h3> <p>Moverse a un punto determinado</p> <h4>Parámetros:</h4> <dl> <dt>destination</dt> <dd class="array">Destino en formato array [x, y]</dd> </dl> <h3>goTo</h3> <p>Moverse a unas coordenadas determinadas</p> <h4>Parámetros:</h4> <dl> <dt>x</dt> <dd class="numerico">Coordenada X</dd> <dt>y</dt> <dd class="numerico">Coordenada Y</dd> </dl> <h3>follow</h3> <p>Seguir a un objeto particular</p> <h4>Parámetros:</h4> <dl> <dt>target</dt> <dd class="objeto">Objeto a seguir</dd> </dl> <h3>stopFollow</h3> <p>Dejar de seguir a un objeto</p> <h3>move</h3> <p>Moverse a una ubicacion relativa </p> <h4>Parámetros:</h4> <dl> <dt>x</dt> <dd class="numerico">Coordenada X relativa</dd> <dt>y</dt> <dd class="numerico">Coordenada Y relativa</dd> </dl> <h3>setViewOrigin</h3> <p>Establecer la esquina superior izquierda de la vista en el area <h4>Parámetros:</h4> <dl> <dt>origin</dt> <dd class="array">Origen en formato array [x, y]</dd> </dl> <h3>setViewSize</h3> <p>Establecer el tamaño de la vista <h4>Parámetros:</h4> <dl> <dt>size</dt> <dd class="array">Tamaño en formato array [x, y]</dd> </dl> <h3>setRenderSize</h3> <p>Establecer el tamaño de la renderización <h4>Parámetros:</h4> <dl> <dt>size</dt> <dd class="array">Tamaño en formato array [x, y]</dd> </dl> <h3>showMessage</h3> <p>Mostrar mensaje</p> <h4>Parámetros:</h4> <dl> <dt>text</dt> <dd class="texto">Mensaje a mostrar</dd> </dl> </section> <?php include "../footer.php"; ?> </body> <file_sep>/src/server/Subscription.php <?php class Subscription { public $left; public $top; public $right; public $bottom; public $conn; public function __construct ($left, $top, $right, $bottom, $conn) { $this-> left = $left; $this-> right = $right; $this-> top = $top; $this-> bottom = $bottom; $this-> conn = $conn; } public function send ($msg) { $this-> conn-> send ($msg); } } <file_sep>/doc/CollisionChecker.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>Clase CollisionChecker: μ-κosmos</title> <link rel="stylesheet" type="text/css" href="/shared.css" /> <link rel="stylesheet" type="text/css" href="/desarrolladores.css" /> <script src="/jquery-3.1.1.min.js"></script> </head> <body> <?php include "../nav.php"; ?> <section id="desarrolladores_section"> <h1>Clase CollisionChecker</h1> <p>La clase CollisionChecker es la encarga de detectar colisiones entre objetos.</p> <p>Una instancia de esta clase es creada automáticamente por RemoteArea, y puede accederse a través de la propiedad collisionChecker del objeto RemoteArea</p> <h4>Ejemplo</h4> <code> var area = new RemoteArea (...);<br> area.collisionChecker.addCheck (...); </code> <h2>Métodos de clase CollisionChecker</h2> <h3>addCheck</h3> <p>Agregar comprobación de colisiones entre dos objetos</p> <h4>Parámetros:</h4> <dl> <dt>one</dt> <dd class="objeto">Primer objeto</dd> <dt>other</dt> <dd class="objeto">Segundo objeto</dd> <dt>callback</dt> <dd class="callback">Callback a ejecutar cuando se detecte colisión</dd> </dl> <h3>addCheckByAttribute</h3> <p>Agregar comprobación de colisiones entre un objeto y cualquiera con un atributo especifcado</p> <h4>Parámetros:</h4> <dl> <dt>object</dt> <dd class="objeto">Objeto</dd> <dt>atr_name</dt> <dd class="text">Nombre del atributo</dd> <dt>atr_value</dt> <dd>Valor del atributo</dd> <dt>callback</dt> <dd class="callback">Callback a ejecutar cuando se detecte colisión</dd> </dl> <h3>removeChecksForObject</h3> <p>Quitar todas las comprobaciones de colisión para un objeto</p> <h4>Parámetros:</h4> <dl> <dt>object</dt> <dd class="objeto">Objeto</dd> </dl> <h3>removeCheck</h3> <p>Quitar comprobación de colisiones entre dos objetos</p> <h4>Parámetros:</h4> <dl> <dt>one</dt> <dd class="objeto">Primer objeto</dd> <dt>other</dt> <dd class="objeto">Segundo objeto</dd> </dl> <h3>collide</h3> <p>Comprueba si hay colisión entre dos objetos</p> <h4>Parámetros:</h4> <dl> <dt>one</dt> <dd class="objeto">Primer objeto</dd> <dt>another</dt> <dd class="objeto">Segundo objeto</dd> </dl> <h3>stop</h3> <p>Detiene la comprobación de colisiones</p> </section> <?php include "../footer.php"; ?> </body> <file_sep>/src/TileFactory.js TileFactory = { } TileFactory.getTileColor = function (surface) { var color = 'black'; if (SurfaceColor[surface] != undefined) { color = SurfaceColor[surface]; } return color; } <file_sep>/src/CanvasRenderer.js CanvasRenderer = function (area) { this.area = area; this.viewOrigin = [0, 0]; this.viewSize = [16, 16]; this.renderSize = [300, 300]; this.tileScale = [300/16, 300/16]; this.drawingCanvas = null; this.canvasContext = null; this.mustExit = false; this.followTarget = null; this.followIntervalId = null; this.drawImages = true; this.textMessage = null; area.setRenderer (this); } /* Establecer un nivel de zoom */ CanvasRenderer.prototype.setZoomLevel = function (zoomLevel) { this.setViewSize ([20/zoomLevel, (20/zoomLevel)*(this.renderSize[1]/this.renderSize[0])]); this.adjust(); } /* Iniciar el dibujado continuo */ CanvasRenderer.prototype.startRenderLoop = function (maxFps) { this.lastStep = Date.now (); this.stepGap = 1000/maxFps; this.renderStep() } /* Detener el dibujado continuo */ CanvasRenderer.prototype.stopRenderLoop = function () { this.mustExit = true; } CanvasRenderer.prototype.renderStep = function () { var beforeRender = Date.now (); this.area.recalcObjectPositions (beforeRender); this.refresh(); var afterRender = Date.now (); var renderTime = afterRender - beforeRender; var wait = this.stepGap - renderTime; if (wait < 1) { wait = 1; } var self = this; window.setTimeout (function () { if (!self.mustExit) { self.renderStep(); } }, wait); } /* Crear elemento canvas y poner en container */ CanvasRenderer.prototype.render = function (container, maxFps) { this.drawingCanvas = document.createElement("canvas"); this.canvasContext = this.drawingCanvas.getContext ("2d"); this.adjust(); container.appendChild (this.drawingCanvas); if (maxFps == undefined) { maxFps = 60; } this.startRenderLoop (maxFps); } /* Ajustar posicion y tamanio */ CanvasRenderer.prototype.adjust = function () { this.drawingCanvas.setAttribute("width", this.renderSize[0]); this.drawingCanvas.setAttribute("height", this.renderSize[1]); this.tileScale = [ this.renderSize[0]/this.viewSize[0], this.renderSize[1]/this.viewSize[1] ]; } /* Actualizar imagen */ CanvasRenderer.prototype.refresh = function () { var self = this; /* Callback para dibujar asincronicamente */ var asyncDraw = function (rect) { debug_rect = rect; for (var x = rect.left; x <= rect.right; x++) { for (var y = rect.top; y <= rect.bottom; y++) { self.drawTile (rect.data[x-rect.left][y-rect.top], x, y); } } } this.area.execOnSurfaceRect ( Math.floor(this.viewOrigin[0]), Math.floor(this.viewOrigin[1]), Math.ceil(this.viewOrigin[0] + this.viewSize[0]), Math.ceil(this.viewOrigin[1] + this.viewSize[1]), asyncDraw ); this.drawObjects(); if (this.textMessage != null) { this.renderMessage (this.textMessage); } } /* Dibujar un area rectangular */ CanvasRenderer.prototype.drawSurfaceRect = function (rect) { for (var x = rect.left; x <= rect.right; x++) { for (var y = rect.top; y <= rect.bottom; y++) { this.drawTile (rect[x-left][y-top], x, y); } } } /* Dibujar un tile particular */ CanvasRenderer.prototype.drawTile = function (surface, x, y) { var pos = this.coordTranslate (x, y); if (pos != null) { this.canvasContext.fillStyle = TileFactory.getTileColor (surface); this.canvasContext.fillRect (pos.x, pos.y, this.tileScale[0], this.tileScale[1]); } } /* Dibujar objetos visibles */ CanvasRenderer.prototype.drawObjects = function () { var self = this; var time = Date.now(); this.area.objects.forEach (function (object) { if ( (object.x+object.radius >= self.viewOrigin[0]) && (object.x-object.radius <= self.viewOrigin[0]+self.viewSize[0]) && (object.y+object.radius >= self.viewOrigin[1]) && (object.y-object.radius <= self.viewOrigin[1]+self.viewSize[1]) ) { self.drawObject (object, time); } }); } /* Dibujar un objeto */ CanvasRenderer.prototype.drawObject = function (object, time) { if ( this.drawImages && this.area.resourceHandler.hasObjectSprite (object) && object.current_sprite ){ this.drawObjectImage (object, time); } else { this.drawObjectSimple (object); } } /* Dibujar un objeto */ CanvasRenderer.prototype.drawObjectSimple = function (object) { var drawX = (object.x - this.viewOrigin[0]) * this.tileScale[0]; var drawY = (object.y - this.viewOrigin[1]) * this.tileScale[1]; var radius = object.radius * this.tileScale[0]; this.canvasContext.beginPath(); this.canvasContext.arc(drawX, drawY, radius, 0, 6.28319); if (object.archetype && object.archetype.color){ this.canvasContext.fillStyle = object.archetype.color; } else { this.canvasContext.fillStyle = 'red'; } this.canvasContext.fill(); this.canvasContext.closePath();} /* Dibujar un objeto */ CanvasRenderer.prototype.drawObjectImage = function (object, time) { var drawX = (object.x - this.viewOrigin[0] - object.radius) * this.tileScale[0]; var drawY = (object.y - this.viewOrigin[1] - object.radius) * this.tileScale[1]; var drawWidth = 2* object.radius * this.tileScale[0]; var drawHeight = 2* object.radius * this.tileScale[1]; this.area.resourceHandler.drawObject (object, this.canvasContext, drawX, drawY, drawWidth, drawHeight, time); } /* Traducir las coordenadas del mapa a las coordenadas del canvas */ CanvasRenderer.prototype.coordTranslate = function (x, y) { var coords = { x: this.tileScale[0] * (x-this.viewOrigin[0]), y: this.tileScale[1] * (y-this.viewOrigin[1]) } if (x < 0 || y < 0 ){ return null; } return coords; } /* Moverse a un punto determinado */ CanvasRenderer.prototype.goToPosition = function (destination) { this.goTo (destination[0], destination[1]); } /* Moverse a unas coordenadas determinadas */ CanvasRenderer.prototype.goTo = function (x, y) { this.viewOrigin[0] = x; this.viewOrigin[1] = y; } /* Seguir a un objeto particular */ CanvasRenderer.prototype.follow = function (target) { this.followTarget = target; var shiftLeft = this.viewSize[0]/2; var shiftTop = this.viewSize[1]/2; var self = this; this.followIntervalId = window.setInterval (function () { var destination_x = target.x - shiftLeft; var destination_y = target.y - shiftTop; self.goTo (destination_x, destination_y); }, 80); } /* Dejar de seguir a un objeto */ CanvasRenderer.prototype.stopFollow = function () { this.followTarget = null; if (this.followIntervalId != null) { window.clearInterval (this.followIntervalId); this.followIntervalId = null; } } /* Moverse a una ubicacion relativa */ CanvasRenderer.prototype.move = function (x, y) { this.viewOrigin[0] += x; this.viewOrigin[1] += y; this.adjust(); } /* Establecer la esquina superior izquierda de la vista en el area origin: [x, y] */ CanvasRenderer.prototype.setViewOrigin = function (origin) { this.viewOrigin = origin; } /* Establecer la coordenada izquierda de la vista */ CanvasRenderer.prototype.setViewLeft = function (x) { this.viewOrigin[0] = x; } /* Establecer la coordenada superior de la vista */ CanvasRenderer.prototype.setViewTop = function (y) { this.viewOrigin[1] = y; } /* Establecer el tamanio de la vista size: [width, height] */ CanvasRenderer.prototype.setViewSize = function (size) { this.viewSize = size; } /* Establecer el ancho de la vista */ CanvasRenderer.prototype.setViewWidth = function (width) { this.viewSize[0] = width; } /* Establecer el alto de la vista */ CanvasRenderer.prototype.setViewHeight = function (height) { this.viewSize[1] = height; } /* Establecer el tamanio de la renderizacion size: [width, height], expresado en pixeles */ CanvasRenderer.prototype.setRenderSize = function (size) { this.renderSize = size; } /* Establecer el ancho de la renderizacion */ CanvasRenderer.prototype.setRenderWidth = function (width) { this.renderSize[0] = width; } /* Establecer el alto de la renderizacion */ CanvasRenderer.prototype.setRenderHeight = function (height) { this.renderSize[1] = height } /* Mostrar mensaje */ CanvasRenderer.prototype.showMessage = function (text) { this.textMessage = text; var self = this; window.setTimeout (function () { self.textMessage = null; }, 2000); } CanvasRenderer.prototype.renderMessage = function () { this.canvasContext.font = "bold 24px Arial"; this.canvasContext.fillStyle = "#000"; this.canvasContext.strokeStyle = "#88f"; this.canvasContext.textAlign = "center"; this.canvasContext.textWeight = "bold"; this.canvasContext.strokeText (this.textMessage, this.renderSize[0]/2, this.renderSize[1]/2); this.canvasContext.fillText (this.textMessage, this.renderSize[0]/2, this.renderSize[1]/2); }<file_sep>/src/server/Surface.php <?php const SURFACE_WATER = "\x00"; const SURFACE_SWALLOW = 6; const SURFACE_MUD = 16; const SURFACE_QUICKSAND = 20; const SURFACE_GRASS = "\x20"; const SURFACE_EARTH = 48; const SURFACE_SAND = "\x31"; const SURFACE_RED_EARTH = 50; const SURFACE_ROCK = 64; const SURFACE_MOUNTAIN = 65; const SURFACE_BUILDING = 96; const SURFACE_COBBLE = 97; const SURFACE_BRICK = 98; const SURFACE_ICE = 128; const SURFACE_SNOW = 129; const SURFACE_METAL = 144; const SURFACE_GOLD = 145; const SURFACE_AIR = 224; const SURFACE_CLOUD = 225; const SURFACE_VOID = 255;<file_sep>/global.php <html> <head> <meta charset="utf-8" /> <title>μ-κosmos: Mapa del mundo</title> <link rel="stylesheet" type="text/css" href="shared.css" /> <link rel="stylesheet" type="text/css" href="editor.css" /> <script src="jquery-3.1.1.min.js"></script> <script type="application/javascript" src="config.js"></script> <script type="application/javascript" src="jquery-3.1.1.min.js"></script> <script type="application/javascript" src="src/RemoteArea.js"></script> <script type="application/javascript" src="src/ObjectUpdater.js"></script> <script type="application/javascript" src="src/CanvasRenderer.js"></script> <script type="application/javascript" src="src/Surface.js"></script> <script type="application/javascript" src="src/TileFactory.js"></script> <script type="application/javascript" src="src/ResourceHandler.js"></script> <script type="application/javascript" src="src/CollisionChecker.js"></script> <script type="application/javascript" src="global.js"></script> </head> <body> <?php include "nav.php"; ?> <section id="global_map_section"> <div class="controllers"> <header>Editor de mapa</header> <label for="surface_type">Tipo de terreno: </label> <span id="surface_example"></span> <select name="surface_type"></select> <br> <br> <label for="brush_shape">Forma del pincel: </label> <select name="brush_shape"> <option value="square">Cuadrado</option> <option value="circle">Redondo</option> </select> <br> <label for="brush_size">Tama&ntilde;o del pincel: </label> <input name="brush_size" type="number" value="4" min="1" max="128" step="1"> <br> </section> <?php include "footer.php"; ?> </body> <file_sep>/src/ResourceHandler.js ResourceHandler = function () { this.archetypes = {} this.tilesets = {} this.frameDuration = 250; // Esto es para los sprites animados } ResourceHandler.prototype.preloadArchetype = function (url) { var self = this; $.ajax (url, { method: "GET", dataType: "json", success: function (data) { self.archetypes [url] = data; if (data.tileset && data.tileset.url) { self.loadTile (data.tileset.url); } }, }); } ResourceHandler.prototype.execOnArchetype = function (url, callback) { if (this.archetypes[url] != undefined) { callback (this.archetypes [url]); } else { var self = this; $.ajax (url, { method: "GET", dataType: "json", success: function (data) { self.archetypes [url] = data; if (data.tileset && data.tileset.url) { self.loadTile (data.tileset.url); } callback (data); }, error: function (err) { console.log ("Ajax error"); } }); } } ResourceHandler.prototype.loadTile = function (url) { var record = { isLoaded: false, image: new Image() }; record.image.onload = function () { record.isLoaded = true; } record.image.src = url; this.tilesets[url] = record; } ResourceHandler.prototype.hasObjectSprite = function (object) { return ( object.archetype && object.archetype.tileset && this.hasTile (object.archetype.tileset.url) ); } ResourceHandler.prototype.hasTile = function (url) { if (this.tilesets [url] != undefined) { return this.tilesets[url].isLoaded; } } ResourceHandler.prototype.drawObject = function (object, canvas, x, y, width, height, time) { if (object.archetype_url && object.current_sprite) { this.drawTile (object.archetype_url, object.current_sprite, canvas, x, y, width, height, time); } } ResourceHandler.prototype.drawTile = function (url, sprite, canvas, dx, dy, dwidth, dheight, time) { var archetype = this.archetypes[url]; if (archetype && archetype.sprites[sprite]) { var tileset_url = archetype.tileset.url; if (tileset_url && this.hasTile (tileset_url)) { var frame = Math.floor(time/this.frameDuration) % archetype.sprites[sprite].length; var tileset = this.tilesets[tileset_url].image; var sx = archetype.sprites[sprite][frame][0] * archetype.tileset.tile_size[0]; var sy = archetype.sprites[sprite][frame][1] * archetype.tileset.tile_size[1]; var swidth = archetype.tileset.tile_size[0]; var sheight = archetype.tileset.tile_size[1]; canvas.drawImage ( tileset, sx, sy, swidth, sheight, dx, dy, dwidth, dheight ); } } } <file_sep>/doc/Surface.php <!DOCTYPE HTML> <head> <meta charset="utf-8" /> <title>Clase Surface: μ-κosmos</title> <link rel="stylesheet" type="text/css" href="/shared.css" /> <link rel="stylesheet" type="text/css" href="/desarrolladores.css" /> <script src="/jquery-3.1.1.min.js"></script> </head> <body> <?php include "../nav.php"; ?> <section id="desarrolladores_section"> <h1>Surface</h1> <p>El objeto Surface tiene información sobre los tipos de terreno</p> <h4>Surface.WATER</h4> <span class="surface_example" style="background-color: #44f"></span> Agua <h4>Surface.SHALLOW</h4> <span class="surface_example" style="background-color: #48f"></span> Agua de charco <h4>Surface.MUD</h4> <span class="surface_example" style="background-color: #864"></span> Barro <h4>Surface.QUICKSAND</h4> <span class="surface_example" style="background-color: #cc8"></span> Arena movediza <h4>Surface.GRASS</h4> <span class="surface_example" style="background-color: #4f4"></span> Pasto <h4>Surface.EARTH</h4> <span class="surface_example" style="background-color: #621"></span> Tierra <h4>Surface.SAND</h4> <span class="surface_example" style="background-color: #ff6"></span> Arena <h4>Surface.RED_EARTH</h4> <span class="surface_example" style="background-color: #a32"></span> Tierra roja <h4>Surface.ROCK</h4> <span class="surface_example" style="background-color: #866"></span> Roca <h4>Surface.MOUNTAIN</h4> <span class="surface_example" style="background-color: #666"></span> Roca de montaña <h4>Surface.BUILDING</h4> <span class="surface_example" style="background-color: #777"></span> Edificio <h4>Surface.COBBLE</h4> <span class="surface_example" style="background-color: #555"></span> Escombros <h4>Surface.BRICK</h4> <span class="surface_example" style="background-color: #a40"></span> Ladrillo <h4>Surface.ICE</h4> <span class="surface_example" style="background-color: #ccf"></span> Hielo <h4>Surface.SNOW</h4> <span class="surface_example" style="background-color: #eef"></span> Nieve <h4>Surface.METAL</h4> <span class="surface_example" style="background-color: #888"></span> Metal <h4>Surface.GOLD</h4> <span class="surface_example" style="background-color: #fe0"></span> Oro <h4>Surface.AIR</h4> <span class="surface_example" style="background-color: #0cf"></span> Aire <h4>Surface.CLOUD</h4> <span class="surface_example" style="background-color: #eef"></span> Nubes <h4>Surface.VOID</h4> <span class="surface_example" style="background-color: #000"></span> Vacío <h2>Funciones de Surface</h2> <h3>Surface.isSolid</h3> <p>Verifica si una superficie es sólida</p> <h4>Parámetros:</h4> <dl> <dt>surface</dt> <dd class="terreno">Tipo de terreno</dd> </dl> </section> <?php include "../footer.php"; ?> </body> <file_sep>/src/server/start_server.php <?php require_once 'config.php'; require_once 'vendor/autoload.php'; require_once 'Controller.php'; require_once 'WorldServer.php'; require_once 'WorldGenerator.php'; use Ratchet\Server\IoServer; use Ratchet\Http\HttpServer; use Ratchet\WebSocket\WsServer; const MAP_WIDTH = 128; const MAP_HEIGHT = 128; const MAP_FILENAME = "worldfile.json"; $controller = new Controller(); $worldServer = WorldGenerator::generateIslands (MAP_WIDTH, MAP_HEIGHT); $worldServer-> save (MAP_FILENAME); /* if (file_exists (MAP_FILENAME)) { $worldServer = WorldServer::loadFile (MAP_FILENAME); } else { $worldServer = new WorldServer (MAP_WIDTH, MAP_HEIGHT); $worldServer-> save (MAP_FILENAME); } */ $controller-> setWorldServer ($worldServer); $server = IoServer::factory( new HttpServer( new WsServer( $controller ) ), SERVER_PORT ); $server->run(); <file_sep>/src/server/DestroyObjectMessage.php <?php class DestroyObjectMessage { public $entity = "object"; public $action = "destroy"; public $id; public function __construct ($object) { $this-> id = $object-> id; } } <file_sep>/config.js CONFIG_SERVER_ADDRESS="ws://mkosmos.pablocabrera.xyz:443";
ef8ebe632a5551ccc51f5c6e193c6da7189351b2
[ "JavaScript", "PHP" ]
31
PHP
PabloCabrera/mkosmos
d878505fbcb8e851c0f0436b08975a9376bb169b
68aeb759bb826ef9b9b172048de9d8a1f47b60ab
refs/heads/master
<repo_name>AlbertoCF88/carrito<file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { StatefulComponent } from './stateful/stateful.component'; import { StatelessComponent } from './stateless/stateless.component'; import { ConfirmComponent } from './confirm/confirm.component'; import { StatusCartComponent } from './status-cart/status-cart.component'; import { FormularioprimeroComponent } from './formularioprimero/formularioprimero.component'; import { FormualriosegundoComponent } from './formualriosegundo/formualriosegundo.component'; import { NavegadorComponent } from './navegador/navegador.component'; import { ErrorRutaComponent } from './error-ruta/error-ruta.component'; import { ResumenComponent } from './resumen/resumen.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ declarations: [ AppComponent, StatefulComponent, StatelessComponent, ConfirmComponent, StatusCartComponent, FormularioprimeroComponent, FormualriosegundoComponent, NavegadorComponent, ErrorRutaComponent, ResumenComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, HttpClientModule, AppRoutingModule, NgbModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/status-cart/status-cart.component.ts import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core'; import { Product } from '../interface/product'; //onchandges para detectar cambios y simplechsanges @Component({ selector: 'app-status-cart', templateUrl: './status-cart.component.html', styleUrls: ['./status-cart.component.css'] }) export class StatusCartComponent implements OnInit, OnChanges { @Input() price: number;//monitoriza precio @Input() shopModel: Array<Product>;//monitoriza producto @Output() add: EventEmitter<null> = new EventEmitter();// constructor() { } ngOnInit(): void { } ngOnChanges(changes: SimpleChanges): void { console.log(changes) } confirm() { this.add.emit();//envia evento a statefull } } <file_sep>/src/app/error-ruta/error-ruta.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-error-ruta', templateUrl: './error-ruta.component.html', styleUrls: ['./error-ruta.component.css'] }) export class ErrorRutaComponent implements OnInit { constructor() { } ngOnInit(): void { } } <file_sep>/src/app/formualriosegundo/formualriosegundo.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { from } from 'rxjs'; //fromGropu Realiza un seguimiento del valores del formulario //Formbuilder, no añade funcionalidad nueva, simplemente es una manera de dejar el código más bonito y mantenible. //Validators: Para validar la información de los campos del formulario, podemos usar las funciones que nos ofrece Angular o implementar las nuestras propias, para ello cambiamos los objetos: import{ validateURL} from '../validators/url.validators' @Component({ selector: 'app-formualriosegundo', templateUrl: './formualriosegundo.component.html', styleUrls: ['./formualriosegundo.component.css'] }) export class FormualriosegundoComponent implements OnInit { formulario:FormGroup; //hace referenica a la importacion de arriba patronValidacion="[a-z]*"; patronContraseña =/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,15}$/; //sin comillas constructor(private formBuilder: FormBuilder) { } //https://angular.io/api/forms/Validator parametros de validaciones //https://angular.io/api/forms/Validators //https://regex101.com/ web para crear patrones de validaciones ngOnInit(): void { this.formulario = this.formBuilder.group({ user: ['', [Validators.required, Validators.minLength(4), Validators.pattern(this.patronValidacion)]], password: ['', [Validators.required,Validators.pattern(this.patronContraseña)]], email: ["",[Validators.required , Validators.email]],//Validators.email ya tiene por defecto que debe incluir @ y .com, .es... url: ["", [Validators.required, validateURL]] //creada nueva carpeta fuera de la app }); } onSubmit(_formulario){ console.log(_formulario.value); } } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { StatefulComponent } from './stateful/stateful.component'; import { ResumenComponent } from './resumen/resumen.component'; import { ErrorRutaComponent } from './error-ruta/error-ruta.component'; import { FormualriosegundoComponent } from './formualriosegundo/formualriosegundo.component'; const routes: Routes = [ { path: 'cursos', component: StatefulComponent }, { path: 'Resumen/Compra', component: ResumenComponent }, { path: 'Resumen/Compra/:cursoId', component: ResumenComponent }, { path: 'registro', component: FormualriosegundoComponent}, { path: '', component: StatefulComponent, pathMatch: 'full' }, { path: '**', component:ErrorRutaComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/resumen/resumen.component.ts import { Component, OnInit } from '@angular/core'; import {ActivatedRoute} from '@angular/router'; @Component({ selector: 'app-resumen', templateUrl: './resumen.component.html', styleUrls: ['./resumen.component.css'] }) export class ResumenComponent implements OnInit { constructor( private ruta:ActivatedRoute ) { this.ruta.params.subscribe(params=>{ console.log(params['cursoId']) }) } ngOnInit(): void { } } <file_sep>/src/app/formualriosegundo/formualriosegundo.component.html <main role="main" class="container mt-5"> <section id="forms"> <header> <h1>Formulario reactivo</h1></header> <form [formGroup]="formulario" (ngSubmit)="onSubmit(formulario)"novalidate> <fieldset id="forms__input"> <p> <label for="user" >Usuario</label> <input formControlName="user" placeholder="Su nombre de usuario"> <span *ngIf="formulario.get('user').hasError('required')">minimo 4 caracteres y todo minúsculas</span> {{formulario.controls.user.errors | json}} </p> <p> <label for="password">Password</label> <input formControlName="password" type="<PASSWORD>" placeholder="<PASSWORD>"> <span *ngIf="formulario.get('password').hasError('required')"> Minimo 8 caracteres,Mayusculas,numeros y caracter especial </span> {{formulario.controls.password.errors | json}} </p> <p> <label for="url">URL:</label> <input formControlName="url" placeholder="direccion https://"> <span *ngIf="formulario.get('url').hasError('required')">empieza con (https) y termina con (.com)</span> {{formulario.controls.url.errors | json}} </p> <p> <label for="email">Email:</label> <input formControlName="email" placeholder="corre electrónico"> <span *ngIf="formulario.get('email').hasError('required')">debe incluir (@) y terminar en (.com o .es)</span> {{formulario.controls.email.errors | json}} </p> <p> <button class="btn btn-success" type="submit"[disabled]="!formulario.valid">Enviar</button> </p> </fieldset> </form> </section> </main><file_sep>/src/app/stateless/stateless.component.ts import { ChangeDetection } from '@angular/cli/lib/config/schema'; import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { Product } from '../interface/product'; //ChangeDetectionStrategy -> mejorar rendimiento @Component({ selector: 'app-stateless', templateUrl: './stateless.component.html', styleUrls: ['./stateless.component.css'], changeDetection: ChangeDetectionStrategy.OnPush//onPush -> para una mejor eficacia interna de los cambios que produce los botones }) export class StatelessComponent implements OnInit { @Input() product: Product;//usar algo producto de la hota html stataless @Input() disable: boolean; @Output() cursomatriculado: EventEmitter<Product> = new EventEmitter();//evento que recogene componenete padre stateful @Output() cambioColorPadre = new EventEmitter<boolean>();//cambio color precio final padre //lo de public o private para opcional public matricula: string;//es como una variable global para que puede ser llamado por otra hoja or el ejemplo por la hoja html //private es como una varible local(no salgas de esta hoja) constructor() { this.disable=false } ngOnInit(): void { this.matricula = 'Matricularse';//cuando este componente se inicia pone en texto matricularse luego cambiara el texto } matricularse() { //clica entoes es true this.matricula = '¡Matriculado!';//cuando clicas cambiar el texto this.cursomatriculado.emit(this.product);//el padre recibe el evento para mostar el carrito lo sellecionado } isdisabled() { this.disable = true; } mensaje(){ alert('¿Te vas a descargar la imagen?'); } //cambiar precio final color padre FunCambioColor() { this.cambioColorPadre.emit(true) console.log(`color ${this.cambioColorPadre}`) } } <file_sep>/src/app/models/shop.model.ts export class Shop { shopItems: object; static Model: any; constructor() { this.shopItems = [ { title: 'no afecta', desc: 'no afecta ', picture: 'no afecta', price: 0 }, { title: 'no afecta', desc: 'no afecta', picture: 'no afecta', price:0 }, { title: 'no afecta', desc: 'no afecta', picture: 'no afecta', price: 0 } ]; } }<file_sep>/src/app/stateful/stateful.component.ts import { Component, OnInit,ViewChild, OnDestroy, Renderer2, ElementRef } from '@angular/core'; import { ConfirmComponent } from '../confirm/confirm.component'; import { Product } from '../interface/product'; import { Shop } from '../models/shop.model'; import { HttpClient, HttpResponse } from '@angular/common/http'; //importar tambien en app.module import { Subscription } from 'rxjs'; import { style } from '@angular/animations'; //Subscription para manejar (assets)curos.jason como un objeto y sea mas facil de llamar //ahora los cursos van a ser llamdos desde un http externo @Component({ selector: 'app-stateful', templateUrl: './stateful.component.html', styleUrls: ['./stateful.component.css'] }) export class StatefulComponent implements OnInit, OnDestroy {//clase integrada con onInit y onDestroy @ViewChild(ConfirmComponent, {static: false}) confirmchild:ConfirmComponent; @ViewChild ("CambioColor") CambioColor: ElementRef; // shopModel: Shop = new Shop(); errorHttp:boolean; shopModel:any; boughtItems: Array<Product>; cambioColorPadre: boolean;//precio final en rojo viene del hijo disableP:boolean; private shopSubscription: Subscription; //private de forma loca/shopSubcription viene referenciada de import Subcription constructor(private http: HttpClient, private ren: Renderer2) { this.boughtItems = []; this.shopModel ={shopItems: []}; this.cambioColorPadre=false this.disableP=false //ahora los cursos sale de assets cursos.jason y no de models shop.models } ngOnInit(): void { this.shopSubscription = this.http.get('assets/cursos.json').subscribe( (respuesta: Response) => { this.shopModel.shopItems = respuesta; }, (respuesta: Response) => { this.errorHttp = true; } ); this.onGlobalKeyboard(); } ngOnDestroy(): void { this.shopSubscription.unsubscribe();//me desuscribo de shopSbcrption para mejorar rendimiento document.removeEventListener('click', this.onGlobalKeyboard) } clickItem(_curso: Product) { this.boughtItems.push(_curso);//al clicar mete el curso ene l carritod e la compra } eliminarCurso(_curso){ this.boughtItems.splice(_curso,1); } funDisable(){ this.disableP=false; console.log(`this.disable PADRE ${this.disableP}`) } cursoMatriculado(_event: Product){ this.clickItem(_event);//viene del html y a suvez del stateless this.onConfirm(); //muestra alert de metodo onconfimr mas abajo this.confirmchild.isDisabled=false; //controlar el boton de confirm sin pasar por la vista } //https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/reduce //el método reduce() ejecuta una función reductora sobre cada elemento de un array, devolviendo como resultado un único valor. /* La función reductora recibe cuatro argumentos: Acumulador (acc) Valor Actual (cur) Índice Actual (idx) Array (src) El valor devuelto de la función reductora se asigna al acumulador, cuyo valor se recuerda en cada iteración de la matriz y, en última instancia, se convierte en el valor final, único y resultante. Sintaxis arr.reduce(callback(acumulador, valorActual[, índice[, array]])[, valorInicial])*/ onConfirm() { alert('Has añadido un nuevo curso'); } finalPrice() { if (this.boughtItems) {//array con todos los elementos esto se ejecuta solo si this.boughtItems tiene algo que mostar return this.boughtItems.reduce(//devuleveme el precio de cada producto mas la suma de cada producto seleccionado (prev: number, item: Product) => { return prev + item.price; }, 0//valor inicial 0 ); } } onKeyboard(_event){ console.log(_event); if( _event.key === "Enter"){ alert("INTRO") } } onGlobalKeyboard() { document.addEventListener('click', (eventoGlobal) => { console.log("hola, estas clicando por ahi") }); } //recibir color true del hijo FunCambiar(e) { this.cambioColorPadre = e; } } <file_sep>/src/app/validators/url.validators.ts import { AbstractControl } from '@angular/forms'; // si https no estas al principio || o no lleva .com incluido export function validateURL(control: AbstractControl){ if(!control.value.startsWith('https://') || !control.value.includes('.com')) { //tiene que empezar con https y debe incluir un .com return {validUrl: true}; //y si vuelve null es correcto } return null; } // export function validarCorreo (control: AbstractControl) { // if(!control.value.includes('@') || !control.value.includes('.com') && !control.value.includes('.es')) // { //tiene que empezar con https y debe incluir un .com // return {validcorreo: true}; //y si vuelve null es correcto // } // return null; // }
4dea0afd9173d1a98527e39c3c2017a19bfd8a44
[ "TypeScript", "HTML" ]
11
TypeScript
AlbertoCF88/carrito
800cdd08012e6245168521eb2bd2797c5d8bb24b
de575cced6e617526bedf432608e40d3a7903f0c
refs/heads/master
<repo_name>eliecharra/refugesinfo<file_sep>/Makefile VERSION := $(shell git describe --always --long --dirty) build: @go build -ldflags="-X main.version=${VERSION}" <file_sep>/options.go package main // Options passed to api type Options struct { Format string `validate:"eq=gpx|eq=geojson|eq=kmz|eq=kml|eq=gml|eq=csv|eq=xml|eq=rss"` TextFormat string `validate:"eq=bbcode|eq=texte|eq=markdown|eq=html"` NbComs string NbPoints string Detail string `validate:"eq=simple|eq=complet"` PointType string `validate:"eq=cabane|eq=refuge|eq=gite|eq=pt_eau|eq=sommet|eq=pt_passage|eq=bivouac|eq=lac|eq=all"` } <file_sep>/README.md refugesinfo =========== Refuges.info CLI api client Usage ----- ``` $ ./refugesinfo NAME: refugesinfo - Refuges.info API CLI tool USAGE: refugesinfo [global options] command [command options] [arguments...] VERSION: e9a8a7c COMMANDS: bbox Export des points contenus dans une bbox help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --output value Give a file name to save output --help, -h show help --version, -v print the version ``` Bbox ---- ``` ➜ ./refugesinfo bbox --help NAME: refugesinfo bbox - Export des points contenus dans une bbox USAGE: refugesinfo bbox [command options] [arguments...] OPTIONS: --format value Le format de l'export. (default: "geojson") --text-format value Le formatage du texte, que vous devrez retravailler par la suite. (default: "bbcode") --nb-coms value Nombre de commentaires maximum à retourner. Retourne aucun commentaire pour 0. Retourne les n commentaires les plus récents. (default: 0) --nb-points value Nombre de points à exporter (le choix est fait par un algorithme interne avec prioritées élevées pour les abris et cabanes, et faibles pour refuges, sommets, cols...). 0 retournera tous les points de la zone, mais à utiliser avec précautions (lecture illisible et charge serveur importante). (default: 121) --detail value Les détails du point, par défaut uniquement long, lat, altitude, nom, type, id et lien. complet est disponible uniquement lorsque format est geojson, xml. Aussi disponible en gpx (pour avoir un fichier léger) et en rss (complet conseillé pour afficher les remarques diverses). (default: "simple") --point-type value Les types de point à exporter, parmis la liste suivante : cabane, refuge, gite, pt_eau, sommet, pt_passage, bivouac et lac (default: "all") ``` <file_sep>/bbox.go package main import ( "fmt" "io" "log" "net/http" "os" "github.com/urfave/cli" validator "gopkg.in/go-playground/validator.v9" ) func bbox(bbox string, options *Options) { req, err := http.NewRequest("GET", apiBaseURL+"/bbox", nil) if err != nil { log.Fatal(err) os.Exit(1) } q := req.URL.Query() q.Add("bbox", bbox) q.Add("format", options.Format) q.Add("format_texte", options.TextFormat) q.Add("nb_coms", options.NbComs) q.Add("nb_points", options.NbPoints) q.Add("detail", options.Detail) q.Add("type_points", options.PointType) req.URL.RawQuery = q.Encode() resp, err := http.Get(req.URL.String()) if err != nil { log.Fatal(err) os.Exit(1) } defer resp.Body.Close() stream := os.Stdout if output != "" { stream, err = os.Create(output) } io.Copy(stream, resp.Body) } var bboxCmd = cli.Command{ Name: "bbox", Usage: "Export des points contenus dans une bbox", Flags: []cli.Flag{ cli.StringFlag{ Name: "format", Value: "geojson", Usage: "Le format de l'export.", }, cli.StringFlag{ Name: "text-format", Value: "bbcode", Usage: "Le formatage du texte, que vous devrez retravailler par la suite.", }, cli.IntFlag{ Name: "nb-coms", Value: 0, Usage: "Nombre de commentaires maximum à retourner. Retourne aucun commentaire pour 0. Retourne les n commentaires les plus récents.", }, cli.IntFlag{ Name: "nb-points", Value: 121, Usage: "Nombre de points à exporter (le choix est fait par un algorithme interne avec prioritées élevées pour les abris et cabanes, et faibles pour refuges, sommets, cols...). 0 retournera tous les points de la zone, mais à utiliser avec précautions (lecture illisible et charge serveur importante).", }, cli.StringFlag{ Name: "detail", Value: "simple", Usage: "Les détails du point, par défaut uniquement long, lat, altitude, nom, type, id et lien. complet est disponible uniquement lorsque format est geojson, xml. Aussi disponible en gpx (pour avoir un fichier léger) et en rss (complet conseillé pour afficher les remarques diverses).", }, cli.StringFlag{ Name: "point-type", Value: "all", Usage: "Les types de point à exporter, parmis la liste suivante : cabane, refuge, gite, pt_eau, sommet, pt_passage, bivouac et lac", }, }, Action: func(c *cli.Context) error { if c.NArg() != 1 { cli.ShowSubcommandHelp(c) return cli.NewExitError("Missing bbox argument", 1) } options := &Options{ c.String("format"), c.String("text-format"), c.String("nb-coms"), c.String("nb-points"), c.String("detail"), c.String("point-type"), } err := validate.Struct(options) if err != nil { if _, ok := err.(*validator.InvalidValidationError); ok { fmt.Println(err) } for _, err := range err.(validator.ValidationErrors) { return cli.NewExitError("L'option '"+err.Field()+"' est invalide", 1) } } bbox(c.Args().First(), options) return nil }, }
45ebcdd81b81313e91b13c575a10f5c17b2d9f64
[ "Go", "Makefile", "Markdown" ]
4
Makefile
eliecharra/refugesinfo
55f944dea8641f5b275a95ecf1ce6bff923949c2
be01d422d4c9bc0f49c6134a4714fef1dd503791
refs/heads/master
<repo_name>sthurian/jackclient<file_sep>/jackclient/jackclient.cpp #include "jackclient.h" jack_nframes_t JackClient::nframes = 0; JackPort::JackPort(JackClient* client, jack_port_t* port, JackPortType type) : client(client), portType(type) { this->client_handle = client->client; this->port = port; } JackInputPort::JackInputPort(JackClient* client, jack_port_t* port, JackPortType type) : JackPort(client, port, type) {} JackOutputPort::JackOutputPort(JackClient* client, jack_port_t* port, JackPortType type) : JackPort(client, port, type) {} JackAudioInputPort::JackAudioInputPort(JackClient* client, jack_port_t* port) : JackInputPort(client, port, JackPortType::AUDIO) {} JackAudioOutputPort::JackAudioOutputPort(JackClient* client, jack_port_t* port) : JackOutputPort(client, port, JackPortType::AUDIO) {} JackMIDIInputPort::JackMIDIInputPort(JackClient* client, jack_port_t* port) : JackInputPort(client, port, JackPortType::MIDI) {} JackMIDIOutputPort::JackMIDIOutputPort(JackClient* client, jack_port_t* port) : JackOutputPort(client, port, JackPortType::MIDI) {} JackPort::JackPort(JackClient* client, const char* name, JackPortType type) : client(client), portType(type) { this->client_handle = client->client; } JackPort::~JackPort() {} JackInputPort::JackInputPort(JackClient* client, const char* name, JackPortType type) : JackPort(client, name, type) { if (type == JackPortType::AUDIO) this->port = jack_port_register(this->client_handle, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); else if (type == JackPortType::MIDI) this->port = jack_port_register(this->client_handle, name, JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0); } JackOutputPort::JackOutputPort(JackClient* client, const char* name, JackPortType type) : JackPort(client, name, type) { if (type == JackPortType::AUDIO) this->port = jack_port_register(this->client_handle, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); else if (type == JackPortType::MIDI) this->port = jack_port_register(this->client_handle, name, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0); } JackAudioInputPort::JackAudioInputPort(JackClient* client, const char* name) : JackInputPort(client, name, JackPortType::AUDIO) {} JackAudioOutputPort::JackAudioOutputPort(JackClient* client, const char* name) : JackOutputPort(client, name, JackPortType::AUDIO) {} JackMIDIInputPort::JackMIDIInputPort(JackClient* client, const char* name) : JackInputPort(client, name, JackPortType::MIDI) {} JackMIDIOutputPort::JackMIDIOutputPort(JackClient* client, const char* name) : JackOutputPort(client, name, JackPortType::MIDI) {} JackMIDIEvent::JackMIDIEvent(uint32_t time, size_t size, unsigned char* buffer) : time(time), size(size), buffer(buffer) {} uint32_t JackMIDIEvent::getTime() { return this->time; } size_t JackMIDIEvent::getSize() { return this->size; } unsigned char* JackMIDIEvent::getMIDIData() { return this->buffer; } void* JackPort::getBufferInternal() { return jack_port_get_buffer(this->port, JackClient::nframes); } template <typename T> std::vector<std::unique_ptr<T>> JackPort::listConnections() { std::vector<std::unique_ptr<T>> list; const char** portList = jack_port_get_all_connections(this->client_handle, this->port); if (portList) { unsigned int portNum = 0; while (portList[portNum]) { jack_port_t* _port = jack_port_by_name(this->client_handle, portList[portNum]); list.push_back(std::make_unique<T>(this->client, _port)); portNum++; } jack_free(portList); } return list; } std::string JackPort::getName() { return std::string(jack_port_name(this->port)); } std::string JackPort::getShortName() { return std::string(jack_port_short_name(this->port)); } bool JackPort::isPhysical() { return ((jack_port_flags(this->port) & JackPortIsPhysical) == JackPortIsPhysical); } bool JackPort::isMine() { return jack_port_is_mine(this->client_handle, this->port) ? true : false; } JackPortType JackPort::getPortType() { return this->portType; } void JackPort::disconnectAll() { jack_port_disconnect(this->client_handle, this->port); } float* JackAudioInputPort::getBuffer() { return (float*)getBufferInternal(); } float* JackAudioOutputPort::getBuffer() { return (float*)getBufferInternal(); } void JackOutputPort::connectTo(JackInputPort& inPort) { if (this->getPortType() != inPort.getPortType()) throw JackClientException("Cannot connect ports with different types"); if (this->client->getState() != JackState::ACTIVE) throw JackClientException("Cannot connect ports when client is not active"); int err = jack_connect(this->client_handle, jack_port_name(this->port), jack_port_name(inPort.port)); if (err != 0 && err != EEXIST) throw JackClientException("Connecting port failed"); } void JackOutputPort::disconnect(JackInputPort& inPort) { jack_disconnect(this->client_handle, jack_port_name(this->port), jack_port_name(inPort.port)); } void JackInputPort::connectTo(JackOutputPort& outPort) { if (this->getPortType() != outPort.getPortType()) throw JackClientException("Cannot connect ports with different types"); if (this->client->getState() != JackState::ACTIVE) throw JackClientException("Cannot connect ports when client is not active"); int err = jack_connect(this->client_handle, jack_port_name(outPort.port), jack_port_name(this->port)); if (err != 0 && err != EEXIST) throw JackClientException("Connecting port failed"); } void JackInputPort::disconnect(JackOutputPort& outPort) { jack_disconnect(this->client_handle, jack_port_name(outPort.port), jack_port_name(this->port)); } std::vector<std::unique_ptr<JackAudioOutputPort>> JackAudioInputPort::getConnections() { return this->listConnections<JackAudioOutputPort>(); } std::vector<std::unique_ptr<JackAudioInputPort>> JackAudioOutputPort::getConnections() { return this->listConnections<JackAudioInputPort>(); } std::vector<std::unique_ptr<JackMIDIEvent>> JackMIDIInputPort::getMIDIEvents() { std::vector<std::unique_ptr<JackMIDIEvent>> events; void* internalBuf = this->getBufferInternal(); uint32_t count = jack_midi_get_event_count(internalBuf); for (uint32_t i = 0; i < count; i++) { jack_midi_event_t ev; if (!jack_midi_event_get(&ev, this->getBufferInternal(), i)) { events.push_back(std::make_unique<JackMIDIEvent>(ev.time, ev.size, ev.buffer)); } } return events; } void JackMIDIOutputPort::clearBuffer() { jack_midi_clear_buffer(getBufferInternal()); } void JackMIDIOutputPort::writeEvent(JackMIDIEvent& event) { this->write(event.getTime(), event.getMIDIData(), event.getSize()); } void JackMIDIOutputPort::write(uint32_t time, unsigned char* buffer, size_t size) { // Exception ? Return ErrorCode ? Do Nothing if it fails? jack_midi_event_write(getBufferInternal(), time, buffer, size); } JackMIDIInputPort::~JackMIDIInputPort() {} JackClient::JackClient(const char* name) : name(name) {} JackClient::~JackClient() {} JackState JackClient::getState() { return jackState; } int JackClient::process(jack_nframes_t nframes, void* arg) { JackClient* cl = static_cast<JackClient*>(arg); return cl->onProcess(nframes); } void JackClient::jack_shutdown(void* arg) { static_cast<JackClient*>(arg)->jackState = JackState::CLOSED; return static_cast<JackClient*>(arg)->onShutdown(); } int JackClient::buffer_size_callback(jack_nframes_t nframes, void* arg) { JackClient::nframes = nframes; return 0; } int JackClient::xrun_callback(void* arg) { static_cast<JackClient*>(arg)->onXRun(); return 0; } int JackClient::sync_callback(jack_transport_state_t state, jack_position_t* pos, void* arg) { return static_cast<JackClient*>(arg)->onTransportSync( static_cast<Transport::JackTransportState>(state), static_cast<Transport::JackPosition*>(pos)); } void JackClient::timebase_callback(jack_transport_state_t state, jack_nframes_t nframes, jack_position_t* pos, int new_pos, void* arg) { static_cast<JackClient*>(arg)->onTimebase(static_cast<Transport::JackTransportState>(state), nframes, static_cast<Transport::JackPosition*>(pos), new_pos ? true : false); } void JackClient::open() { this->client = jack_client_open(this->name, JackNoStartServer, &this->status, NULL); if (this->client == NULL) { if (this->status & JackServerFailed) { throw JackClientException("Unable to connect to JACK server"); } return; } if (this->status & JackNameNotUnique) this->name = jack_get_client_name(client); jack_set_process_callback(this->client, &JackClient::process, this); jack_on_shutdown(this->client, &JackClient::jack_shutdown, this); jack_set_buffer_size_callback(this->client, &JackClient::buffer_size_callback, this); jack_set_xrun_callback(this->client, &JackClient::xrun_callback, this); jack_set_sync_callback(this->client, &JackClient::sync_callback, this); jackState = JackState::INACTIVE; } void JackClient::close() { if (jackState != JackState::CLOSED) { if (this->client != NULL) jack_client_close(this->client); jackState = JackState::CLOSED; } } void JackClient::activate() { if ((jackState == JackState::INACTIVE) && this->client != NULL && jack_activate(this->client)) { throw JackClientException("cannot activate client"); } jackState = JackState::ACTIVE; } void JackClient::deactivate() { if (jackState == JackState::ACTIVE) jack_deactivate(client); jackState = JackState::INACTIVE; } std::unique_ptr<JackAudioInputPort> JackClient::createAudioInputPort(const char* name) { if (jackState == JackState::CLOSED) throw JackClientException("cannot create port when client is not opened"); return std::make_unique<JackAudioInputPort>(this, name); } std::unique_ptr<JackAudioOutputPort> JackClient::createAudioOutputPort(const char* name) { if (jackState == JackState::CLOSED) throw JackClientException("cannot create port when client is not opened"); return std::make_unique<JackAudioOutputPort>(this, name); } std::unique_ptr<JackMIDIInputPort> JackClient::createMIDIInputPort(const char* name) { if (jackState == JackState::CLOSED) throw JackClientException("cannot create port when client is not opened"); return std::make_unique<JackMIDIInputPort>(this, name); } std::unique_ptr<JackMIDIOutputPort> JackClient::createMIDIOutputPort(const char* name) { if (jackState == JackState::CLOSED) throw JackClientException("cannot create port when client is not opened"); return std::make_unique<JackMIDIOutputPort>(this, name); } void JackClient::startFreewheel() { if (jack_set_freewheel(this->client, 1)) throw JackClientException("Error starting freewheel-mode"); } void JackClient::stopFreewheel() { if (jack_set_freewheel(this->client, 0)) throw JackClientException("Error stopping freewheel-mode"); } std::vector<std::unique_ptr<JackAudioInputPort>> JackClient::getAudioInputPorts() { return this->createPorts<JackAudioInputPort>(JackPortType::AUDIO, JackPortFlags::JackPortIsInput); } std::vector<std::unique_ptr<JackAudioOutputPort>> JackClient::getAudioOutputPorts() { return this->createPorts<JackAudioOutputPort>(JackPortType::AUDIO, JackPortFlags::JackPortIsOutput); } std::vector<std::unique_ptr<JackMIDIInputPort>> JackClient::getMIDIInputPorts() { return this->createPorts<JackMIDIInputPort>(JackPortType::MIDI, JackPortFlags::JackPortIsInput); } std::vector<std::unique_ptr<JackMIDIOutputPort>> JackClient::getMIDIOutputPorts() { return this->createPorts<JackMIDIOutputPort>(JackPortType::MIDI, JackPortFlags::JackPortIsOutput); } template <typename T> std::vector<std::unique_ptr<T>> JackClient::createPorts(JackPortType type, JackPortFlags flags) { std::vector<std::unique_ptr<T>> list; const char** portList; if (type == JackPortType::AUDIO) { portList = jack_get_ports(this->client, NULL, JACK_DEFAULT_AUDIO_TYPE, flags); } else { portList = jack_get_ports(this->client, NULL, JACK_DEFAULT_MIDI_TYPE, flags); } unsigned int portNum = 0; while (portList[portNum]) { jack_port_t* _port = jack_port_by_name(this->client, portList[portNum]); list.push_back(std::make_unique<T>(this, _port)); portNum++; } jack_free(portList); return list; } void JackClient::stopTransport() { jack_transport_stop(this->client); } void JackClient::startTransport() { jack_transport_start(this->client); } void JackClient::setTransportPosition(uint32_t position) { jack_transport_locate(this->client, position); } int JackClient::onTransportSync(Transport::JackTransportState state, Transport::JackPosition* pos) { switch (state) { case Transport::JackTransportState::STARTING: return this->onTransportStart(pos); break; case Transport::JackTransportState::STOPPED: return this->onTransportStop(pos); break; case Transport::JackTransportState::ROLLING: return this->onTransportRoll(pos); break; default: break; } return 0; } void JackClient::enableTimebaseMaster() { if (jack_set_timebase_callback(this->client, 0, &JackClient::timebase_callback, this)) throw JackClientException("Could not enable Timebase Master"); } void JackClient::disableTimebaseMaster() { if (jack_release_timebase(this->client)) throw JackClientException("Could not disable Timebase Master"); } Transport::JackTransportState JackClient::getTransportState() { return static_cast<Transport::JackTransportState>(jack_transport_query(this->client, NULL)); } uint32_t JackClient::getSampleRate() { return jack_get_sample_rate(this->client); }<file_sep>/Makefile CC=/usr/bin/g++ CFLAGS=--std=c++14 -pthread -Os -Wall JACKFLAGS=`pkg-config --cflags --libs jack` TARGETS=main.cpp jackclient/jackclient.cpp all : $(CC) $(CFLAGS) $(TARGETS) $(JACKFLAGS) -o example_client <file_sep>/jackclient/jackclient.h #ifndef _JACKCLIENT_H #define _JACKCLIENT_H #include <jack/jack.h> #include <jack/midiport.h> #include <memory> #include <string> #include <vector> enum class JackPortType { AUDIO, MIDI }; enum class JackState { ACTIVE, INACTIVE, CLOSED }; namespace Transport { enum class JackTransportState { STARTING = JackTransportStarting, ROLLING = JackTransportRolling, STOPPED = JackTransportStopped }; using JackPosition = jack_position_t; } // namespace Transport class JackClient; /** * * * * */ class JackClientException : public std::exception { private: std::string message; public: JackClientException(std::string message) : message(message){}; ~JackClientException(){}; virtual const char* what() { return message.c_str(); }; }; /** * * * * */ class JackPort { protected: JackClient* client; JackPortType portType; jack_client_t* client_handle; uint32_t bufSize; jack_port_t* port; JackPort(JackClient* client, const char* name, JackPortType type); JackPort(JackClient* client, jack_port_t* port, JackPortType type); void* getBufferInternal(); template <typename T> std::vector<std::unique_ptr<T>> listConnections(); public: ~JackPort(); JackPortType getPortType(); std::string getName(); void disconnectAll(); std::string getShortName(); bool isPhysical(); bool isMine(); }; /** * * * * */ class JackOutputPort; class JackInputPort : public JackPort { friend class JackOutputPort; protected: JackInputPort(JackClient* client, const char* name, JackPortType type); JackInputPort(JackClient* client, jack_port_t* port, JackPortType type); public: void connectTo(JackOutputPort& port); void disconnect(JackOutputPort& port); }; /** * * * * */ class JackOutputPort : public JackPort { friend class JackInputPort; protected: JackOutputPort(JackClient* client, const char* name, JackPortType type); JackOutputPort(JackClient* client, jack_port_t* port, JackPortType type); public: void connectTo(JackInputPort& port); void disconnect(JackInputPort& port); }; class JackAudioOutputPort; class JackAudioInputPort : public JackInputPort { friend class JackAudioOutputPort; public: JackAudioInputPort(JackClient* client, const char* name); JackAudioInputPort(JackClient* client, jack_port_t* port); std::vector<std::unique_ptr<JackAudioOutputPort>> getConnections(); float* getBuffer(); }; class JackAudioOutputPort : public JackOutputPort { friend class JackAudioInputPort; public: JackAudioOutputPort(JackClient* client, const char* name); JackAudioOutputPort(JackClient* client, jack_port_t* port); std::vector<std::unique_ptr<JackAudioInputPort>> getConnections(); float* getBuffer(); }; class JackMIDIEvent { private: uint32_t time; size_t size; unsigned char* buffer; public: JackMIDIEvent(uint32_t time, size_t size, unsigned char* buffer); uint32_t getTime(); size_t getSize(); unsigned char* getMIDIData(); }; class JackMIDIInputPort : public JackInputPort { friend class JackOutputPort; public: JackMIDIInputPort(JackClient* client, const char* name); JackMIDIInputPort(JackClient* client, jack_port_t* port); std::vector<std::unique_ptr<JackMIDIEvent>> getMIDIEvents(); ~JackMIDIInputPort(); }; class JackMIDIOutputPort : public JackOutputPort { friend class JackInputPort; public: JackMIDIOutputPort(JackClient* client, const char* name); JackMIDIOutputPort(JackClient* client, jack_port_t* port); void clearBuffer(); void writeEvent(JackMIDIEvent& event); void write(uint32_t time, unsigned char* buffer, size_t size); }; /** * * * * */ class JackClient { friend class JackPort; private: JackState jackState = JackState::CLOSED; jack_status_t status; jack_client_t* client; static jack_nframes_t nframes; const char* name; static int process(jack_nframes_t nframes, void* arg); static void jack_shutdown(void* arg); static void handleShutdown(void* arg); static int buffer_size_callback(jack_nframes_t nframes, void* arg); static int xrun_callback(void* arg); static int sync_callback(jack_transport_state_t state, jack_position_t* pos, void* arg); static void timebase_callback(jack_transport_state_t state, jack_nframes_t nframes, jack_position_t* pos, int new_pos, void* arg); template <typename T> std::vector<std::unique_ptr<T>> createPorts(JackPortType type, JackPortFlags flags); protected: virtual int onProcess(uint32_t sampleCount) = 0; virtual void onShutdown(){}; virtual void onXRun(){}; virtual int onTransportStart(Transport::JackPosition* pos) { return 1; }; virtual int onTransportStop(Transport::JackPosition* pos) { return 1; }; virtual int onTransportRoll(Transport::JackPosition* pos) { return 1; }; virtual int onTransportSync(Transport::JackTransportState state, Transport::JackPosition* pos); virtual void onTimebase(Transport::JackTransportState state, uint32_t frame, Transport::JackPosition* pos, bool newPos){}; public: JackState getState(); JackClient(const char* name); ~JackClient(); void open(); void close(); void activate(); void startTransport(); void stopTransport(); void setTransportPosition(uint32_t position); Transport::JackTransportState getTransportState(); void enableTimebaseMaster(); void disableTimebaseMaster(); void deactivate(); void startFreewheel(); void stopFreewheel(); void setBufferSize(uint32_t bufSize); uint32_t getSampleRate(); std::unique_ptr<JackAudioInputPort> createAudioInputPort(const char* name); std::unique_ptr<JackAudioOutputPort> createAudioOutputPort(const char* name); std::unique_ptr<JackMIDIInputPort> createMIDIInputPort(const char* name); std::unique_ptr<JackMIDIOutputPort> createMIDIOutputPort(const char* name); std::vector<std::unique_ptr<JackAudioInputPort>> getAudioInputPorts(); std::vector<std::unique_ptr<JackAudioOutputPort>> getAudioOutputPorts(); std::vector<std::unique_ptr<JackMIDIInputPort>> getMIDIInputPorts(); std::vector<std::unique_ptr<JackMIDIOutputPort>> getMIDIOutputPorts(); }; #endif <file_sep>/main.cpp #include <iostream> #include "jackclient/jackclient.h" class ExampleClient : public JackClient { private: std::unique_ptr<JackAudioInputPort> inPort; std::unique_ptr<JackAudioOutputPort> outPort; public: ExampleClient() : JackClient("test") { open(); this->inPort = this->createAudioInputPort("example_input"); this->outPort = this->createAudioOutputPort("example_output"); activate(); for (auto &in : this->getAudioInputPorts()) { if (in->isPhysical()) { in->connectTo(*outPort); } } for (auto &out : this->getAudioOutputPorts()) { if (out->isPhysical()) { out->connectTo(*inPort); } } }; ~ExampleClient() { this->close(); } protected: int onProcess(uint32_t sampleCount) { float *out = outPort->getBuffer(); float *in = inPort->getBuffer(); for (uint32_t i = 0; i < sampleCount; i++) (*out++) = in[i]; return 0; } }; int main() { try { ExampleClient client; char input; std::cout << "\nRunning ... press <enter> to quit" << std::endl; std::cin.get(input); } catch (JackClientException &e) { std::cerr << e.what() << std::endl; } return 0; } <file_sep>/README.md # jackclient C++ Wrapper for JACK Audio Connection Kit
f113dc3451968e50da09d06c3966ca0b95c8516d
[ "Markdown", "Makefile", "C++" ]
5
C++
sthurian/jackclient
99dd02dd2732ad4ad255ff75833ece803e6ee2cc
b90f8b9e93d43615f5c370804b9dee9c20b27997
refs/heads/master
<file_sep>package user; import java.sql.CallableStatement; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import database.Database; import database.SQLVO; public class UserDAO { public int posRead(String user_id) { int position=-1; try { String sql="select position from users where user_id=?"; PreparedStatement ps= Database.CON.prepareStatement(sql); ps.setString(1, user_id); ResultSet rs= ps.executeQuery(); if(rs.next()) { position= rs.getInt("position"); } }catch(Exception e) { System.out.println("포지션 읽기"+e.toString()); } return position; } //블랙리스트 public JSONObject blacklist(SQLVO vo) { JSONObject json=new JSONObject(); try { String sql="call blacklist(?,?,?,?,?,?,?)"; CallableStatement cs=Database.CON.prepareCall(sql); cs.setString(1, "users"); cs.setString(2, vo.getKey()); cs.setString(3, vo.getWord()); cs.setString(4, vo.getOrder()); cs.setString(5, vo.getDesc()); cs.setInt(6, vo.getPage()); cs.setInt(7, vo.getPerPage()); cs.execute(); ResultSet rs=cs.getResultSet(); JSONArray array=new JSONArray(); while(rs.next()) { JSONObject obj=new JSONObject(); obj.put("user_id",rs.getString("user_id")); obj.put("user_name",rs.getString("user_name")); array.add(obj); }json.put("blacklist",array); cs.getMoreResults(); rs=cs.getResultSet(); int count=0; if(rs.next()) {count=rs.getInt("total");} int perPage =vo.getPerPage(); int totPage=count%perPage==0?count/perPage:count/perPage+1; json.put("count", count); json.put("page", vo.getPage()); json.put("prePage", vo.getPerPage()); json.put("totPage", totPage); }catch(Exception e) { System.out.println("유저목록:"+e.toString()); }return json; } //position바꾸기 (블랙리스트) public void position(UserVO vo) { try { String sql="update users set position=? where user_id=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, "2"); ps.setString(2, vo.getUser_id()); ps.execute(); }catch(Exception e) { System.out.println("position바꾸기:"+e.toString()); } } //position바꾸기 (블랙리스트) public void positionChange(UserVO vo) { try { String sql="update users set position=? where user_id=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, "0"); ps.setString(2, vo.getUser_id()); ps.execute(); }catch(Exception e) { System.out.println("position바꾸기:"+e.toString()); } } //회원정보읽기(관리자가) public UserVO userRead(String user_id) { UserVO vo=new UserVO(); try { String sql="select * from users where user_id=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, user_id); ResultSet rs=ps.executeQuery(); if(rs.next()) { vo.setUser_id(rs.getString("user_id")); vo.setUser_name(rs.getString("user_name")); vo.setPassword(rs.getString("password")); vo.setBirthday(rs.getString("birthday")); vo.setAddress(rs.getString("address")); vo.setAddress2(rs.getString("address2")); vo.setPoint(rs.getInt("point")); vo.setImage(rs.getString("image")); vo.setPosition(rs.getString("position")); } }catch(Exception e) { System.out.println("관리자가 회원읽기:"+e.toString()); }return vo; } //수정 public void update(UserVO vo){ try { String sql="update users set user_name=?,password=?,phone=?,address=?,address2=? where user_id=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, vo.getUser_name()); ps.setString(2, vo.getPassword()); ps.setString(3, vo.getPhone()); ps.setString(4, vo.getAddress()); ps.setString(5, vo.getAddress2()); ps.setString(6, vo.getUser_id()); ps.execute(); }catch(Exception e) { System.out.println("수정:"+e.toString()); } } //회원탈퇴 public void delete(String user_id) { try { String sql="delete from users where user_id=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, user_id); ps.execute(); }catch(Exception e) { System.out.println("회원탈퇴:"+e.toString()); } } //회원정보읽기(회원이) public UserVO read(String user_id) { UserVO vo=new UserVO(); try { String sql="select * from users where user_id=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, user_id); ResultSet rs=ps.executeQuery(); if(rs.next()) { vo.setUser_id(rs.getString("user_id")); vo.setPassword(rs.getString("password")); vo.setUser_name(rs.getString("user_name")); vo.setPhone(rs.getString("phone")); vo.setAddress(rs.getString("address")); vo.setAddress2(rs.getString("address2")); vo.setPoint(rs.getInt("point")); } }catch(Exception e) { System.out.println("읽기:"+e.toString()); } return vo; } //회원가입 public void insert(UserVO vo) { try { String sql="insert into users(user_id,password,user_name,birthday,position,address,address2,point,phone,image) values(?,?,?,?,0,?,?,0,?,null)"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, vo.getUser_id()); ps.setString(2, vo.getPassword()); ps.setString(3, vo.getUser_name()); ps.setString(4, vo.getBirthday()); ps.setString(5, vo.getAddress()); ps.setString(6, vo.getAddress2()); ps.setString(7, vo.getPhone()); ps.execute(); }catch(Exception e) { System.out.println("회원가입"+e.toString()); } } //로그인체크 public UserVO check(String user_id) { UserVO vo=new UserVO(); try { String sql="select * from users where user_id=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, user_id); ResultSet rs=ps.executeQuery(); if(rs.next()) { vo.setUser_id(rs.getString("user_id")); vo.setPassword(<PASSWORD>("<PASSWORD>")); vo.setUser_name(rs.getString("user_name")); } }catch(Exception e) { System.out.println("로그인체크"+e.toString()); } return vo; } //로그인 public UserVO login(String user_id) { UserVO vo=new UserVO(); try { String sql="select * from users where user_id=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, user_id); ResultSet rs=ps.executeQuery(); if(rs.next()) { vo.setUser_id(rs.getString("user_id")); vo.setPassword(<PASSWORD>")); vo.setUser_name(rs.getString("user_name")); vo.setPosition(rs.getString("position")); vo.setPhone(rs.getString("phone")); } }catch(Exception e) { System.out.println("로그인:"+e.toString()); } return vo; } //유저목록 public JSONObject list(SQLVO vo) { JSONObject json=new JSONObject(); try { String sql="call list(?,?,?,?,?,?,?)"; CallableStatement cs=Database.CON.prepareCall(sql); cs.setString(1, "users"); cs.setString(2, vo.getKey()); cs.setString(3, vo.getWord()); cs.setString(4, vo.getOrder()); cs.setString(5, vo.getDesc()); cs.setInt(6, vo.getPage()); cs.setInt(7, vo.getPerPage()); cs.execute(); ResultSet rs=cs.getResultSet(); JSONArray array=new JSONArray(); while(rs.next()) { JSONObject obj=new JSONObject(); obj.put("user_id",rs.getString("user_id")); obj.put("user_name",rs.getString("user_name")); obj.put("position",rs.getString("position")); obj.put("address",rs.getString("address")); obj.put("address2",rs.getString("address2")); obj.put("phone",rs.getString("phone")); obj.put("image",rs.getString("image")); obj.put("birthday",rs.getString("birthday")); DecimalFormat df=new DecimalFormat("#,###"); obj.put("point", df.format(rs.getInt("point"))); array.add(obj); }json.put("userlist",array); cs.getMoreResults(); rs=cs.getResultSet(); int count=0; if(rs.next()) {count=rs.getInt("total");} int perPage =vo.getPerPage(); int totPage=count%perPage==0?count/perPage:count/perPage+1; json.put("count", count); json.put("page", vo.getPage()); json.put("prePage", vo.getPerPage()); json.put("totPage", totPage); }catch(Exception e) { System.out.println("유저목록:"+e.toString()); }return json; } }<file_sep>package QnA; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import database.SQLVO; @WebServlet(value= {"/QnA/list","/QnA/read","/QnA/AnswerDelete","/QnA/insert","/QnA/updateRead","/QnA/delete","/QnA/update","/QnA/AnswerUpdate"}) public class QnAServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); QnADAO dao=new QnADAO(); QnAVO vo = new QnAVO(); RequestDispatcher dis = null; switch(request.getServletPath()) { case "/QnA/updateRead": request.setAttribute("vo", dao.read(request.getParameter("question_number"))); dis = request.getRequestDispatcher("update.jsp"); dis.forward(request, response); break; case "/QnA/delete": dao.delete(request.getParameter("question_number")); break; case "/QnA/read": request.setAttribute("vo", dao.read(request.getParameter("question_number"))); dis = request.getRequestDispatcher("read.jsp"); dis.forward(request, response); break; case "/QnA/list": SQLVO SQLVO=new SQLVO(); String key=request.getParameter("key")==null?"question_number":request.getParameter("key"); String word=request.getParameter("word")==null?"":request.getParameter("word"); String order=request.getParameter("order")==null?"question_number":request.getParameter("order"); String desc=request.getParameter("key")==null?"":request.getParameter("desc"); String page=request.getParameter("page")==null?"1":request.getParameter("page"); String perPage=request.getParameter("perPage")==null?"5":request.getParameter("perPage"); SQLVO.setKey(key); SQLVO.setWord(word); SQLVO.setOrder(order); SQLVO.setDesc(desc); SQLVO.setPage(Integer.parseInt(page)); SQLVO.setPerPage(Integer.parseInt(perPage)); out.println(dao.list(SQLVO)); break; } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); QnADAO dao=new QnADAO(); QnAVO vo = new QnAVO(); RequestDispatcher dis = null; switch(request.getServletPath()) { case "/QnA/AnswerDelete": vo.setQuestion_number(request.getParameter("question_number")); dao.AnswerDelete(vo); break; case "/QnA/insert": vo.setUser_id(request.getParameter("user_id")); vo.setTitle(request.getParameter("title")); vo.setContent(request.getParameter("content")); dao.insert(vo); response.sendRedirect("list.jsp"); break; case "/QnA/update": vo.setQuestion_number(request.getParameter("question_number")); vo.setTitle(request.getParameter("title")); vo.setContent(request.getParameter("content")); dao.update(vo); break; case "/QnA/AnswerUpdate": vo.setQuestion_number(request.getParameter("question_number")); vo.setAdmin_id(request.getParameter("admin_id")); vo.setContent2(request.getParameter("content2")); dao.AnswerUpdate(vo); break; } } }<file_sep>package QnA; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import database.Database; import database.SQLVO; public class QnADAO { //QnA 답변 삭제 public void AnswerDelete(QnAVO vo) { try { String sql="update qna set admin_id=null,answerDate=null,content2=null,state=0 where question_number=?";; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, vo.getQuestion_number()); ps.execute(); }catch(Exception e) { System.out.println("답변삭제:" + e.toString()); } } //QnA 게시판답변 public void AnswerUpdate(QnAVO vo) { try { String sql="update qna set admin_id=?,answerDate=now(),content2=?,state=1 where question_number=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, vo.getAdmin_id()); ps.setString(2, vo.getContent2()); ps.setString(3, vo.getQuestion_number()); ps.execute(); }catch(Exception e) { System.out.println("게시판답변:" + e.toString()); } } //QnA 게시글 삭제 public void delete(String question_number) { try { String sql = "delete from qna where question_number=?"; PreparedStatement ps = Database.CON.prepareStatement(sql); ps.setString(1, question_number); ps.execute(); }catch(Exception e) { System.out.println("게시글 삭제 :" + e.toString()); } } //QnA 게시글 수정 public void update(QnAVO vo) { try { String sql="update qna set title=?,content=? where question_number=?"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, vo.getTitle()); ps.setString(2, vo.getContent()); ps.setString(3, vo.getQuestion_number()); ps.execute(); }catch(Exception e) { System.out.println("게시글 수정:" + e.toString()); } } //QnA 수정 게시글 읽기 public QnAVO updateRead(String question_number) { QnAVO vo = new QnAVO(); try { String sql="select * from qna where question_number=?"; PreparedStatement ps = Database.CON.prepareStatement(sql); ps.setString(1,question_number); ResultSet rs = ps.executeQuery(); if(rs.next()) { vo.setContent(rs.getString("content")); vo.setTitle(rs.getString("title")); vo.setUser_id(rs.getString("user_id")); vo.setQuestion_number(rs.getString("question_number")); vo.setQuestionDate(rs.getString("questionDate")); } }catch (Exception e) { System.out.println("게시글읽기 : " + e.toString()); } return vo; } //QnA 게시글 읽기 public QnAVO read(String question_number) { QnAVO vo = new QnAVO(); try { String sql="select * from qna where question_number=?"; PreparedStatement ps = Database.CON.prepareStatement(sql); ps.setString(1,question_number); ResultSet rs = ps.executeQuery(); if(rs.next()) { vo.setContent2(rs.getString("content2")); vo.setAnswerDate(rs.getString("answerDate")); vo.setContent(rs.getString("content")); vo.setTitle(rs.getString("title")); vo.setUser_id(rs.getString("user_id")); vo.setQuestion_number(rs.getString("question_number")); vo.setQuestionDate(rs.getString("questionDate")); vo.setState(rs.getString("state")); } }catch (Exception e) { System.out.println("게시글읽기 : " + e.toString()); } return vo; } //QnA 게시판 글쓰기 public boolean insert(QnAVO vo) { boolean success=false; try { String sql="insert into qna(user_id,questionDate,title,content) values(?,now(),?,?)"; PreparedStatement ps = Database.CON.prepareStatement(sql); ps.setString(1, vo.getUser_id()); ps.setString(2, vo.getTitle()); ps.setString(3, vo.getContent()); ps.execute(); success=true; }catch (Exception e) { success=false; System.out.println("게시판 글쓰기 :" + e.toString()); } return false; } //QnA 게시판 목록 출력 public JSONObject list(SQLVO vo) { JSONObject jObject = new JSONObject(); try { String sql="call QnAList(?,?,?,?,?,?,?)"; CallableStatement cs = Database.CON.prepareCall(sql); cs.setString(1, "QnA"); cs.setString(2, vo.getKey()); cs.setString(3, vo.getWord()); cs.setString(4, vo.getOrder()); cs.setString(5, vo.getDesc()); cs.setInt(6, vo.getPage()); cs.setInt(7, vo.getPerPage()); cs.execute(); ResultSet rs = cs.getResultSet(); JSONArray jArray = new JSONArray(); while(rs.next()) { JSONObject obj = new JSONObject(); obj.put("question_number", rs.getString("question_number")); obj.put("user_id", rs.getString("user_id")); obj.put("title", rs.getString("title")); obj.put("questionDate", rs.getString("questionDate")); obj.put("state", rs.getString("state")); jArray.add(obj); } jObject.put("array",jArray); //검색 데이터 갯수 cs.getMoreResults(); rs=cs.getResultSet(); int count=0; if(rs.next()) {count = rs.getInt("total");} int perPage = vo.getPerPage(); int totPage = count%perPage==0? count/perPage:count/perPage+1; jObject.put("count",count); jObject.put("page", vo.getPage()); jObject.put("perPage", perPage); jObject.put("totPage", totPage); }catch (Exception e) { System.out.println("게시판목록 출력 : " + e.toString()); } return jObject; } }<file_sep>package orders; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import database.Database; import database.SQLVO; public class OrderDAO { public JSONObject list(SQLVO vo) { JSONObject jObject= new JSONObject(); try { String sql="call list(?,?,?,?,?,?,?)"; CallableStatement cs=Database.CON.prepareCall(sql); cs.setString(1, "orders"); cs.setString(2, vo.getKey()); cs.setString(3, vo.getWord()); cs.setString(4, vo.getOrder()); cs.setString(5, vo.getDesc()); cs.setInt(6, vo.getPage()); cs.setInt(7, vo.getPerPage()); cs.execute(); ResultSet rs=cs.getResultSet(); JSONArray jArray=new JSONArray(); while(rs.next()) { JSONObject obj=new JSONObject(); obj.put("phone", rs.getString("phone")); obj.put("goods_id", rs.getString("goods_id")); obj.put("orderDate", rs.getString("orderDate")); obj.put("color", rs.getString("color")); obj.put("price", rs.getString("price")); obj.put("quantity", rs.getInt("quantity")); jArray.add(obj); } jObject.put("array", jArray); //검색 데이터 갯수 cs.getMoreResults(); rs=cs.getResultSet(); int count=0; if(rs.next()) { count=rs.getInt("total"); } int perPage=vo.getPerPage(); int totPage=count%perPage==0?count/perPage:count/perPage+1; jObject.put("count", rs.getInt("total")); //전체 데이터 갯수 jObject.put("page", vo.getPage());//현재 페이지 갯수 jObject.put("perPage", perPage); //페이지당 갯수 jObject.put("totPage", totPage); //전체페이지 }catch(Exception e) { System.out.println("구매자 리스트"); } return jObject; } public void insert(OrderVO vo) { try { String sql="insert into orders values(?,?,now(),?,?,?)"; PreparedStatement ps=Database.CON.prepareStatement(sql); ps.setString(1, vo.getPhone()); ps.setString(2, vo.getGoods_id()); ps.setString(3, vo.getColor()); ps.setInt(4, vo.getPrice()); ps.setInt(5, vo.getQuantity()); ps.execute(); }catch(Exception e) { } } //주문 정보 읽기 public JSONObject uoread(String phone) { JSONObject jObject=new JSONObject(); try { String sql="select * from orders where phone=?"; PreparedStatement ps= Database.CON.prepareStatement(sql); ps.setString(1, phone); ResultSet rs= ps.executeQuery(); JSONArray array = new JSONArray(); while(rs.next()) { JSONObject obj= new JSONObject(); obj.put("goods_id", rs.getString("goods_id")); obj.put("color", rs.getString("color")); obj.put("orderDate", rs.getString("orderDate")); obj.put("price", rs.getInt("price")); obj.put("quantity", rs.getInt("quantity")); obj.put("sum",rs.getInt("price")*rs.getInt("quantity")); array.add(obj); } jObject.put("user_order",array); }catch(Exception e) { System.out.println("주문 정보 읽기 :"+e.toString()); } return jObject; } }<file_sep>package stock; public class StockVO { private String goods_id; private String color; private int stock; public String getGoods_id() { return goods_id; } public void setGoods_id(String goods_id) { this.goods_id = goods_id; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } } <file_sep>package orders; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import database.SQLVO; import product.ProductDAO; import purchase.PurchaseDAO; import purchase.PurchaseVO; import product.Stock2VO; import user.UserDAO; @WebServlet(value= {"/orders/read","/orders/purIn","/orders/OrdIn","/orders/poin","/orders/list"}) public class OrdersServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); HttpSession session=request.getSession(); PrintWriter out = response.getWriter(); switch(request.getServletPath()) { case "/orders/list" : OrderDAO odao=new OrderDAO(); SQLVO sqlVO=new SQLVO(); String key=request.getParameter("key")==null?"goods_id":request.getParameter("goods_id"); String word=request.getParameter("word")==null?"":request.getParameter("word"); String order=request.getParameter("order")==null?"goods_id":request.getParameter("order"); String desc=request.getParameter("desc")==null?"":request.getParameter("desc"); String page=request.getParameter("page")==null?"1":request.getParameter("page"); String perPage=request.getParameter("perPage")==null?"5":request.getParameter("perPage"); sqlVO.setKey(key); sqlVO.setWord(word); sqlVO.setOrder(order); sqlVO.setDesc(desc); sqlVO.setPage(Integer.parseInt(page)); sqlVO.setPerPage(Integer.parseInt(perPage)); out.println(odao.list(sqlVO)); break; case "/orders/read": ArrayList<Stock2VO> orderCart=(ArrayList<Stock2VO>)session.getAttribute("orderCart"); Stock2VO svo = new Stock2VO(); for(Stock2VO v:orderCart) { svo.setTotSum(svo.getTotSum()+v.getSum()); } session.setAttribute("totSum", svo.getTotSum()); session.setAttribute("orderCart", orderCart); String goods_id = request.getParameter("goods_id"); session.setAttribute("goods_id", goods_id); ProductDAO pdao=new ProductDAO(); request.setAttribute("prod", pdao.orderList(goods_id)); String user_id = request.getParameter("user_id"); UserDAO udao=new UserDAO(); request.setAttribute("user", udao.read(user_id)); RequestDispatcher dis = request.getRequestDispatcher("order.jsp"); dis.forward(request, response); break; } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); HttpSession session=request.getSession(); PrintWriter out = response.getWriter(); String user_name=request.getParameter("user_name"); String user_phone=request.getParameter("user_phone"); String address=request.getParameter("address"); String goods_id=request.getParameter("goods_id"); switch(request.getServletPath()) { case "/orders/purIn": System.out.println("purchase in"); PurchaseVO pvo=new PurchaseVO(); PurchaseDAO pdao=new PurchaseDAO(); session=request.getSession(); session.setAttribute("phone", user_phone); pvo.setPhone(user_phone); pvo.setUser_name(user_name); pvo.setAddress(address); System.out.println(user_phone+user_name+address); pdao.insert(pvo); break; case "/orders/OrdIn": System.out.println("order in"); user_phone=request.getParameter("user_phone"); goods_id=request.getParameter("goods_id"); OrderVO vo=new OrderVO(); OrderDAO dao=new OrderDAO(); ArrayList<Stock2VO> orderCart=(ArrayList<Stock2VO>)session.getAttribute("orderCart"); for(Stock2VO v:orderCart) { vo.setPhone(user_phone); vo.setGoods_id(goods_id); vo.setColor(v.getColor()); vo.setPrice(v.getPrice()); vo.setQuantity(v.getQuan()); dao.insert(vo); } System.out.println("¿Ï·á"); break; case "/orders/poin": String user_id=request.getParameter("user_id"); int point = Integer.parseInt(request.getParameter("point")); pdao= new PurchaseDAO(); pdao.pointUpdate(user_id,point); break; case "/orders/read": String phone = request.getParameter("phone"); OrderDAO odao= new OrderDAO(); out.print(odao.uoread(phone)); break; } } }<file_sep>package user; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONObject; import database.SQLVO; @WebServlet(value= {"/user/list","/user/logout","/user/login","/user/check","/user/insert","/user/read", "/user/delete","/user/update","/user/userRead","/user/position", "/user/blacklist","/user/positionChange","/user/orderRead"}) public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); UserDAO userdao=new UserDAO(); UserVO uservo=new UserVO(); JSONObject json=new JSONObject(); HttpSession session=request.getSession(); SQLVO sqlVO=new SQLVO(); String user_id=request.getParameter("user_id"); String position=request.getParameter("position"); String user_name=request.getParameter("user_name"); String key=request.getParameter("key")==null?"user_id":request.getParameter("key"); String word=request.getParameter("word")==null?"":request.getParameter("word"); String order=request.getParameter("order")==null?"user_name":request.getParameter("order"); String desc=request.getParameter("desc")==null?"":request.getParameter("desc"); String page=request.getParameter("page")==null?"0":request.getParameter("page"); String perPage=request.getParameter("perPage")==null?"5":request.getParameter("perPage"); switch(request.getServletPath()) { case "/user/blacklist" : sqlVO.setKey(key); sqlVO.setWord(word); sqlVO.setOrder(order); sqlVO.setDesc(desc); sqlVO.setPage(Integer.parseInt(page)); sqlVO.setPerPage(Integer.parseInt(perPage)); out.println(userdao.blacklist(sqlVO)); break; case "/user/list" : sqlVO.setKey(key); sqlVO.setWord(word); sqlVO.setOrder(order); sqlVO.setDesc(desc); sqlVO.setPage(Integer.parseInt(page)); sqlVO.setPerPage(Integer.parseInt(perPage)); out.println(userdao.list(sqlVO)); break; case "/user/logout" : session=request.getSession(); session.invalidate(); response.sendRedirect("login.jsp"); break; case "/user/check" : uservo=userdao.check(request.getParameter("user_id")); int check=-1; if(uservo.getUser_id()==null) { check=0;//아이디없음 } json.put("check",check); out.println(json); break; case "/user/read"://유저읽기(회원이 자기 정보 보는것) request.setAttribute("vo",userdao.read((String) session.getAttribute("user_id"))); //request.setAttribute("clist", pdao.listAll()); RequestDispatcher dis=request.getRequestDispatcher("read.jsp"); dis.forward(request, response); break; case "/user/userRead"://유저읽기(관리자가 회원정보 보는것) System.out.println(position); request.setAttribute("uservo",userdao.userRead(user_id)); //request.setAttribute("clist", pdao.listAll()); dis=request.getRequestDispatcher("userRead.jsp"); dis.forward(request, response); break; case "/user/orderRead": String phone=request.getParameter("phone"); session=request.getSession(); session.setAttribute("phone", phone); response.sendRedirect("userorder.jsp"); break; } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); HttpSession session=request.getSession(); PrintWriter out=response.getWriter(); UserVO vo=new UserVO(); UserDAO userdao=new UserDAO(); String user_id=request.getParameter("user_id"); String password=request.getParameter("password"); String user_name=request.getParameter("user_name"); String phone=request.getParameter("phone"); String position=request.getParameter("position")==null?"2":request.getParameter("position"); String yy=request.getParameter("yy"); String mm=request.getParameter("mm"); String dd=request.getParameter("dd"); String address=request.getParameter("address"); String address2=request.getParameter("address2"); String birthday=yy+"-"+mm+"-"+dd; switch(request.getServletPath()) { case "/user/login" : vo=userdao.login(user_id); int check=0;//아이디가 없는 경우 if(vo.getUser_id()!=null) {//아이디가 있는경우 if(!vo.getPassword().equals(password)){ check=1;//pass가 일치하지않는경우 } else if(vo.getPosition().equals("3")) { check=3; }else if(vo.getPosition().equals("2")) { check=4; }else{ check=2;//pass가 일치하는경우 /*out.println(userdao.userRead(user_id));*/ session=request.getSession(); session.setAttribute("user_id", vo.getUser_id()); session.setAttribute("user_name", vo. getUser_name()); session.setAttribute("position", vo.getPosition()); } } JSONObject json=new JSONObject(); json.put("position",position); json.put("check",check); out.print(json); System.out.println("check:"+ check); break; case "/user/insert" : vo=new UserVO(); vo.setUser_id(user_id); vo.setPassword(<PASSWORD>); vo.setUser_name(user_name); vo.setAddress(address); vo.setAddress2(address2); vo.setBirthday(birthday); vo.setPhone(phone); userdao.insert(vo); response.sendRedirect("/clotheshop_F/user/login.jsp"); break; case "/user/update" : vo.setUser_name(user_name); vo.setPassword(<PASSWORD>); vo.setPhone(phone); vo.setAddress(address); vo.setAddress2(address2); vo.setUser_id(user_id); userdao.update(vo); response.sendRedirect("/ClothShop/index.jsp"); break; case "/user/position" : vo.setUser_id(user_id); vo.setPosition(position); userdao.position(vo); response.sendRedirect("blacklist.jsp"); break; case "/user/positionChange" : System.out.println(user_id); vo.setUser_id(user_id); userdao.positionChange(vo); response.sendRedirect("list.jsp"); break; case "/user/delete" : userdao.delete(user_id); session=request.getSession(); session.invalidate(); break; } } }
b164dd0c5fa80913cdd6418c38a7f8e20a644cb2
[ "Java" ]
7
Java
DeveloperChang/semiProject
91c8b2ec5eff2064e1cde8d9dc85d5d3173fdebd
059a360c189fd9b70697568b86e8e36ed8dc5b9e
refs/heads/master
<file_sep>package bigO; import java.util.Arrays; import java.time.LocalDateTime; import java.util.Date; public class nemo { public static void main(String[] args) { String[] nemo = {"nemo"}; String[] everyone = {"doty","doty","doty","doty","doty","doty","doty","doty","doty","doty","doty","doty","nemo"}; String[] large = new String[100000]; Arrays.fill(large, "nemo"); findNemo(large); } private static void findNemo(String[] arr) { long t0 = System.nanoTime(); for (int i = 0; i < arr.length; i++) { if (arr[i] == "nemo") ; System.out.println("Found NEMO!"); break; } long t1= System.nanoTime(); System.out.println("call to find nemo took: " + (t1-t0) /1e6+" ms"); } }
ab0a1381674f7977caa8785e7b5c2f65a7466d7f
[ "Java" ]
1
Java
mub4shir/MDSA
e6b552b183bb84891bf84902c155704f8223ea20
70ebe3ac71201c8dfe0c007394ff38f451ac4f02
refs/heads/master
<repo_name>MAPR94/voleygenmymodel<file_sep>/ElectivaUDDS.sql -- -- Uncomment me if you want :) -- CREATE DATABASE ElectivaUDDS; CREATE TABLE Miembro ( persona Persona NOT NULL ); CREATE TABLE Carta ( persona Persona NOT NULL, correoentrante String NOT NULL, fecharegistro String NOT NULL, sellomembresia String NOT NULL, fechamembresia String NOT NULL ); CREATE TABLE Registro de Miembros ( miembro Miembro NOT NULL ); CREATE TABLE Persona ( nombre String NOT NULL, apellido String NOT NULL, fechadenacimiento String NOT NULL, edad Integer NOT NULL, sexo String NOT NULL, telefono String NOT NULL, direccion String NOT NULL ); CREATE TABLE Libro de Cartas ( cartas Carta NOT NULL ); <file_sep>/src/main/java/electivaudds/MiembroController.java package electivaudds; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; @RestController public class MiembroController { @RequestMapping("/miembro") public String index() { return "Greetings from MiembroController!"; } } <file_sep>/src/main/java/electivaudds/Libro de CartasController.java package electivaudds; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; @RestController public class Libro de CartasController { @RequestMapping("/libro de cartas") public String index() { return "Greetings from Libro de CartasController!"; } }
989ecc34fe4045c76260a3160f258c8b22f7ccf4
[ "Java", "SQL" ]
3
SQL
MAPR94/voleygenmymodel
336e9d0f8931b2885723da6de2a330fd290076b2
dce2c3857fb329444c1902a1351b034e0b97fc82
refs/heads/master
<file_sep># NoProtocol Laravel Generator The *NoProtocol Laravel Generator* creates a project scaffolding for a Laravel project based on NoProtocol's best practices. This includes such features as: * Complete Gulp build file (based on our own) [gulp-noprotocol](https://github.com/NoProtocol/gulp-noprotocol) library * Automatic robots.txt based on environment setting * Pre-defined SASS & JS structure See the [features](#features) list to see them all. ## Installation If you don't already have it installed, install [Yeoman](http://yeoman.io) npm install -g yo Install the generator npm install -g generator-np-laravel ## Using the generator Make a new directory, and `cd` into it: mkdir my-new-project && cd $_ Run `yo np-laravel` or simply `yo` and select the `Np Laravel` generator. ### Options: * `--quick` Skip interaction and install app with defaults* and setup the database, create Git repository and install all Composer/NPM/Bower dependencies * `--skipdbsetup` Skip the database setup * `--skipdependencies` Skip installation of all the Composer/NPM/Bower dependencies * `--force` Force installation even if the directory isn't empty __\*__ Defaults are as follows: * Projectname: __dirname__ * Project version: __1.0.0__ * Laravel version: __5.2.24__ * Setup database: __yes__ * Database credentials: __root/root__ * Database name: __projectname_ddb__ * Setup git repository: __yes__ *You can also see these options by running `yo np-laravel --help`.* When the generator is finished, run `gulp` and you're done. ## Features: ### Laravel Laravel `v5.2.24`, `v5.2.23`, `v5.2.15`, `v5.2.0`, `5.1.11`, `5.1.4`, `5.1` or `master`. See the [Laravel site](http://laravel.com/) for the various versions. ### Gulp Build the app using [Gulp](http://gulpjs.com/) and our own [gulp-noprotocol](https://github.com/NoProtocol/gulp-noprotocol) (which takes care of bundling files, running sass etc). Place all the app JS files outside the webroot in `resources/js`. The gulp process will bundle them into *app.min.js* in the `public/build/js` folder. If needed, extra JS libs can be placed anywhere and added to the gulp `bundle-libs` task. These will be bundled into *libs.min.js* Place all the Sass files outside the webroot in `resources/sass`. The gulp process will bundle them into *app.js* in the `public/build/js` folder. The gulp watch task also activates Livereload which is set to reload on changes to *.js* and *.css* files. ### Robots.txt Due to repeated incidents in which staging server still allowed crawlers to access everything, the generator comes with `RobotsController.php`. On any Laravel environment other the production the output will be `Disallow: *`. ### .htaccess The .htaccess file has been augmented with several settings taken from the [HTML5 boilerplate](https://github.com/h5bp/server-configs-apache/blob/master/dist/.htaccess) such as media types, security settings, gzip etc. The option to force HTTPS for one or more domains has also been added. See the file for more info. ### Splash page A NoProtocol splash page on the index :) <file_sep><?php namespace App\Http\Controllers; class RobotsController extends Controller { /* |-------------------------------------------------------------------------- | Robots Controller |-------------------------------------------------------------------------- | | Returns the correct content for a robots.txt based on the environment. | */ /** * By default, every environment returns 'Disallow: /' (disallowing everything) except production which returns 'Disallow: ' (allow everything) * If you want to disallow files/folders for production, add them to the $disallowedItems array. * @return Response the plain text robots.txt response */ public function index() { $robot = 'User-agent: *' . PHP_EOL; // Disallowed files/folders on production environment $disallowedItems = []; // append extra dissallowed items here // $disallowedItems[] = 'foo/bar'; if(app()->environment() !== 'production') { // not environment production, dissallow everything $robot .= 'Disallow: /' . PHP_EOL; } else { // if there are no dissallowed items, return an empty string of the item ('Disallow: ') equals allow everything if(count($disallowedItems) === 0) { $robot .= 'Disallow: ' . PHP_EOL; } foreach ($disallowedItems as $item) { $robot .= 'Disallow: ' . $item . PHP_EOL; } } return \Response::make($robot, 200, array('content-type' => 'text/plain')); } } <file_sep>var gulp = require('gulp'); var noprotocol = require('gulp-noprotocol'); var livereload = require('gulp-livereload'); gulp.task('css', function () { return gulp.src('resources/sass/**/*.{scss,sass}') .pipe(noprotocol.css()) .on('error', noprotocol.notify) .pipe(gulp.dest('public/build/css')); }); gulp.task('bundle-libs', function () { return gulp.src([ //'node_modules/jquery/dist/jquery.min.js' ]) .pipe(noprotocol.bundle('libs.min.js')) .on('error', noprotocol.notify) .pipe(gulp.dest('public/build/js')); }); gulp.task('bundle-app', function () { return gulp .src(['resources/js/**/*.js']) .on('error', noprotocol.notify) .pipe(noprotocol.bundle('app.min.js')) .pipe(gulp.dest('public/build/js')); }); gulp.task('watch', ['css', 'bundle-app', 'bundle-libs'], function () { livereload.listen(); gulp.watch(['resources/sass/**/*.{scss,sass}'], ['css']); gulp.watch(['resources/js/**/*.js'], ['bundle-app']); gulp.watch([ 'public/build/**/*.css', 'public/build/**/*.js', ]).on('change', livereload.changed); gulp.watch(['gulpfile.js'], function () { noprotocol.notify('Stopping `gulp watch`, gulpfile.js was changed'); process.exit(); }); }); gulp.task('deploy', ['css', 'bundle-app', 'bundle-libs']); gulp.task('default', ['watch']);<file_sep># <Project name> ## Install guide How to install this app / get it running ## Project info Info about the project such as: whitelisting, gotcha's, pitfalls, different standards etc, used tech etc. Basically anything that isn't immediately visible. ## Links Staging, Production etc
091f24f240c88262f4a1e632f50c5f191a201f69
[ "Markdown", "JavaScript", "PHP" ]
4
Markdown
NoProtocol/generator-np-laravel
28ec0acac73f344a6c6dfee11b58468468deaf5b
224df291aa8867046ad1be46ab14634a28fa34f1
refs/heads/master
<repo_name>simonyilunw/cars_cities<file_sep>/cars_cities/management/commands/compute_latlng_data2.py from os import path from django.core.management.base import BaseCommand from django.db import connections from django.conf import settings from ...constants import GEOCARS_DB from ...utils.files import pickle_save QUERY = """ select t1.lat, t1.lng, sum(t1.score) as total_score, sum(t2.price*t1.score)/sum(t1.score) as avg_price, sum(t2.mpg_highway*t1.score)/sum(t1.score) as avg_mpg_highway, sum(t2.mpg_city*t1.score)/sum(t1.score) as avg_mpg_city, sum(t2.hybrid*t1.score) as avg_hybrid, sum(t2.is_foreign*t1.score) as avg_foreign, sum(t2.electric*t1.score) as avg_electric, sum(t1.score/t2.mpg_city) as mpg_weighted, t1.id from all_cars.`city_%s` t1 join geocars.`car_metadata` t2 on t1.group_id = t2.group_id group by t1.lat, t1.lng; """ LAT = 0 LNG = 1 TOTAL_SCORE = 2 AVG_PRICE = 3 AVG_MPG_HIGHWAY = 4 AVG_MPG_CITY = 5 AVG_HYBRID = 6 AVG_FOREIGN = 7 AVG_ELECTRIC = 8 MPG_WEIGHTED = 9 DB_ID = 10 CUSTOM_CITIES = {174, 173} class Command(BaseCommand): def handle(self, *args, **kwargs): for city_id in CUSTOM_CITIES or settings.CITY_IDS: self.compute_latlng_for_city(city_id) def compute_latlng_for_city(self, city_id): self.stdout.write('Querying data for %s...' % city_id) cursor = connections[GEOCARS_DB].cursor() cursor.execute(QUERY % city_id) raw_data = cursor.fetchall() self.stdout.write('Finished querying data for %s, starting pickling...' % city_id) latlngs = {} count = 0 for row in raw_data: lat, lng = float(row[LAT]), float(row[LNG]) if (lat, lng) not in latlngs: latlngs[(lat, lng)] = { 'price': 0.0, 'mpg_highway': 0.0, 'mpg_city': 0.0, 'hybrid': 0.0, 'electric': 0.0, 'is_foreign': 0.0, 'total_score': 0.0, 'mpg_weighted': 0.0, } latlngs[(lat, lng)]['id'] = row[DB_ID] latlngs[(lat, lng)]['total_score'] = row[TOTAL_SCORE] latlngs[(lat, lng)]['price'] = row[AVG_PRICE] latlngs[(lat, lng)]['mpg_highway'] = row[AVG_MPG_HIGHWAY] latlngs[(lat, lng)]['mpg_city'] = row[AVG_MPG_CITY] latlngs[(lat, lng)]['hybrid'] = row[AVG_HYBRID] latlngs[(lat, lng)]['electric'] = row[AVG_ELECTRIC] latlngs[(lat, lng)]['is_foreign'] = row[AVG_FOREIGN] latlngs[(lat, lng)]['mpg_weighted'] = row[MPG_WEIGHTED] count += 1 if count % 3000 == 0: self.stdout.write('Pickled %s rows..' % count) self.stdout.write('Pickling complete for %s, writing data file..' % city_id) pickle_save(latlngs, path.join(settings.LATLNGS_DIR, str(city_id))) self.stdout.write('Finished!') <file_sep>/cars_cities/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic import TemplateView from django.views.generic.base import RedirectView from django.contrib.staticfiles.urls import staticfiles_urlpatterns from views import Home, Stats, Samples, AggregateStats, Hotspots, Results, \ Heatmap, Coverage, CountryHeatmap, CustomZip, Voting urlpatterns = patterns('', url(r'^$', RedirectView.as_view(pattern_name='home')), url(r'^home$', Home.as_view(), name='home'), url(r'^aggregate$', AggregateStats.as_view(), name='aggregate'), url(r'^stats$', Stats.as_view(), name='stats'), url(r'^coverage$', Coverage.as_view(), name='coverage'), url(r'^results$', Results.as_view(), name='results'), url(r'^results/zipcode/correlations$', TemplateView.as_view(template_name='correlations.html'), name='correlations'), url(r'^samples/(?P<cityid>[\d]+)$', Samples.as_view(), name='samples'), url(r'^hotspots/(?P<cityid>[\d]+)$', Hotspots.as_view(), name='hotspots'), url(r'^heatmap/(?P<cityid>[\d]+)$', Heatmap.as_view(), name='heatmap'), url(r'^customzip/$', CustomZip.as_view(), name='customzip'), url(r'^countryheatmap$', CountryHeatmap.as_view(), name='countryheatmap'), url(r'^admin/', include(admin.site.urls)), url(r'^car_cities/', include(staticfiles_urlpatterns())), url(r'^voting/(?P<cityid>[\d]+)$', Voting.as_view(), name='voting') ) urlpatterns += staticfiles_urlpatterns() <file_sep>/cars_cities/constants.py # constants that represent the database names ALL_CARS_DB = 'all_cars' BOSTON_CARS_DB = 'boston_cars' GEO_DB = 'geo' GEOCARS_DB = 'geocars' GEOCARS_CRAWLED_DB = 'geocars_crawled' <file_sep>/cars_cities/scripts/compute_gwr.py from os import path import sys try: import arcpy except ImportError: print 'Cannot import arcpy. Abort.' sys.exit(1) from constants import LATLNGS_SHP_DIR, CACHE_DIR, PROJECTION_FILE AREA_COMPUTE_EXPRESSION = '{0}'.format('!SHAPE.area@SQUAREMILES!') def compute_gwr(cityid): input_path = path.join(LATLNGS_SHP_DIR, '%s_age.shp' % cityid) output_path = path.join(CACHE_DIR, 'gwr', '%s.shp' % cityid) rasters_path = path.join(CACHE_DIR, 'gwr_rasters') print 'Computing gwr for city %s' % cityid arcpy.GeographicallyWeightedRegression_stats(input_path, 'income', 'price', output_path, 'ADAPTIVE', 'BANDWIDTH PARAMETER', '#', '25', '#', rasters_path,) print 'DONE!' if __name__=='__main__': compute_gwr(153) <file_sep>/cars_cities/management/commands/compute_stats.py import numpy as np from django.core.management.base import BaseCommand from django.db import connections from django.conf import settings from ...constants import ALL_CARS_DB from ...models import City from ...utils.files import pickle_save class Command(BaseCommand): def handle(self, *args, **kwargs): cursor = connections[ALL_CARS_DB].cursor() cursor.execute('SHOW TABLES') tables = cursor.fetchall() cursor.close() stats = {} for (table, ) in tables: split = table.split('_') if len(split) != 2: continue city_id = split[1] city = City(int(city_id)) self.stdout.write('Computing stats for city %s... with %d samples' % (city_id, city.samples)) stats[city.name] = self.compute_stats(city) stats[city.name].update({ 'latitude': city.latitude, 'longitude': city.longitude, 'total_samples': city.samples }) pickle_save(stats, settings.STATS_DIR + '/aggregate') def compute_stats(self, city): stats = {} total_car_mpg_highway = 0.0 total_score = 0.0 total_hybrid = 0.0 total_foreign = 0.0 total_domestic = 0.0 weighted_prices = [] for group_id, data in city.groups.iteritems(): score = data['score'] raw_price = data['price'] price = raw_price * score weighted_prices.append(price) total_score += score total_car_mpg_highway += data['mpg_highway'] * score if data['hybrid']: total_hybrid += score if data['is_foreign']: total_foreign += score else: total_domestic += score stats['total_cars'] = total_score stats['car_price_avg'] = sum(weighted_prices) / total_score stats['car_price_variance'] = np.var(weighted_prices) stats['car_mpg_highway_avg'] = total_car_mpg_highway / total_score stats['car_hybrid_ratio'] = total_hybrid / total_score stats['car_foreign_ratio'] = total_foreign / total_score stats['car_domestic_ratio'] = total_domestic / total_score return stats <file_sep>/cars_cities/management/commands/compute_city_aggregate.py from os import path from django.core.management.base import BaseCommand from django.db import connections from django.conf import settings from ...constants import GEOCARS_DB from ...utils.files import pickle_save, pickle_load QUERY = """ select stddev(t2.price*t1.score) as std_price, stddev(t2.mpg_city*t1.score) as std_mpg_city, stddev(t2.mpg_highway*t1.score) as std_mpg_highway, sum(t1.score)/sum(t2.mpg_highway*t1.score) as avg_gpm_highway, sum(t1.score)/sum(t2.mpg_city*t1.score) as avg_gpm_city, stddev(t2.hybrid*t1.score) as std_hybrid, stddev(t2.is_foreign*t1.score) as std_foreign, stddev(t2.electric*t1.score) as std_electric from all_cars.city_%s t1 join geocars.car_metadata t2 on t1.group_id = t2.group_id """ CUSTOM_CITIES = {} class Command(BaseCommand): def handle(self, *args, **kwargs): for city_id in CUSTOM_CITIES or settings.CITY_IDS: self.compute_latlng_for_city(city_id) def compute_latlng_for_city(self, city_id): self.stdout.write('Querying data for %s...' % city_id) cursor = connections[GEOCARS_DB].cursor() cursor.execute(QUERY % city_id) raw_data = cursor.fetchall() self.stdout.write('Finished querying data for %s, starting pickling...' % city_id) aggregate = pickle_load(path.join(settings.STATS_DIR, 'aggregate')) count = 0 if city_id not in aggregate: aggregate[city_id] = {} for std_price, std_mpg_city, std_mpg_highway, avg_gpm_highway, avg_gpm_city, \ std_hybrid, std_foreign, std_electric in raw_data: aggregate[city_id]['std_price'] = std_price aggregate[city_id]['std_mpg_city'] = std_mpg_city aggregate[city_id]['std_mpg_highway'] = std_mpg_highway aggregate[city_id]['avg_gpm_highway'] = avg_gpm_highway aggregate[city_id]['avg_gpm_city'] = avg_gpm_city aggregate[city_id]['std_hybrid'] = std_hybrid aggregate[city_id]['std_foreign'] = std_foreign aggregate[city_id]['std_electric'] = std_electric count += 1 self.stdout.write('Pickled %s rows..' % count) if count > 1: self.stderr.write('How did there appear more than 1 row??') self.stdout.write('Pickling complete for %s, writing data file..' % city_id) pickle_save(aggregate, path.join(settings.STATS_DIR, 'aggregate')) self.stdout.write('Finished!') <file_sep>/cars_cities/scripts/compute_zipcode_data.py from os import path import sys import shapefile from constants import CACHE_DIR, SHAPEFILE_DIR, CONVEXHULL_DIR, CITY_IDS, PROJECTION_FILE from utils import pickle_load, pickle_save def format_zipcode(zipcode): zipcode = str(zipcode) while len(zipcode) < 5: zipcode = '0' + zipcode return zipcode if __name__=='__main__': all_cars_data = pickle_load(path.join(CACHE_DIR, 'all_cars_data')) all_census_data = pickle_load(path.join(CACHE_DIR, 'all_census_data')) reader = shapefile.Reader(path.join(CACHE_DIR, 'zipcodes/zip_poly/zip_poly')) zipcodeList = {} for key, data in all_cars_data.iteritems(): zipcode = data[94] cityid = int(data[95]) formatted_zipcode = format_zipcode(zipcode) if cityid == 137: if formatted_zipcode not in zipcodeList: zipcodeList[formatted_zipcode] = 1 print 'Reading polygon file...' zip_poly = {} for sr in reader.shapeRecords(): if sr.record[0] in zipcodeList: polygon = sr.shape.points zip_poly[str(sr.record[0])] = map(lambda x: [x[1], x[0]], polygon) print 'Finished reading polygon file!' print 'Writing city zipcodes file' city_zipcode_data = {} for key, data in all_cars_data.iteritems(): zipcode = data[94] cityid = int(data[95]) if cityid == 137: if cityid not in city_zipcode_data: city_zipcode_data[cityid] = {} formatted_zipcode = format_zipcode(zipcode) if formatted_zipcode not in city_zipcode_data[cityid]: city_zipcode_data[cityid][formatted_zipcode] = {} city_zipcode_data[cityid][formatted_zipcode]['price'] = data[2] city_zipcode_data[cityid][formatted_zipcode]['income'] = all_census_data[zipcode][11] if formatted_zipcode in zip_poly: poly = zip_poly[formatted_zipcode] else: poly = [] print 'zip_poly does not contain %s!' % formatted_zipcode city_zipcode_data[cityid][formatted_zipcode]['polygon'] = poly print 'Saving pickle files' for cityid in city_zipcode_data: pickle_save(city_zipcode_data[cityid], path.join(CACHE_DIR, 'zipcodes/pickled/' + str(cityid))) print 'Wrote pickled zipcode file for', cityid print 'Finished!' <file_sep>/cars_cities/utils/shapefile.py from __future__ import absolute_import from shapefile import Reader as UnsafeReader from shapefile import unpack, b, u class Reader(UnsafeReader): def __record(self): """ Overrides the __record method of the original shapefile Reader so that interpreting floats as ints will not throw exception """ f = self.__getFileObj(self.dbf) recFmt = self.__recordFmt() recordContents = unpack(recFmt[0], f.read(recFmt[1])) if recordContents[0] != b(' '): return None record = [] for (name, typ, size, deci), value in zip(self.fields, recordContents): if name == 'DeletionFlag': continue elif not value.strip(): record.append(value) continue elif typ == "N": value = value.replace(b('\0'), b('')).strip() if value == b(''): value = 0 elif deci: value = float(value) else: try: value = int(float(value or 0)) # THIS is the change required, was just int(value) except ValueError: value = 0 elif typ == b('D'): try: y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8]) value = [y, m, d] except: value = value.strip() elif typ == b('L'): value = (value in b('YyTt') and b('T')) or \ (value in b('NnFf') and b('F')) or b('?') else: value = u(value) value = value.strip() record.append(value) return record <file_sep>/requirements.txt Django==1.7 MySQL-python==1.2.5 wsgiref==0.1.2 ipython==2.0.0 ipdb==0.8 numpy==1.6.2 pyshp==1.2.1 us==0.9.0<file_sep>/cars_cities/scripts/constants.py import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) CACHE_DIR = os.path.join(BASE_DIR, 'cache') ARCGIS_DIR = os.path.join(CACHE_DIR, 'arcgis') SAMPLES_DIR = os.path.join(CACHE_DIR, 'samples') SHAPEFILE_DIR = os.path.join(SAMPLES_DIR, 'shp') STATS_DIR = os.path.join(CACHE_DIR, 'stats') CITY_DIR = os.path.join(CACHE_DIR, 'city') CITY_BOUNDARY_SHP_DIR = os.path.join(CACHE_DIR, 'city_boundary_shp') GROUPS_DIR = os.path.join(CITY_DIR, 'groups') LATLNGS_DIR = os.path.join(CITY_DIR, 'latlngs') HOTSPOTS_DIR = os.path.join(CITY_DIR, 'hotspots') LATLNGS_SHP_DIR = os.path.join(LATLNGS_DIR, 'shp') CONVEXHULL_DIR = os.path.join(SAMPLES_DIR, 'convexhull') RESAMPLE_DIR = os.path.join(CACHE_DIR, 'resample') DOWNSAMPLE_DIR = os.path.join(CACHE_DIR, 'downsample') CITY_IDS = [int(f.split('.')[0]) for f in os.listdir(SAMPLES_DIR) if f.endswith('.csv')] PROJECTION_FILE = os.path.join(ARCGIS_DIR, 'WGS 1984.prj') MAKES = [ 'nissan', 'mitsubishi', 'mercury', 'mercedes-benz', 'mclaren', 'mazda', 'maybach', 'maserati', 'mini', 'lotus', 'lincoln', 'lexus', 'land rover', 'lamborghini', 'kia', 'jeep', 'jaguar', 'isuzu', 'infiniti', 'hyundai', 'honda', 'hummer', 'geo', 'gmc', 'ford', 'fisker', 'ferrari', 'fiat', 'eagle', 'dodge', 'daewoo', 'chrysler', 'plymouth', 'chevrolet', 'cadillac', 'buick', 'bugatti', 'bentley', 'bmw', 'audi', '<NAME>', 'acura', '<NAME>', 'oldsmobile', 'panoz', 'pontiac', 'porsche', 'ram', 'rolls-royce', 'saab', 'saturn', 'scion', 'spyker', 'subaru', 'suzuki', 'tesla', 'toyota', 'volkswagen', 'volvo', 'smart' ]<file_sep>/cars_cities/scripts/generate_all_city_digest.py from os import path import sys import us import cPickle as pickle from constants import CACHE_DIR, STATS_DIR, CITY_IDS, CITY_DIR, GROUPS_DIR, SAMPLES_DIR from cars_cities.models import City from utils import pickle_load digest = [] for cityid in CITY_IDS: city = City(cityid) print 'Processing', city.name, city.state name = city.name.title() state = city.state.title() area = city.area samples = city.samples polygon_path = path.join(SAMPLES_DIR, 'polygons', str(cityid)) polygon = pickle.load(open(polygon_path, 'r')) sample_area = polygon['area'] coverage = float(sample_area) / float(area) moran_indices = pickle_load(path.join(CACHE_DIR, 'moran_indices')) digest.append({ 'cityid': cityid, 'name': name, 'state': state, 'area': area, 'samples': samples, 'sample_area': sample_area, 'coverage': coverage, 'moran_index': moran_indices[cityid] }) pickle.dump(digest, open(path.join(STATS_DIR, 'all_cities'), 'wb')) print 'FINISHED' <file_sep>/cars_cities/management/commands/compute_car_aggregate.py from os import path from django.core.management.base import BaseCommand from django.db import connections from django.conf import settings from ...constants import GEOCARS_DB from ...utils.files import pickle_save, pickle_load MAKES_QUERY = """ select car.make, car.%s, sum(sample.score) from all_cars.city_%s sample join geocars_crawled.control_classes car on sample.group_id = car.group_id where car.make='Aston Martin' or car.make='Land Rover' or car.make='AM General' group by car.make, car.%s """ COUNTRIES_QUERY = """ select car.country, sum(sample.score) from all_cars.city_%s sample join geocars.car_metadata car on sample.group_id = car.group_id group by car.country """ CUSTOM_CITIES = {} class Command(BaseCommand): def write_countries(self): cursor = connections[GEOCARS_DB].cursor() cursor.execute( 'select distinct country from geocars.car_metadata') raw_data = cursor.fetchall() countries = [str(r[0]) for r in raw_data] self.stdout.write(str(countries)) pickle_save(countries, path.join(settings.STATS_DIR, 'countries')) self.stdout.write('Written to countries file') def write_makes(self): cursor = connections[GEOCARS_DB].cursor() cursor.execute( 'select distinct make from geocars_crawled.control_classes') raw_data = cursor.fetchall() makes = [str(r[0]) for r in raw_data] self.stdout.write(str(makes)) pickle_save(makes, path.join(settings.STATS_DIR, 'makes')) self.stdout.write('Written to makes file') def write_models(self): cursor = connections[GEOCARS_DB].cursor() cursor.execute( 'select make, model from geocars_crawled.control_classes group by make, model') raw_data = cursor.fetchall() models = {} for make, model in raw_data: if make not in models: models[make] = [] models[make].append(model) for m in models.values(): m = sorted(m) self.stdout.write(str(models)) pickle_save(models, path.join(settings.STATS_DIR, 'models')) self.stdout.write('Written to models file') def fix_aggregate_from_backup(self): aggregate = pickle_load(path.join(settings.STATS_DIR, 'aggregate')) backup = pickle_load( path.join(settings.STATS_DIR, 'aggregate_backup_12-10-2014')) for cityid in backup: makes = backup[cityid]['makes'] models = backup[cityid]['models'] for make in makes: if make not in aggregate[cityid]['makes']: aggregate[cityid]['makes'][make] = makes[make] self.stdout.write( 'Syncing make %s from city %s' % (make, cityid)) for model in models: if model not in aggregate[cityid]['models']: aggregate[cityid]['models'][model] = models[model] self.stdout.write( 'Syncing model %s from city %s' % (model, cityid)) pickle_save(aggregate, path.join(settings.STATS_DIR, 'aggregate')) def handle(self, *args, **kwargs): self.fix_aggregate_from_backup() return for city_id in CUSTOM_CITIES or settings.CITY_IDS: self.compute_car_aggregate_for_city(city_id) def compute_car_aggregate_for_city(self, city_id): self.stdout.write('Loading aggregate data...') aggregate = pickle_load(path.join(settings.STATS_DIR, 'aggregate')) cursor = connections[GEOCARS_DB].cursor() self.stdout.write('Querying %s data for %s...' % ('country', city_id)) cursor.execute(COUNTRIES_QUERY % city_id) raw_data = cursor.fetchall() self.stdout.write( 'Finished querying data for %s, starting pickling...' % city_id) if city_id not in aggregate: aggregate[city_id] = {} aggregate[city_id]['countries'] = {} for country, score in raw_data: aggregate[city_id]['countries'][country] = score self.stdout.write( 'Pickling complete for %s, writing data file..' % city_id) pickle_save(aggregate, path.join(settings.STATS_DIR, 'aggregate')) self.stdout.write('Finished!') <file_sep>/cars_cities/management/commands/car_model_distribution.py from os import path from collections import defaultdict import shapefile from django.core.management.base import BaseCommand from django.db import connections from django.conf import settings from ...constants import GEOCARS_DB from ...utils.files import pickle_save QUERY = """ select cc.make, cc.model, cc.submodel, t1.score from all_cars.city_%s t1 join geocars.car_metadata t2 on t1.group_id=t2.group_id join geocars_crawled.control_classes cc on t2.group_id=cc.group_id where %s group by t1.lat, t1.lng; """ class Command(BaseCommand): def handle(self, *args, **kwargs): self.stdout.write('Loading SHP file...') reader = shapefile.Reader(path.join(settings.CACHE_DIR, 'government', 'new_mexico_clipped')) make_distribution = defaultdict(float) model_distribution = defaultdict(float) submodel_distribution = defaultdict(float) filter_clause = [] for shape in reader.shapes(): lng, lat = shape.points[0] filter_clause.append(('(t1.lat=%s and t1.lng=%s)' % (lat, lng))) print '%s filter clauses!' % len(filter_clause) segment = 0 increment = 500 raw_data = [] segments = len(filter_clause) / increment while segment * increment < len(filter_clause): filter_string = ' or '.join(filter_clause[segment * increment:segment * increment + increment]) print 'Quering segment %d out of %s' % (segment, segments) self.stdout.write('Querying data...') cursor = connections[GEOCARS_DB].cursor() cursor.execute(QUERY % (173, filter_string)) raw_data += cursor.fetchall() cursor.execute(QUERY % (174, filter_string)) raw_data += cursor.fetchall() segment += 1 for make, model, submodel, score in raw_data: make_distribution[make] += score model_distribution[model] += score submodel_distribution[submodel] += score make_distribution = sorted(make_distribution.items(), key=lambda x: x[1], reverse=True) print '\nMake Distribution:' for make, score in make_distribution: print '%s: %s' % (make.title(), score) model_distribution = sorted(model_distribution.items(), key=lambda x: x[1], reverse=True) print '\nModel Distribution:' for model, score in model_distribution: print '%s: %s' % (model.title(), score) submodel_distribution = sorted(submodel_distribution.items(), key=lambda x: x[1], reverse=True) print '\nSubmodel Distribution:' for submodel, score in submodel_distribution: print '%s: %s' % (submodel.title(), score) """ makes = defaultdict(float) count = 0 for row in raw_data: lat, lng = float(row[LAT]), float(row[LNG]) if (lat, lng) not in latlngs: latlngs[(lat, lng)] = { 'price': 0.0, 'mpg_highway': 0.0, 'mpg_city': 0.0, 'hybrid': 0.0, 'electric': 0.0, 'is_foreign': 0.0, 'total_score': 0.0, 'mpg_weighted': 0.0, } latlngs[(lat, lng)]['id'] = row[DB_ID] latlngs[(lat, lng)]['total_score'] = row[TOTAL_SCORE] latlngs[(lat, lng)]['price'] = row[AVG_PRICE] latlngs[(lat, lng)]['mpg_highway'] = row[AVG_MPG_HIGHWAY] latlngs[(lat, lng)]['mpg_city'] = row[AVG_MPG_CITY] latlngs[(lat, lng)]['hybrid'] = row[AVG_HYBRID] latlngs[(lat, lng)]['electric'] = row[AVG_ELECTRIC] latlngs[(lat, lng)]['is_foreign'] = row[AVG_FOREIGN] latlngs[(lat, lng)]['mpg_weighted'] = row[MPG_WEIGHTED] count += 1 if count % 3000 == 0: self.stdout.write('Pickled %s rows..' % count) """ self.stdout.write('Finished!') <file_sep>/cars_cities/scripts/shp_to_csv.py import csv from shutil import copyfile from os.path import join, exists import shapefile from constants import RESAMPLE_DIR, CITY_IDS def shp_to_csv(filename, city_id): """ Converts sampling CSV (lat, long) into shapefiles """ print 'Processing shapefile %s...' % filename reader = shapefile.Reader(filename) writer = csv.writer(open(filename + '.csv', 'wb+'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) count = 0 for shape in reader.shapes(): writer.writerow(shape.points[0]) count += 1 if count % 10000 == 0: print 'Written %s rows' % count print 'FINISHED' if __name__ == '__main__': for city_id in CITY_IDS: target_file = 'C:\\Users\\huifang\\Desktop\\Dropbox\\Stanford\\Research\\cvpr2015\\resample\\%s.csv' % city_id if exists(target_file): print 'City %s csv already exists, continuing' % city_id continue city_id = str(city_id) try: shp_to_csv(join(RESAMPLE_DIR, city_id, 'sample_grid_clipped'), city_id) except Exception as e: print 'ERROR', str(e) continue copyfile(join(RESAMPLE_DIR, city_id, 'sample_grid_clipped.csv'), target_file) <file_sep>/cars_cities/settings/_base.py """ Django settings for cars_cities project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ from ..constants import ALL_CARS_DB, BOSTON_CARS_DB, GEO_DB, GEOCARS_DB, GEOCARS_CRAWLED_DB # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) CACHE_DIR = os.path.join(BASE_DIR, 'cache') CITY_DIR = os.path.join(CACHE_DIR, 'city') GROUPS_DIR = os.path.join(CITY_DIR, 'groups') LATLNGS_DIR = os.path.join(CITY_DIR, 'latlngs') LATLNGS_SHP_DIR = os.path.join(LATLNGS_DIR, 'shp') HOTSPOTS_DIR = os.path.join(CITY_DIR, 'hotspots') STATS_DIR = os.path.join(CACHE_DIR, 'stats') SAMPLES_DIR = os.path.join(CACHE_DIR, 'samples') SHAPEFILE_DIR = os.path.join(SAMPLES_DIR, 'shp') CONVEXHULL_DIR = os.path.join(SAMPLES_DIR, 'convexhull') POLYGONS_DIR = os.path.join(SAMPLES_DIR, 'polygons') MA_DATA_DIR = os.path.join(CACHE_DIR, 'ma_data/Spatial') CITY_IDS = [int(f.split('.')[0]) for f in os.listdir(SAMPLES_DIR) if f.endswith('.csv')] # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = <KEY> # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cars_cities' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', #'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'cars_cities.urls' WSGI_APPLICATION = 'cars_cities.wsgi.application' # Database DATABASE_TEMPLATE = { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'imagenet.stanford.edu', 'USER': 'duchen', 'PASSWORD': '', # TODO add a password this this account for security! 'PORT': '3306', } DATABASE_NAMES = (ALL_CARS_DB, BOSTON_CARS_DB, GEO_DB, GEOCARS_DB, GEOCARS_CRAWLED_DB) DATABASES = {} for name in DATABASE_NAMES: template = DATABASE_TEMPLATE.copy() template['NAME'] = name DATABASES[name] = template # add a default DB (some random sqlite db since we won't ever really need to use this db) DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } # Internationalization LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Los_Angeles' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' <file_sep>/cars_cities/models/base.py from django.db import connections class BaseModel(object): DB = 'default' def execute_query(self, query, args=[], db=None): if not db: db = self.DB cursor = connections[db].cursor() cursor.execute(query, args) result = cursor.fetchall() cursor.close() return result <file_sep>/cars_cities/scripts/census_income.py import sys from os import path import time from census import Census, ALL from fcc.census_block_conversions import census_block_dict import shapefile from constants import CACHE_DIR, LATLNGS_SHP_DIR from utils import pickle_save, pickle_load YEAR = 2010 try: BLOCK_DATA_CACHE = pickle_load(path.join(CACHE_DIR, 'block_data')) except Exception as e: print 'CANNOT LOAD BLOCK DATA CACHE: ', str(e) sys.exit(1) CENSUS_DATA_CACHE = pickle_load(path.join(CACHE_DIR, 'census_data_cache')) CENSUS_API_KEY = '3a7f0def09f356fa48f84558824b09a009c1f6e2' INCOME_VARIABLE = 'B06011_001E' AGE_VARIABLE = 'B05004_004E' client = Census(CENSUS_API_KEY).acs def get_block_data(lat, lng, data): if not data.get((lat, lng)): data[(lat, lng)] = census_block_dict(lat, lng, year=YEAR) return data[(lat, lng)] def get_variable(lat, lng, data, var=INCOME_VARIABLE): block_data = get_block_data(lat, lng, data) #print block_data try: state_fips = block_data['State']['FIPS'] county_fips = block_data['County']['FIPS'][2:] tract_fips = block_data['Block']['FIPS'][5:11] except Exception as e: print 'Error getting block data for %s, %s' % (lat, lng) return 0 query = (var, state_fips, county_fips, tract_fips) if query not in CENSUS_DATA_CACHE: result = client.state_county_tract(*query)[0] CENSUS_DATA_CACHE[query] = result return CENSUS_DATA_CACHE[query][var] def compute_city(cityid): reader = shapefile.Reader(path.join(LATLNGS_SHP_DIR, str(cityid))) writer = shapefile.Writer(shapefile.POINT) writer.autoBalance = 1 writer.field('price', 'N') writer.field('income', 'N') writer.field('age', 'N') total = len(reader.shapeRecords()) count = 0 for sr in reader.shapeRecords(): point = sr.shape.points[0] price = sr.record[0] income = get_variable(point[1], point[0], BLOCK_DATA_CACHE[cityid], INCOME_VARIABLE) age = get_variable(point[1], point[0], BLOCK_DATA_CACHE[cityid], AGE_VARIABLE) writer.point(point[0], point[1]) writer.record(price, income, age) count += 1 if count % 100 == 0: print 'Processed %d out of %d' % (count, total) pickle_save(CENSUS_DATA_CACHE, path.join(CACHE_DIR, 'census_data_cache')) pickle_save(BLOCK_DATA_CACHE, path.join(CACHE_DIR, 'block_data')) writer.save(path.join(LATLNGS_SHP_DIR, str(cityid) + '_age')) if __name__ == '__main__': compute_city(153)<file_sep>/cars_cities/views/stats.py from django.views.generic import TemplateView from django.conf import settings from ..utils.files import pickle_load class Stats(TemplateView): template_name = 'stats.html' def get_context_data(self, **kwargs): cities = pickle_load(settings.STATS_DIR + '/aggregate') kwargs.update({ 'cities': cities }) return kwargs <file_sep>/cars_cities/views/samples.py from os import path from django.views.generic import View from django.conf import settings from django.shortcuts import render from ..utils.files import pickle_load class Samples(View): def get(self, request, cityid=None): polygon_path = path.join(settings.SAMPLES_DIR, 'polygons', str(cityid)) polygon = pickle_load(polygon_path) city = pickle_load(path.join(settings.CITY_DIR, str(cityid))) if 'boundary' in city: city['boundary'] = [[y,x] for [x,y] in city['boundary']] # reverse the lat longs context = { 'polygon': polygon, 'city': city } return render(request, 'samples.html', context) <file_sep>/cars_cities/models/city.py from os import path from collections import defaultdict from django.conf import settings from base import BaseModel from ..constants import ALL_CARS_DB, GEOCARS_DB, GEO_DB from ..utils.files import pickle_save, pickle_load class City(BaseModel): def __init__(self, city_id, force_recompute=False): self.city_id = city_id data = pickle_load(path.join(settings.CITY_DIR, str(city_id))) if force_recompute or not data: self.compute_data() else: self.load_state(data) def save_state(self): pickle_save(self.__dict__, path.join(settings.CITY_DIR, str(self.city_id))) def load_state(self, data): for key, value in data.iteritems(): setattr(self, key, value) def compute_data(self): self.fetch_metadata() QUERY = """ SELECT group_id, score FROM city_%s """ result = self.execute_query(QUERY, [self.city_id], ALL_CARS_DB) groups = defaultdict(dict) for group_id, score in result: if 'score' in groups[group_id]: groups[group_id]['score'] += score else: groups[group_id]['score'] = score QUERY = """ SELECT * FROM car_metadata WHERE group_id IN %s """ result = self.execute_query(QUERY, [groups.keys()], GEOCARS_DB) for group_id, price, fuel_type, mpg_highway, mpg_city, hybrid, electric, country, is_foreign in result: groups[group_id].update({ 'price': price, 'fuel_type': fuel_type, 'mpg_city': mpg_city, 'mpg_highway': mpg_highway, 'hybrid': hybrid, 'electric': electric, 'country': country, 'is_foreign': is_foreign }) pickle_save(groups, path.join(settings.GROUPS_DIR, str(self.city_id))) @property def groups(self): return pickle_load(path.join(settings.GROUPS_DIR, str(self.city_id))) def fetch_metadata(self): QUERY = """ SELECT cityname, state, lat, lng FROM cities WHERE cityid=%s """ result = self.execute_query(QUERY, [self.city_id], GEO_DB) assert len(result) == 1 result = result[0] self.name = result[0] self.state = result[1] self.latitude = result[2] self.longitude = result[3] <file_sep>/cars_cities/views/voting.py from os import path from django.views.generic import View from django.conf import settings from django.shortcuts import render from ..utils.files import pickle_load from ..utils.shapefile import Reader ZIPCODE_FIELDS = { 'zipcode_price_avg': 'zip_code_to_car_price', 'zipcode_income_avg': 'zip_code_to_income' } FINE_GRAIN_HEATMAP_FIELDS = { 'car_density': 0.0001 } class Voting(View): def get(self, request, cityid): field = request.GET.get('field', 'voting') context = {} template = 'voting.html' polygon_path = path.join(settings.SAMPLES_DIR, 'polygons', str(cityid)) polygon = pickle_load(polygon_path) if not self.request.GET.get('show_city_boundary') and 'data' in polygon: polygon.pop('data') context['polygon'] = polygon voting = Reader(path.join(settings.CACHE_DIR, 'arcgis/voting_result_new')) # print voting.fields[36] if field == 'voting': voting_data = dict([(sr.record[36], { 'polygon': map(lambda x: list(x[::-1]), sr.shape.points), 'voting': sr.record[37], }) for sr in voting.shapeRecords() ]) elif field == 'voting_preds': voting_data = dict([(sr.record[36], { 'polygon': map(lambda x: list(x[::-1]), sr.shape.points), 'demo': sr.record[38], }) for sr in voting.shapeRecords() ]) print len(voting_data) #for sr in voting.shapeRecords(): # print sr.record context['voting'] = voting_data context['field'] = field return render(request, template, context) <file_sep>/cars_cities/scripts/test.py from os import path import time from census import Census, ALL from fcc.census_block_conversions import census_block_dict import shapefile from constants import CACHE_DIR, LATLNGS_SHP_DIR from utils import pickle_load def compute_city(cityid): data = pickle_load(path.join(CACHE_DIR, 'MA_census_data')) print data if __name__ == '__main__': compute_city(153)<file_sep>/cars_cities/scripts/group_price_by_block.py from os import path from collections import defaultdict import shapefile from utils import pickle_save, pickle_load from constants import CACHE_DIR, LATLNGS_SHP_DIR try: BLOCK_DATA_CACHE = pickle_load(path.join(CACHE_DIR, 'block_data')) except Exception as e: print 'CANNOT LOAD BLOCK DATA CACHE: ', str(e) BLOCK_DATA_CACHE = {} def get_block_id(data): return data['Block']['FIPS'][:-1] def group_price_by_block(cityid): reader = shapefile.Reader(path.join(LATLNGS_SHP_DIR, str(cityid))) changed = False block_total = {} block_data = BLOCK_DATA_CACHE[cityid] for sr in reader.shapeRecords(): (lng, lat) = sr.shape.points[0] data = block_data.get((lat, lng)) if not data: continue if 'price' not in data and 'income' not in data: block_data[(lat, lng)]['price'] = sr.record[0] block_data[(lat, lng)]['income'] = sr.record[1] changed = True if 'Block' in data: if get_block_id(data) in block_total: block_total[get_block_id(data)]['total'] += float(sr.record[0]) block_total[get_block_id(data)]['count'] += 1 else: block_total[get_block_id(data)] = { 'total': float(sr.record[0]), 'count': 1 } block_averages = {k: v['total'] / v['count'] for k, v in block_total.iteritems()} print len(block_data) print len(block_averages) for key, data in block_data.iteritems(): if 'Block' in data: data['block_price_average'] = block_averages[get_block_id(data)] changed = True if changed: print 'CHANGED! updating block cache file' pickle_save(BLOCK_DATA_CACHE, path.join(CACHE_DIR, 'block_data')) if __name__ == '__main__': group_price_by_block(153) <file_sep>/cars_cities/scripts/downsample.py import os import sys import us import xlrd import ftplib import zipfile import datetime from os.path import join, exists try: print 'Initializing ArcGIS python modules...' import arcpy except ImportError: print 'Cannot import arcpy. Abort.' sys.exit(1) else: arcpy.env.overwriteOutput = True print 'ArcGIS initialization complete' from constants import LATLNGS_SHP_DIR, DOWNSAMPLE_DIR, PROJECTION_FILE, CITY_IDS SEGMENT = 'all' CITY_IDS_CUSTOM = [] def log(msg, *args): print ('[%s] Segment %s: ' % (datetime.datetime.now().strftime('%H:%M:%S'), SEGMENT) + msg) % args def downsample(city_id): log('Downsampling points for %s', city_id) output_dir = join(DOWNSAMPLE_DIR, str(city_id)) if not exists(output_dir): os.makedirs(output_dir) log('Created %s', output_dir) else: log('%s already exists!', output_dir) samples_shp = join(LATLNGS_SHP_DIR, '%s.shp' % city_id) downsampling_fishnet_poly_shp = join(output_dir, 'downsampling_fishnet.shp') downsampling_fishnet_label_shp = join(output_dir, 'downsampling_fishnet_label.shp') if not exists(downsampling_fishnet_poly_shp): log('Creating fishnet...') desc = arcpy.Describe(samples_shp) arcpy.CreateFishnet_management( downsampling_fishnet_poly_shp, str(desc.extent.lowerLeft), str(desc.extent.XMin) + ' ' + str(desc.extent.YMax + 10), '0.0012', '0.0012', '0', '0', str(desc.extent.upperRight), 'LABELS', '#', 'POLYGON' ) log('Fishnet creation complete') samples_identity_shp = join(output_dir, 'samples_identity.shp') if not exists(samples_identity_shp): log('Computing identity...') arcpy.Identity_analysis(samples_shp, downsampling_fishnet_poly_shp, samples_identity_shp) log('Identity complete') samples_stats = join(output_dir, 'samples_stats') if not exists(join(output_dir, 'info')): log('Starting summary statistics...') arcpy.Statistics_analysis(samples_identity_shp, samples_stats, [['price', 'MEAN']], 'FID_downsa') log('Summary statistics complete') log('Detecting if join has already been done...') join_done = False fields = arcpy.ListFields(downsampling_fishnet_label_shp) for field in fields: if field.name == 'MEAN_PRICE': join_done = True if not join_done: log('Performing table join on FID:FID_DOWNSA...') arcpy.JoinField_management(downsampling_fishnet_label_shp, 'FID', samples_stats, 'FID_DOWNSA', ['MEAN_PRICE']) log('Table join on FID:FID_DOWNSA done.') log('Defining projection...') arcpy.DefineProjection_management(downsampling_fishnet_label_shp, PROJECTION_FILE) log('FINISHED downsampling %s', city_id) return downsampling_fishnet_label_shp log('======================END==========================') if __name__ == '__main__': # shp = compute_resampling(196) # export_to_png(shp, join(RESAMPLE_DIR, str(196))) log('=====================BEGIN=========================') for city_id in CITY_IDS_CUSTOM or CITY_IDS: downsample(city_id) <file_sep>/cars_cities/management/commands/convert_city_boundary_shp.py from os import path from django.core.management.base import BaseCommand from django.conf import settings import us import shapefile from ...models import City class Command(BaseCommand): """ Converts city boundary shp data obtained from the census website into list of [x,y] and store in City data files under the attribute "boundary" """ def handle(self, *args, **kwargs): cities = [City(cityid) for cityid in settings.CITY_IDS] self.stdout.write('Loaded %d city data files' % len(cities)) city_dict = {(city.name.strip().lower(), city.state.strip().lower()): city for city in cities} for state in us.STATES: try: reader = shapefile.Reader(path.join(settings.CACHE_DIR, 'city_boundary_shp', 'tl_2014_%s_place' % state.fips)) except shapefile.ShapefileException: self.stderr.write('State %s places SHP file not found' % state.name) continue else: self.stdout.write('Processing SHP file for %s' % state.name) shaperecords = reader.shapeRecords() for shaperecord in shaperecords: record = shaperecord.record shape = shaperecord.shape name = record[4] match_criteria = (name.lower(), state.name.lower()) matched_city = city_dict.get(match_criteria) if matched_city: self.stdout.write('Match criteria: %s' % str(match_criteria)) self.stdout.write('Matched boundary for cityid %s' % matched_city.city_id) matched_city.boundary = shape.points matched_city.save_state() cities_without_boundary = [city.name for city in cities if not hasattr(city, 'boundary')] self.stderr.write('Cities without boundaries: %s' % cities_without_boundary) <file_sep>/cars_cities/views/countryheatmap.py from os import path from django.views.generic import View from django.conf import settings from django.shortcuts import render from ..models import City from ..utils.files import pickle_save, pickle_load class CountryHeatmap(View): def get(self, request): field = request.GET.get('field', 'race') context = {} if field: print 'Using field ', field context['field'] = field if field == 'race' or field == 'race_preds' or field == 'edu' or field == 'edu_preds' or field == 'income' or field == 'income_preds': try: context['zipcodes'] = pickle_load(path.join(settings.CACHE_DIR, 'zipcodes/pickled/allCities')) data = pickle_load(path.join(settings.STATS_DIR, 'demog')) except Exception as e: context['error'] = e else: for zipcode, d in context['zipcodes'].iteritems(): if zipcode in data: if field == 'income': context['zipcodes'][zipcode]['demog'] = data[zipcode]['census'][11] elif field == 'income_preds': context['zipcodes'][zipcode]['demog'] = data[zipcode]['preds'][11] elif field == 'race': context['zipcodes'][zipcode]['demog'] = self.getRace(data[zipcode]['census']) elif field == 'race_preds': context['zipcodes'][zipcode]['demog'] = self.getRace(data[zipcode]['preds']) elif field == 'edu': context['zipcodes'][zipcode]['demog'] = self.getEdu(data[zipcode]['census']) elif field == 'edu_preds': context['zipcodes'][zipcode]['demog'] = self.getEdu(data[zipcode]['preds']) #print context['zipcodes'][zipcode]['demog'] return render(request, 'countryheatmap.html', context) def getRace(self, x): maxValue = max(x[16:19]) if x[16] == maxValue: return 1 elif x[17] == maxValue: return 2 elif x[18] == maxValue: return 3 def getEdu(self, x): maxValue = max([x[20], x[22], x[23]]) if x[20] == maxValue: return 1 elif x[22] == maxValue: return 2 elif x[23] == maxValue: return 3<file_sep>/cars_cities/views/hotspots.py from os import path import shapefile from django.views.generic import TemplateView from django.conf import settings from ..utils.files import pickle_load from ..utils.shapefile import Reader class Hotspots(TemplateView): template_name = 'hotspots.html' def get_context_data(self, **kwargs): cityid = self.kwargs.get('cityid') special = self.request.GET.get('special') if special: shp_path = path.join( settings.CACHE_DIR, 'hotspots', special) else: shp_path = path.join( settings.HOTSPOTS_DIR, str(cityid) + '_hotspots') try: reader = Reader(shp_path) except Exception as e: kwargs['error'] = e return kwargs zipcodes = Reader( path.join(settings.MA_DATA_DIR, 'ma_zipcodes_poly_latlng')) polygon_path = path.join(settings.SAMPLES_DIR, 'polygons', str(cityid)) polygon = pickle_load(polygon_path) kwargs['data'] = reader kwargs['polygon'] = polygon kwargs['zipcodes'] = zipcodes return kwargs <file_sep>/cars_cities/apache/django.wsgi import os import sys root_path='/imagenetdb/duchen/cars_cities' path=root_path + '/cars_cities' if root_path not in sys.path: sys.path.append(root_path) if path not in sys.path: sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cars_cities.settings.production") import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() <file_sep>/cars_cities/scripts/sample_csv_to_shp.py import csv from os import path import shapefile from constants import CITY_IDS, SAMPLES_DIR, SHAPEFILE_DIR def csv_to_ship(cityid): """ Converts sampling CSV (lat, long) into shapefiles """ with open(path.join(SAMPLES_DIR, '%s.csv' % cityid), 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) print 'Processing shapefile %s...' % cityid writer = shapefile.Writer(shapefile.POINT) writer.autoBalance = 1 writer.field('lat') writer.field('lng') index = 0 for row in reader: lat, lng = map(float, row) writer.point(lng, lat) writer.record(lng, lat) index += 1 shp_path = path.join(SHAPEFILE_DIR, str(cityid)) writer.save(shp_path) print 'Written shapefile to %s' % shp_path if __name__=='__main__': for cityid in CITY_IDS: csv_to_ship(cityid) <file_sep>/cars_cities/views/results.py from os import path from django.views.generic import TemplateView from django.conf import settings from ..utils.files import pickle_load import shapefile class Results(TemplateView): template_name = 'results.html' def get_context_data(self, **kwargs): cities = pickle_load(path.join(settings.STATS_DIR, 'all_cities')) for city in cities: city['hotspots_available'] = path.isfile( path.join(settings.HOTSPOTS_DIR, str(city['cityid']) + '_hotspots.shp')) city['latlng_data_available'] = path.isfile( path.join(settings.LATLNGS_DIR, str(city['cityid']))) city['zipcode_available'] = path.isfile( path.join(settings.CACHE_DIR, 'zipcodes', 'pickled', str(city['cityid']))) kwargs['cities'] = cities kwargs['makes'] = pickle_load(path.join(settings.STATS_DIR, 'makes')) kwargs['models'] = pickle_load(path.join(settings.STATS_DIR, 'models')) kwargs['countries'] = pickle_load( path.join(settings.STATS_DIR, 'countries')) return kwargs <file_sep>/cars_cities/views/heatmap.py from os import path from django.views.generic import View from django.conf import settings from django.shortcuts import render from ..utils.files import pickle_load from ..utils.shapefile import Reader import operator ZIPCODE_FIELDS = { 'zipcode_price_avg': 'zip_code_to_car_price', 'zipcode_income_avg': 'zip_code_to_income' } DENSITY_HEATMAP_FIELDS = ('mpg', 'mpg2', 'score') FINE_GRAIN_HEATMAP_FIELDS = { 'car_density': 0.0001 } class Heatmap(View): def get(self, request, cityid): field = request.GET.get('field') variable = request.GET.get('variable', '3') ranking = request.GET.get('ranking', False) context = {} template = 'heatmap2.html' if field in DENSITY_HEATMAP_FIELDS else 'heatmap.html' if field == 'block_price_avg': try: data = pickle_load(path.join(settings.CACHE_DIR, 'block_data'))[int(cityid)] except Exception as e: context['error'] = e context['data'] = data elif field in ZIPCODE_FIELDS: try: context['zipcodes'] = pickle_load(path.join(settings.CACHE_DIR, 'zipcodes/pickled/%s' % cityid)) except IOError as e: context['error'] = e # print context['zipcodes']['94108'] elif field in DENSITY_HEATMAP_FIELDS or field in FINE_GRAIN_HEATMAP_FIELDS: try: data = pickle_load(path.join(settings.LATLNGS_DIR, str(cityid))) except Exception as e: context['error'] = e else: context['data'] = data elif field == 'crime_rates' or field == 'crime_preds': try: context['zipcodes'] = pickle_load(path.join(settings.CACHE_DIR, 'zipcodes/pickled/%s' % cityid)) if field == 'crime_rates': data = pickle_load(path.join(settings.CACHE_DIR, 'crimeVisualization'))[int(cityid)]['crime_rates'] else: data = pickle_load(path.join(settings.CACHE_DIR, 'crimeVisualization'))[int(cityid)]['crime_preds'] except Exception as e: context['error'] = e else: context['crime'] = data for zipcode, d in context['zipcodes'].iteritems(): if zipcode in context['crime']: context['zipcodes'][zipcode]['crime'] = context['crime'][zipcode] #print context['zipcodes'].keys() #print data elif field == 'actual' or field == 'predicted': try: context['zipcodes'] = pickle_load(path.join(settings.CACHE_DIR, 'zipcodes/pickled/%s' % cityid)) data = pickle_load(path.join(settings.STATS_DIR, 'demog')) except Exception as e: context['error'] = e else: if str(cityid) == '153': zipcodes = Reader(path.join(settings.MA_DATA_DIR, 'ma_zipcodes_poly_latlng')) for sr in zipcodes.shapeRecords(): if sr.record[2] == 'Boston': context['zipcodes'][sr.record[1]] = {} for zipcode, d in context['zipcodes'].iteritems(): if zipcode in data and data[zipcode]['census'][int(variable)] != -1: if field == 'actual': context['zipcodes'][zipcode]['demog'] = data[zipcode]['census'][int(variable)] if field == 'predicted': context['zipcodes'][zipcode]['demog'] = data[zipcode]['preds'][int(variable)] if ranking: z_ranking = {} for zipcode in context['zipcodes']: if 'demog' in context['zipcodes'][zipcode]: z_ranking[zipcode] = context['zipcodes'][zipcode]['demog'] z_ranking = sorted(z_ranking.items(), key=operator.itemgetter(1), reverse=True) z_ranking = dict([(x, (idx + 1)) for idx, (x, y) in enumerate(z_ranking)]) for zipcode in context['zipcodes']: if 'demog' in context['zipcodes'][zipcode]: context['zipcodes'][zipcode]['demog'] = z_ranking[zipcode] if not ranking and int(variable) >= 37: for zipcode in context['zipcodes']: if 'demog' in context['zipcodes'][zipcode]: context['zipcodes'][zipcode]['demog'] = round(context['zipcodes'][zipcode]['demog']) #print context['zipcodes'][zipcode]['demog'] else: try: data = Reader(path.join(settings.LATLNGS_SHP_DIR, str(cityid))) except Exception as e: context['error'] = e else: context['data'] = data if 'error' in context: return render(request, 'heatmap.html', context) polygon_path = path.join(settings.SAMPLES_DIR, 'polygons', str(cityid)) polygon = pickle_load(polygon_path) if not self.request.GET.get('show_city_boundary') and 'data' in polygon: polygon.pop('data') context['polygon'] = polygon census_attr = ['Median Age by Sex-Total', 'Median Age by Sex-Male', 'Median Age by Sex-Female', 'Income', 'Housing Units-Total', 'Occupancy Status-Total', 'Occupancy Status-Occupied', 'Occupancy Status-Vacant', 'Median Number of Rooms-Median number of rooms', 'TENURE BY UNITS IN STRUCTURE-Owner-occupied housing units', 'TENURE BY UNITS IN STRUCTURE-Renter-occupied housing units', 'Median household income --total', 'Median household income for units with a mortgage', 'Median household income for units without a mortgage', 'Bedrooms-Total', 'Total Population', 'white', 'black', 'asian', 'less than highschool education', 'highschool', 'some college', 'bachelors', 'grad school', 'aggregate number of vehicles for travel', 'age of own children', 'own children under 6 years', '6-17 years', 'Percentage of Management', 'Percentage of service', 'Percentage of farming', 'Total Race', 'American Indian and Alaska Native alone', 'Native Hawaiian and Other Pacific Islander alone', 'Total Education', 'Median household income', 'housing', 'Aggrevated Assault', 'Burglary', 'Crime Against People', 'Crime Against Property', 'Homicide', 'Larceny', 'Motor Vehicle', 'Robbery', 'Rape', 'Aggrevated Assault (rank)', 'Burglary (rank)', 'Crime Against People (rank)', 'Crime Against Property (rank)', 'Homicide (rank)', 'Larceny (rank)', 'Motor Vehicle (rank)', 'Robbery (rank)', 'Rape (rank)'] if field: print 'Using field ', field context['field'] = field if variable: context['vari'] = int(variable) context['census_attr'] = census_attr[int(variable)] if cityid: context['cityid'] = int(cityid) if ranking: context['ranking'] = ranking # special case boston to use MA data challenge data if str(cityid) == '153' and (field in ZIPCODE_FIELDS): zipcodes = Reader(path.join(settings.MA_DATA_DIR, 'ma_zipcodes_poly_latlng')) attribute_data = pickle_load(path.join(settings.CACHE_DIR, ZIPCODE_FIELDS[field])) zipcode_dict = dict((self.int_to_zipcode(zipcode), attribute) for (zipcode, attribute) in attribute_data) zipcode_data = dict([(sr.record[1], { 'polygon': map(lambda x: list(x[::-1]), sr.shape.points), 'income': zipcode_dict[sr.record[1]], 'price': zipcode_dict[sr.record[1]], }) for sr in zipcodes.shapeRecords() if sr.record[2] == 'Boston' and sr.record[1] != '02163']) context['zipcodes'] = zipcode_data if str(cityid) == '153' and (field == 'crime_rates' or field == 'crime_preds'): zipcodes = Reader(path.join(settings.MA_DATA_DIR, 'ma_zipcodes_poly_latlng')) zipcode_dict = context['crime'] #print zipcode_dict.keys() zipcode_data = dict([(sr.record[1], { 'polygon': map(lambda x: list(x[::-1]), sr.shape.points), 'crime': zipcode_dict[sr.record[1]], }) for sr in zipcodes.shapeRecords() if sr.record[2] == 'Boston' and sr.record[1] in zipcode_dict]) context['zipcodes'] = zipcode_data #print context['zipcodes'].keys() if str(cityid) == '153' and (field == 'actual' or field == 'predicted'): zipcodes = Reader(path.join(settings.MA_DATA_DIR, 'ma_zipcodes_poly_latlng')) #print zipcode_dict.keys() zipcode_data = dict([(sr.record[1], { 'polygon': map(lambda x: list(x[::-1]), sr.shape.points), 'demog': context['zipcodes'][sr.record[1]]['demog'], }) for sr in zipcodes.shapeRecords() if sr.record[2] == 'Boston' and sr.record[1] in context['zipcodes'] and 'demog' in context['zipcodes'][sr.record[1]]]) context['zipcodes'] = zipcode_data context['zipcode_fields'] = ZIPCODE_FIELDS context['density_heatmap_fields'] = DENSITY_HEATMAP_FIELDS return render(request, template, context) def int_to_zipcode(self, n): n = str(n) while len(n) < 5: n = '0' + n return n def getRace(self, x): maxValue = max(x[16:19]) if x[16] == maxValue: return 1 elif x[17] == maxValue: return 2 elif x[18] == maxValue: return 3 def getEdu(self, x): maxValue = max([x[20], x[22], x[23]]) if x[20] == maxValue: return 1 elif x[22] == maxValue: return 2 elif x[23] == maxValue: return 3<file_sep>/cars_cities/management/commands/compute_latlng_data3.py from os import path from django.core.management.base import BaseCommand from django.db import connections from django.conf import settings from ...constants import GEOCARS_DB from ...utils.files import pickle_save, pickle_load QUERY = """ select t1.lat, t1.lng, cc.make, cc.model, cc.submodel, t1.score from all_cars.city_%s t1 join geocars_crawled.control_classes cc on t1.group_id=cc.group_id where cc.make = 'mercedes-benz' """ LAT = 0 LNG = 1 MAKE = 2 MODEL = 3 SUBMODEL = 4 SCORE = 5 class Command(BaseCommand): def handle(self, *args, **kwargs): """ cursor.execute('select distinct cc.make from car_metadata md join geocars_crawled.control_classes cc on md.group_id=cc.group_id') makes = sorted([s[0] for s in cursor.fetchall() if s[0]]) cursor.execute('select distinct cc.model from car_metadata md join geocars_crawled.control_classes cc on md.group_id=cc.group_id') models = sorted([s[0] for s in cursor.fetchall() if s[0]]) cursor.execute('select distinct cc.submodel from car_metadata md join geocars_crawled.control_classes cc on md.group_id=cc.group_id') submodels = sorted([s[0] for s in cursor.fetchall() if s[0]]) """ for city_id in [175] or settings.CITY_IDS: self.compute_latlng_for_city(city_id) def compute_latlng_for_city(self, city_id): self.stdout.write('Loading existing data for %s...' % city_id) latlngs = pickle_load(path.join(settings.LATLNGS_DIR, str(city_id))) self.stdout.write('Querying data for %s...' % city_id) cursor = connections[GEOCARS_DB].cursor() cursor.execute(QUERY % city_id) raw_data = cursor.fetchall() self.stdout.write('Finished querying data for %s, starting pickling...' % city_id) count = 0 for row in raw_data: lat, lng = float(row[LAT]), float(row[LNG]) if (lat, lng) not in latlngs: self.stderr.write('(%s, %s) not found in file! Make sure you run compute_latlng_data2 on %s first!' % (lat, lng, city_id)) continue if 'makes' not in latlngs[(lat, lng)]: latlngs[(lat, lng)]['makes'] = {} latlngs[(lat, lng)]['models'] = {} latlngs[(lat, lng)]['submodels'] = {} latlngs[(lat, lng)]['makes'][row[MAKE]] = row[SCORE] latlngs[(lat, lng)]['models'][row[MODEL]] = row[SCORE] latlngs[(lat, lng)]['submodels'][row[SUBMODEL]] = row[SCORE] count += 1 if count % 3000 == 0: self.stdout.write('Pickled %s rows..' % count) self.stdout.write('Pickling complete for %s, writing data file..' % city_id) pickle_save(latlngs, path.join(settings.LATLNGS_DIR, str(city_id))) self.stdout.write('Finished!') <file_sep>/cars_cities/views/coverage.py from os import path from django.views.generic import TemplateView from django.conf import settings from ..utils.files import pickle_load class Coverage(TemplateView): template_name = 'coverage.html' def get_context_data(self, **kwargs): cities = pickle_load(path.join(settings.STATS_DIR , 'all_cities')) kwargs['cities'] = cities return kwargs <file_sep>/cars_cities/scripts/compute_resamples.py import os import sys import us import xlrd import ftplib import zipfile import datetime from os.path import join, exists try: print 'Initializing ArcGIS python modules...' import arcpy except ImportError: print 'Cannot import arcpy. Abort.' sys.exit(1) else: arcpy.env.overwriteOutput = True print 'ArcGIS initialization complete' from constants import LATLNGS_SHP_DIR, CITY_DIR, RESAMPLE_DIR, \ CITY_BOUNDARY_SHP_DIR, PROJECTION_FILE, CITY_IDS from utils import pickle_load SEGMENT = 18 SEGMENT_SIZE = 10 CITY_IDS_CUSTOM = [115, 226, 129, 183, 203, 144, 197, 121, 132, 117, 229, 175, 192, 122, 196, 198, 268, 139, 234, 278, 146, 232, 161, 147, 195, 298] # 289, 137, CITY_IDS_CUSTOM = [] EXCLUDE = {117, 121, 137, 158, 289, 297} ROADS_SHP_URL = 'ftp://ftp2.census.gov/geo/tiger/TIGER2014/ROADS/' ROADS_TIGER_SHP = 'tl_2014_%s_roads' # set up the fip codes lookup dictionary fips_codes = xlrd.open_workbook(os.path.join(RESAMPLE_DIR, 'fips_codes.xls'))\ .sheet_by_name('cqr_universe_fixedwidth_all') fips_codes_dict = {} for row in xrange(fips_codes.nrows): key = (fips_codes.cell_value(row, 5).lower(), fips_codes.cell_value(row, 1)) fips_code = fips_codes.cell_value(row, 1) + fips_codes.cell_value(row, 2) if key not in fips_codes_dict: fips_codes_dict[key] = {fips_code} else: fips_codes_dict[key].add(fips_code) def export_to_png(shp, output_dir): mxd = arcpy.mapping.MapDocument(join(output_dir, 'test.mxd')) df = arcpy.mapping.ListDataFrames(mxd, '*')[0] shp_layer = arcpy.mapping.Layer(shp) arcpy.mapping.AddLayer(df, shp_layer, 'BOTTOM') arcpy.RefreshActiveView() arcpy.RefreshTOC() def log(msg, *args): print ('[%s] Segment %s: ' % (datetime.datetime.now().strftime('%H:%M:%S'), SEGMENT) + msg) % args def fetch_road_shp(output_dir, fips_set): road_shps = set() for fips in fips_set: roads_shp = ROADS_TIGER_SHP % fips roads_shp_zip = roads_shp + '.zip' roads_shp_zip_path = join(output_dir, roads_shp_zip) roads_shp_path = join(output_dir, roads_shp + '.shp') roads_shp = roads_shp + '.zip' if not exists(roads_shp_zip_path): ftp = ftplib.FTP('ftp2.census.gov') ftp.login() ftp.cwd('geo/tiger/TIGER2014/ROADS/') log('No %s found. Downloading...', roads_shp_zip) try: ftp.retrbinary('RETR ' + roads_shp_zip, open(roads_shp_zip_path, 'wb+').write) except Exception as e: log('FAILED TO FETCH %s: %s', roads_shp_zip, str(e)) continue log('Download complete for %s!', roads_shp_zip) ftp.close() # unzip the files if they haven't already if not exists(roads_shp_path): log('Unzipping %s...', roads_shp_zip) try: zfile = zipfile.ZipFile(roads_shp_zip_path) except Exception as e: log('CANNOT UNZIP! %s', str(e)) continue for name in zfile.namelist(): (_, filename) = os.path.split(name) log('Decompressing %s on %s', filename, output_dir) zfile.extract(name, output_dir) log('Unzip complete') road_shps.add(roads_shp_path) return road_shps def compute_resampling(city_id): log('Computing resample points for %s', city_id) output_dir = join(RESAMPLE_DIR, str(city_id)) if not exists(output_dir): os.makedirs(output_dir) log('Created %s', output_dir) else: log('%s already exists!', output_dir) # find the county fips codes city = pickle_load(join(CITY_DIR, str(city_id))) city_name = city['name'].strip().title() state_name = city['state'].strip().title() log('Looking up state info for %s...', state_name) if 'Utah' in state_name: state_name = 'UT' # weird ass corner case.. state = us.states.lookup(state_name) fips_set = fips_codes_dict[(city['name'].lower(), state.fips)] log('County fips codes for %s, %s: %s', city_name, state.name, fips_set) road_shps = fetch_road_shp(output_dir, fips_set) all_roads_shp = join(output_dir, 'all_roads.shp') if not exists(all_roads_shp): log('Merging %s into %s', list(road_shps), all_roads_shp) arcpy.Merge_management(list(road_shps), all_roads_shp) log('Merge complete') boundary_shp = join(CITY_BOUNDARY_SHP_DIR, 'tl_2014_%s_place.shp' % state.fips) city_boundary_shp = join(output_dir, 'city_boundary.shp') if not exists(city_boundary_shp): log('Fetching city boundary from %s...', boundary_shp) query = "\"NAME\" Like '%%%s%%'" % city['name'].title() log('Using query %s', query) arcpy.MakeFeatureLayer_management(boundary_shp, 'temp', query) arcpy.CopyFeatures_management('temp', city_boundary_shp) log('City boundary %s fetched', city_boundary_shp) all_roads_clipped_shp = join(output_dir, 'all_roads_clipped.shp') if not exists(all_roads_clipped_shp): log('Clipping all_roads into city boundary...') arcpy.Clip_analysis(all_roads_shp, city_boundary_shp, all_roads_clipped_shp) log('Clip complete') all_roads_buffered_shp = join(output_dir, 'all_roads_buffered.shp') if not exists(all_roads_buffered_shp): log('Buffering into %s...', all_roads_buffered_shp) arcpy.Buffer_analysis(all_roads_clipped_shp, all_roads_buffered_shp, '20 Meter') log('Buffering complete') sample_grid_shp = join(output_dir, 'sample_grid.shp') sample_grid_labels_shp = join(output_dir, 'sample_grid_label.shp') if not exists(sample_grid_shp): log('Creating fishnet...') desc = arcpy.Describe(all_roads_buffered_shp) arcpy.CreateFishnet_management( sample_grid_shp, str(desc.extent.lowerLeft), str(desc.extent.XMin) + ' ' + str(desc.extent.YMax + 10), '0.0003', '0.0003', '0', '0', str(desc.extent.upperRight), 'LABELS', '#', 'POLYLINE' ) log('Fishnet creation complete') sample_grid_clipped_shp = join(output_dir, 'sample_grid_clipped.shp') if not exists(sample_grid_clipped_shp): log('Clipping fishnet to buffered roads...') arcpy.Clip_analysis(sample_grid_labels_shp, all_roads_buffered_shp, sample_grid_clipped_shp) log('Clip fishnet to buffered roads complete') ''' sample_grid_erased_shp = join(output_dir, 'sample_grid_erased.shp') if not exists(sample_grid_erased_shp): print 'Projecting using', PROJECTION_FILE # arcpy.DefineProjection_management(sample_grid_clipped_shp, PROJECTION_FILE) print 'Erasing existing samples from fishnet...' samples_shp = join(LATLNGS_SHP_DIR, str(city_id) + '.shp') arcpy.Erase_analysis(sample_grid_clipped_shp, samples_shp, sample_grid_erased_shp, '20 Meter') print 'Erasing existing samples from fishnet complete' ''' log('FINISHED computing resampling for %s: %s, %s', city_id, city_name, state.name) return sample_grid_clipped_shp log('======================END==========================') if __name__ == '__main__': # shp = compute_resampling(196) # export_to_png(shp, join(RESAMPLE_DIR, str(196))) log('=====================BEGIN=========================') for city_id in CITY_IDS_CUSTOM or CITY_IDS[SEGMENT * SEGMENT_SIZE:(SEGMENT + 1) * SEGMENT_SIZE]: if city_id in EXCLUDE: continue compute_resampling(city_id) <file_sep>/cars_cities/views/__init__.py from home import Home from aggregate import AggregateStats from stats import Stats from samples import Samples from hotspots import Hotspots from results import Results from heatmap import Heatmap from coverage import Coverage from countryheatmap import CountryHeatmap from customzip import CustomZip from voting import Voting <file_sep>/cars_cities/management/commands/compute_latlng_data.py from os import path from collections import defaultdict from django.core.management.base import BaseCommand from django.db import connections from django.conf import settings from ...constants import ALL_CARS_DB, GEOCARS_DB from ...utils.files import pickle_save, pickle_load class Command(BaseCommand): def handle(self, *args, **kwargs): cursor = connections[GEOCARS_DB].cursor() cursor.execute('select * from car_metadata') group_raw_data = cursor.fetchall() groups = {} for row in group_raw_data: groups[row[0]] = { 'price': row[1], 'fuel_type': row[2], 'mpg_highway': row[3], 'mpg_city': row[4], 'hybrid': row[5], 'electric': row[6], 'country': row[7], 'is_foreign': row[8], 'price_bracket': row[9], 'fine_price_bracket': row[10], 'tg_price_bracket': row[11], 'country_id': row[12], 'make_id': row[13], 'submodel_id': row[14] } for cityid in args or settings.CITY_IDS: if path.exists(path.join(settings.LATLNGS_DIR, str(cityid))): self.stdout.write('City %s already has latlngs, skipping' % cityid) continue self.stdout.write('Checking if city %s data file has mpg_weighted...' % cityid) try: data = pickle_load(path.join(settings.LATLNGS_DIR, str(cityid))) except: self.stderr.write('Cannot load data file... preparing to query') else: values = data.values() if values and 'mpg_weighted' in values[0]: self.stdout.write('Already has it. Skipping to next') continue self.compute_latlngs_for_city(str(cityid), groups) def compute_latlngs_for_city(self, city_id, groups): self.stdout.write('Querying data for %s...' % city_id) cursor = connections[ALL_CARS_DB].cursor() cursor.execute('select lat, lng, group_id, score from city_%s' % city_id) raw_data = cursor.fetchall() cursor.close() self.stdout.write('Query complete for %s, starting transform' % city_id) latlngs = {} total = len(raw_data) count = 0 for lat, lng, group_id, score in raw_data: count += 1 if count % 10000 == 0: self.stdout.write('Processed %s of %s rows' % (count, total)) if (lat, lng) not in latlngs: latlngs[(lat, lng)] = { 'price': 0.0, 'mpg_highway': 0.0, 'mpg_city': 0.0, 'hybrid': 0.0, 'electric': 0.0, 'is_foreign': 0.0, 'total_score': 0.0, 'mpg_weighted': 0.0, } group_data = groups[group_id] latlngs[(lat, lng)]['total_score'] += score latlngs[(lat, lng)]['price'] += group_data['price'] * score latlngs[(lat, lng)]['mpg_highway'] += group_data['mpg_highway'] * score latlngs[(lat, lng)]['mpg_city'] += group_data['mpg_city'] * score latlngs[(lat, lng)]['hybrid'] += group_data['hybrid'] * score latlngs[(lat, lng)]['electric'] += group_data['electric'] * score latlngs[(lat, lng)]['is_foreign'] += group_data['is_foreign'] * score latlngs[(lat, lng)]['mpg_weighted'] += float(score) / group_data['mpg_city'] # for field in ['fuel_type', 'country', 'price_bracket', 'fine_price_bracket', 'tg_price_bracket', 'country_id', 'make_id', 'submodel_id']: # self.add_counter(latlngs[(lat, lng)], field, group_data[field], score) for (lat, lng) in latlngs: latlngs[(lat, lng)]['price'] /= latlngs[(lat, lng)]['total_score'] latlngs[(lat, lng)]['mpg_highway'] /= latlngs[(lat, lng)]['total_score'] latlngs[(lat, lng)]['mpg_city'] /= latlngs[(lat, lng)]['total_score'] self.stdout.write('Transform complete for %s, writing data file' % city_id) pickle_save(latlngs, path.join(settings.LATLNGS_DIR, str(city_id))) def add_counter(self, latlngs, name, value, score): if name not in latlngs: latlngs[name] = {} if value not in latlngs[name]: latlngs[name][value] = 0.0 latlngs[name][value] += score <file_sep>/cars_cities/scripts/block_fips_to_zcta.py import csv from os import listdir from shutil import copyfile from os.path import join, exists import shapefile from constants import CACHE_DIR, RESAMPLE_DIR, CITY_IDS def shp_to_csv(filename, city_id): """ Converts sampling CSV (lat, long) into shapefiles """ print 'Processing shapefile %s...' % filename reader = shapefile.Reader(filename) count = 0 for shape in reader.shapes(): writer.writerow(shape.points[0]) count += 1 if count % 10000 == 0: print 'Written %s rows' % count print 'FINISHED' if __name__ == '__main__': filename = join(CACHE_DIR, 'block_fips_to_zcta.csv') writer = csv.writer(open(filename + '.csv', 'wb+'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) for f in listdir('D:\\topological_faces'): if f.endswith('.shp'): reader = shapefile.Reader('D:\\topological_faces\\' + f) print f for record in reader.records(): state = record[1] county = record[2] tract = record[3] block = record[5] zcta5 = record[7] writer.writerow([state, county, tract, block, zcta5]) print 'done' <file_sep>/cars_cities/scripts/utils.py import logging log = logging.getLogger(__name__) import os import errno import cPickle as pickle def ensure_dirs(filename, *args, **kwargs): if not os.path.exists(filename): # create all intermediate dirs if they don't exist try: os.makedirs(os.path.dirname(os.path.realpath(filename))) except OSError as exception: # to address rare race condition between the os.path.exists # and the os.makedirs calls if exception.errno != errno.EEXIST: raise def open_safe(filename, *args, **kwargs): """ Checks to see if the filename intermediate dirs exist before returning a python open() handle on it. Example: f = open_safe('/tmp/a/b/c/d/e', 'wb+') """ if not os.path.exists(filename): # create all intermediate dirs if they don't exist try: os.makedirs(os.path.dirname(os.path.realpath(filename))) except OSError as exception: # to address rare race condition between the os.path.exists # and the os.makedirs calls if exception.errno != errno.EEXIST: raise return open(filename, *args, **kwargs) def pickle_save(obj, filename): try: pickle.dump(obj, open_safe(filename, 'wb+')) except: log.exception('Exception pickle saving to %s', filename) def pickle_load(filename): try: return pickle.load(open_safe(filename, 'rb')) except: raise <file_sep>/cars_cities/scripts/populate_city_areas.py from os import path import sys import us import cPickle as pickle from constants import STATS_DIR, CITY_IDS, CITY_DIR, GROUPS_DIR from cars_cities.models import City with open(path.join(STATS_DIR, 'city_areas.txt')) as f: lines = f.readlines() data = [] for line in lines: line = filter(lambda s: s, line.strip().split(' ')) line[0] = line[0].replace('City', '').replace('city,', '').replace('town', '') line[0] = line[0].replace('(balance),', '').replace('CDP', '').replace(',','') line[0] = line[0].replace('-Richmond County', '').replace('St.', 'saint') line[0] = line[0].replace('-Davidson', '').replace('St.', 'saint') line[0] = line[0].strip().lower() line[1] = line[1].replace(',', '') city = ' '.join(line[0].split(' ')[:-1]) state = line[0].split(' ')[-1] data.append([city, state, float(line[1])]) for cityid in CITY_IDS: city = City(str(cityid)) #print 'Processing %s, %s' % (city.name, city.state) name = city.name.replace('city', '').replace('st.', 'saint').lower().strip() state = us.states.lookup(city.state).abbr.lower() for d in data: if d[0].lower().strip() == name and d[1] == state: print 'MATCHED', city.name, city.state city.area = d[2] city.save_state() break else: print 'DID NOT MATCH', city.name, city.state <file_sep>/cars_cities/settings/production.py from _base import * for name, db in DATABASES.iteritems(): if db.get('HOST'): db['HOST'] = 'localhost' STATIC_URL = '/static/' DEBUG = True <file_sep>/cars_cities/scripts/MAData.py import sys import os from mysql_yilunw import connect_to_db from scipy import stats #from numpy import * # If the package has been installed correctly, this should work: import Gnuplot, Gnuplot.funcutils import cPickle as pickle import urllib2 from sklearn.linear_model import LogisticRegression import numpy as np def get_vars_list(): vars=open('%s_variables.txt'% 'acs').readlines() var_keys=[] for v in vars: var_keys.append(v.split(',')[0]) return var_keys def follow_link(br,link): print '......link=%s..................'%link tried=0 connected=False html='' num_to_try=10 while not connected: try: html=br.DownloadURL(link) connected = True # if line above fails, this is never executed except Exception as e: #catch all exceptions print 'Error in follow_link: %s trying again' %e tried += 1 if tried > num_to_try: print 'cannot download from link: %s' %link return return html cities=['boston','springfield','worcester'] muni_ids=[35,281,348] city_ids=[153,300,154] zip_income = [] fp = open("income.csv", "r") for line in fp: lineData = line.split(",") zip_income.append(int(lineData[0])) fp.close() if not os.path.isfile('cars_data'): db_name='geocars' db = connect_to_db(db_name) cursor = db.cursor() make_query='select group_id, price, mpg_highway, mpg_city, hybrid, electric, country, is_foreign from car_metadata' cursor.execute(make_query) cursor_data = cursor.fetchall() car_basic = {} for group_id, price, mpg_highway, mpg_city, hybrid, electric, country, is_foreign in cursor_data: thisID = int(group_id) if price == None: price = 0 if mpg_highway == None: mpg_highway = 0 if mpg_city == None: mpg_city = 0 car_basic[thisID] = (int(price), int(mpg_highway), int(mpg_city), int(hybrid), int(electric), country, int(is_foreign)) db_name='geocars_crawled' db = connect_to_db(db_name) cursor = db.cursor() make_query='select group_id, submodel, years from control_classes' cursor.execute(make_query) cursor_data = cursor.fetchall() car_extended = {} for group_id, submodel, years in cursor_data: thisID = int(group_id) years = years[0:4] if not years[0].isdigit(): years = 0 car_extended[thisID] = (submodel, int(years)) db_name='boston_cars' db = connect_to_db(db_name) cursor = db.cursor() cars_data = [] for zip_code in zip_income: if int(zip_code) != 0: print zip_code make_query='select group_id from ma_detected_cars where zipcode=%d' % int(zip_code) cursor.execute(make_query) cursor_data = cursor.fetchall() thisList = [0.0] * 34 for group_id in cursor_data: group_id = int(group_id[0]) basic = car_basic[group_id] extended = car_extended[group_id] thisList[0] += 1 thisList[2] += basic[0] thisList[4] += basic[1] thisList[5] += basic[2] thisList[6] += basic[3] thisList[7] += basic[4] if basic[5] == 'germany': thisList[8] += 1 elif basic[5] == 'usa': thisList[9] += 1 elif basic[5] == 'south korea': thisList[10] += 1 elif basic[5] == 'sweden': thisList[11] += 1 elif basic[5] == 'japan': thisList[12] += 1 elif basic[5] == 'italy': thisList[13] += 1 elif basic[5] == 'netherlands': thisList[14] += 1 elif basic[5] == 'england': thisList[15] += 1 elif basic[5] == 'france': thisList[16] += 1 thisList[17] += basic[6] if extended[0] == 'coupe': thisList[18] += 1 elif extended[0] == 'minivan': thisList[19] += 1 elif extended[0] == 'sedan': thisList[20] += 1 elif extended[0] == 'hatchback': thisList[21] += 1 elif extended[0] == 'convertible': thisList[22] += 1 elif extended[0] == 'regular cab': thisList[23] += 1 elif extended[0] == 'extended cab': thisList[24] += 1 elif extended[0] == 'crew cab': thisList[25] += 1 elif extended[0] == 'suv': thisList[26] += 1 elif extended[0] == 'wagon': thisList[27] += 1 elif extended[0] == 'van': thisList[28] += 1 if extended[1] <= 1994 and extended[1] >= 1990: thisList[29] += 1 elif extended[1] <= 1999: thisList[30] += 1 elif extended[1] <= 2004: thisList[31] += 1 elif extended[1] <= 2009: thisList[32] += 1 elif extended[1] >= 2010: thisList[33] += 1 for i in range(2, 34): if i != 3: thisList[i] /= thisList[0] if thisList[0] < 100: print "sdfsdfsdfsdfsdfd %d" % zip_code cars_data.append(thisList) pickle.dump( cars_data, open( "cars_data", "wb" ) ) else: cars_data = pickle.load( open( "cars_data", "rb" ) ) if not os.path.isfile('census_data'): census_data = [] URL_BASE='http://api.census.gov/data/2012/acs5?key=' API_KEY='<KEY>' BASE='%s%s&get='%(URL_BASE,API_KEY) vars_list=get_vars_list() vars_len = len(vars_list) vars=",".join(vars_list) for zip_code in zip_income: thisList = [0.0] * vars_len print "census: %d"%zip_code query='%s%s&for=zip+code+tabulation+area:%s'%(BASE,vars,zip_code) thisLine = urllib2.urlopen(query).read() thisData = thisLine.split('\n')[1].replace('[','').replace(']','').split(',') for i in range(vars_len): if thisData[i] == 'null': thisList[i] = 0.0 else: thisList[i] = float(thisData[i][1:-1]) census_data.append( thisList) pickle.dump( census_data, open( "census_data", "wb" ) ) else: census_data = pickle.load( open( "census_data", "rb" ) ) cars_data = np.matrix(cars_data) census_data = np.matrix(census_data) lr = LogisticRegression(C=1.0, penalty='l2') lr.fit(cars_data[0:50,:], np.ravel(census_data[0:50, 11])) #print lr.score(cars_data[51:72, :], np.ravel(census_data[51:72, 11])) print cars_data[:, 2] #print np.ravel(census_data[51:72, 11]) #print lr.predict(cars_data[51:72, :]) ''' total_data = [] our_data = [] for item in cars_data.iteritems(): zip_code = item[0] thisList = item[1] if thisList[0] >= 100: total_data.append(0) ###################################### our_data.append(thisList[2]) g = Gnuplot.Gnuplot(debug=1) #################################### our_data_column = "price" output_file = our_data_column + ".png" g.reset() d = Gnuplot.Data(our_data, total_data) g('set terminal png') g('set output \'' + output_file+'\'') g.title(our_data_column + " corr:" + str(stats.pearsonr(our_data, total_data)[0])) g.xlabel(our_data_column) g.ylabel('income') g.plot(d) '''<file_sep>/cars_cities/models/__init__.py from city import * <file_sep>/cars_cities/views/customzip.py from os import path from django.views.generic import View from django.conf import settings from django.shortcuts import render from ..utils.files import pickle_load from ..utils.shapefile import Reader class CustomZip(View): def get(self, request): cityid = int(request.GET.get('cityid')) fname = request.GET.get('fname') context = {} template = 'customzip.html' try: zip_dict = {} poly_dict = pickle_load(path.join(settings.CACHE_DIR, 'zipcodes/pickled/%d' % cityid)) if fname.endswith('pkl'): # Handle pickle files # Get dictionary of zipcode -> color for zipcodes in the city custom_data = pickle_load(path.join(settings.CACHE_DIR, 'zipcodes', 'custom', fname)) custom_dict = custom_data['zip_map'] # {cityid: {zipcode(%05d):(r,g,b)}} attr_name = custom_data['att_name'] elif fname.endswith('.txt'): # Handle text files custom_dict = {cityid:{}} with open(path.join(settings.CACHE_DIR, 'zipcodes', 'custom', fname), 'r') as in_file: line = in_file.readline() line = line.strip().split(',') for i in range(0, len(line), 2): if line[i] == 'att_name': attr_name = line[i+1] for line in in_file: line = line.strip().split(',') # city, zipcode, r, g, b line_cityid = int(line[0]) if line_cityid == cityid: zipcode = '%05d' % int(line[1]) r = int(line[2]) g = int(line[3]) b = int(line[4]) custom_dict[cityid][zipcode] = (r,g,b) for zipcode in poly_dict: if zipcode in custom_dict[cityid]: rgb = custom_dict[cityid][zipcode] zip_dict[zipcode] = {'polygon':poly_dict[zipcode]['polygon'], 'r':rgb[0], 'g':rgb[1], 'b':rgb[2]} elif int(zipcode) in custom_dict[cityid]: rgb = custom_dict[cityid][int(zipcode)] zip_dict[zipcode] = {'polygon':poly_dict[zipcode]['polygon'], 'r':rgb[0], 'g':rgb[1], 'b':rgb[2]} context['var_name'] = attr_name context['zipcodes'] = zip_dict except Exception as e: context['error'] = e return render(request, template, context) polygon_path = path.join(settings.SAMPLES_DIR, 'polygons', str(cityid)) polygon = pickle_load(polygon_path) polygon.pop('data') context['polygon'] = polygon return render(request, template, context) <file_sep>/cars_cities/scripts/compute_convex_hull.py from os import path import sys try: import arcpy except ImportError: print 'Cannot import arcpy. Abort.' sys.exit(1) from constants import SHAPEFILE_DIR, CONVEXHULL_DIR, CITY_IDS, PROJECTION_FILE AREA_COMPUTE_EXPRESSION = '{0}'.format('!SHAPE.area@SQUAREMILES!') def compute_convex_hull(cityid): input_path = path.join(SHAPEFILE_DIR, '%s.shp' % cityid) output_path = path.join(CONVEXHULL_DIR, '%s.shp' % cityid) print 'Computing convex hull for city %s' % cityid arcpy.MinimumBoundingGeometry_management(input_path, output_path, 'CONVEX_HULL', 'ALL') arcpy.DefineProjection_management(output_path, PROJECTION_FILE) arcpy.AddField_management(output_path, 'area', 'Double') arcpy.CalculateField_management(output_path, 'area', AREA_COMPUTE_EXPRESSION, 'PYTHON', ) print 'DONE!' if __name__=='__main__': for cityid in CITY_IDS: compute_convex_hull(cityid) <file_sep>/cars_cities/management/commands/convert_polygon_shp.py from os import path from django.core.management.base import BaseCommand from django.db import connections from django.conf import settings import shapefile from ...constants import GEO_DB from ...utils.files import pickle_save class Command(BaseCommand): """ Converts shp polygons files into list of [x,y] python structs for simpler reading """ def handle(self, *args, **kwargs): cursor = connections[GEO_DB].cursor() cursor.execute('SELECT cityid, cityname FROM cities') city_data_raw = cursor.fetchall() cursor.close() city_data = {} for cityid, cityname in city_data_raw: city_data[cityid] = cityname.title() self.stdout.write('%d cities queried from GEO database' % len(city_data)) self.stdout.write('%d cities sample csv files found in cache' % len(settings.CITY_IDS)) for cityid in settings.CITY_IDS: self.stdout.write('Reading shapefile for %s' % cityid) shp_path = path.join(settings.CONVEXHULL_DIR, str(cityid)) reader = shapefile.Reader(shp_path) polygon = reader.shapes()[0] points = [[y, x] for [x, y] in polygon.points] # the long lat are flipped center = [0.0, 0.0] for point in points: center[0] += point[0] center[1] += point[1] center[0] /= float(len(points)) center[1] /= float(len(points)) area = float(reader.records()[0][1]) self.stdout.write('Polygon area is %f sq miles' % area) data = { 'name': city_data.get(cityid, 'unknown city'), 'center': center, 'data': points, 'area': area } pickle_save(data, path.join(settings.POLYGONS_DIR, str(cityid))) self.stdout.write('Polygon file saved for %s' % cityid) self.stdout.write('FINISHED') <file_sep>/cars_cities/scripts/latlng_data_to_shp.py import sys import csv from os import path try: import arcpy except ImportError: print 'Cannot import arcpy. Will not adjust projections.' projection = False else: projection = True import shapefile from constants import CITY_IDS, LATLNGS_DIR, LATLNGS_SHP_DIR, PROJECTION_FILE, MAKES from utils import pickle_load override = True CUSTOM_CITIES = {} def latlng_to_shp(cityid): """ Converts sampling CSV (lat, long) into shapefiles """ if not override and path.isfile(path.join(LATLNGS_SHP_DIR, str(cityid) + '.shp')): print '%s.shp already exists. Skipping' % cityid return print 'Processing latlng data for city %s...' % cityid data = pickle_load(path.join(LATLNGS_DIR, str(cityid))) print 'Data loaded' writer = shapefile.Writer(shapefile.POINT) writer.autoBalance = 1 writer.field('price', 'N') for make in MAKES: writer.field(make[:10], 'N', 19, 9) count = 0 for (lat, lng) in data: writer.point(lng, lat) record = { 'price': data[(lat, lng)]['price'] } for make in MAKES: if 'makes' in data[(lat, lng)]: record[make[:10]] = str(data[(lat, lng)]['makes'].get(make, 0.0))[:19] else: record[make[:10]] = 0.0 writer.record(**record) count += 1 if (count % 5000) == 0: print '%s entries copied' % count shp_path = path.join(LATLNGS_SHP_DIR, str(cityid)) print 'Writing shapefile...' writer.save(shp_path) print 'Defining projection...' if projection: arcpy.DefineProjection_management(shp_path + '.shp', PROJECTION_FILE) print 'Written shapefile to %s' % shp_path if __name__ == '__main__': for cityid in CUSTOM_CITIES or CITY_IDS: try: latlng_to_shp(cityid) except Exception as e: print 'Cannot process', cityid, str(e) raise <file_sep>/cars_cities/scripts/compute_hotspots.py import os, sys try: print 'Initializing ArcGIS python modules...' import arcpy except ImportError: print 'Cannot import arcpy. Abort.' sys.exit(1) else: arcpy.env.overwriteOutput = True print 'ArcGIS initialization complete' from constants import LATLNGS_SHP_DIR, HOTSPOTS_DIR, CITY_IDS # Houston 197 # Reno 283 # Seattle 205 # SF 293 CITY_IDS_CUSTOM = {} def compute_hotspots(city_id): print 'Computing hotspots for', city_id shpfile = os.path.join(LATLNGS_SHP_DIR, str(city_id) + '.shp') output = os.path.join(HOTSPOTS_DIR, str(city_id) + '_hotspots.shp') arcpy.OptimizedHotSpotAnalysis_stats(shpfile, output, 'price') print 'FINISHED %s!' % city_id if __name__ == '__main__': for cityid in CITY_IDS_CUSTOM or reversed(CITY_IDS): try: compute_hotspots(cityid) except Exception as e: print 'Cannot compute hotspot for %s: %s' % (cityid, str(e)) <file_sep>/cars_cities/views/home.py from os import path from django.views.generic import TemplateView from django.conf import settings from ..utils.files import pickle_load class Home(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): cities = pickle_load(path.join(settings.STATS_DIR , 'all_cities')) aggregate = pickle_load(path.join(settings.STATS_DIR, 'aggregate')) kwargs['cities'] = cities kwargs['aggregate'] = aggregate return kwargs <file_sep>/cars_cities/scripts/cleanup_hotspots.py import os, sys import shapefile from constants import HOTSPOTS_DIR, CITY_IDS CITY_IDS_CUSTOM = {113} def cleanup_hotspots(city_id): print 'Cleaning up hotspots for', city_id reader = shapefile.Reader(os.path.join(HOTSPOTS_DIR, str(city_id) + '_hotspots.shp')) hotspots = shapefile.Editor(shapefile=os.path.join(HOTSPOTS_DIR, str(city_id) + '_hotspots.shp')) print reader.fields num_deleted = 0 for index, sr in enumerate(reader.shapeRecords()): if float(sr.record[1]) <= 0: print 'Deleting %d' % index try: hotspots.delete(index - num_deleted) except IndexError: print 'Cannot delete %d due to IndexError' % index else: num_deleted += 1 else: print float(sr.record[2]) #hotspots.save(os.path.join(HOTSPOTS_DIR, str(city_id) + '_cleaned.shp')) print 'FINISHED %s!' % city_id if __name__ == '__main__': for cityid in CITY_IDS_CUSTOM or CITY_IDS: try: cleanup_hotspots(cityid) except Exception as e: print 'Cannot cleanup hotspot for %s: %s' % (cityid, str(e)) <file_sep>/cars_cities/scripts/compute_moran.py import os, sys try: print 'Initializing ArcGIS python modules...' import arcpy except ImportError: print 'Cannot import arcpy. Abort.' sys.exit(1) else: arcpy.env.overwriteOutput = True print 'ArcGIS initialization complete' from constants import LATLNGS_SHP_DIR, CITY_DIR, CITY_IDS, CACHE_DIR from utils import pickle_save, pickle_load # Houston 197 # Reno 283 # Seattle 205 # SF 293 CITY_IDS_CUSTOM = {} def compute_hotspots(city_id): print 'Computing Moran index for', city_id shpfile = os.path.join(LATLNGS_SHP_DIR, str(city_id) + '.shp') moran_index = arcpy.SpatialAutocorrelation_stats(shpfile, 'price', 'NO_REPORT', 'INVERSE_DISTANCE_SQUARED', 'EUCLIDEAN DISTANCE', 'NONE', '100', '#') print 'FINISHED %s!' % city_id return moran_index if __name__ == '__main__': try: moran_indices = pickle_load(os.path.join(CACHE_DIR, 'moran_indices')) except Exception as e: print 'Error loading moran_indices: %r, creating a new one' % e moran_indices = {} for cityid in CITY_IDS_CUSTOM or CITY_IDS: if cityid in moran_indices: print '%s already exists, skipping' % cityid continue try: moran_indices[cityid] = compute_hotspots(cityid).getOutput(0) except Exception as e: print 'Cannot compute Morans I for %s: %s' % (cityid, str(e)) else: pickle_save(moran_indices, os.path.join(CACHE_DIR, 'moran_indices')) <file_sep>/cars_cities/management/commands/compute_sample_csv.py import csv from collections import defaultdict from django.core.management.base import BaseCommand from django.db import connections from django.conf import settings from ...constants import GEO_DB from ...utils.files import ensure_dirs class Command(BaseCommand): def handle(self, *args, **kwargs): self.stdout.write('Querying for sample data...') cursor = connections[GEO_DB].cursor() cursor.execute('SELECT cityid, lat, lng FROM samples WHERE sampled=1') raw_data = cursor.fetchall() cursor.close() self.stdout.write('Finished querying for sample data!') data = defaultdict(set) for cityid, lat, lng in raw_data: data[cityid].add((lat, lng)) for cityid in data: self.stdout.write('Writing csv for city %s...' % cityid) filename = settings.SAMPLES_DIR + '/%s.csv' % cityid ensure_dirs(filename) with open(filename, 'wb') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) for item in data[cityid]: writer.writerow(item) <file_sep>/cars_cities/management/commands/compute_cities.py from django.core.management.base import BaseCommand from django.db import connections from ...constants import ALL_CARS_DB, GEO_DB from ...models import City class Command(BaseCommand): def handle(self, *args, **kwargs): cursor = connections[ALL_CARS_DB].cursor() cursor.execute('SHOW TABLES') tables = cursor.fetchall() cursor.close() samples = {} if 'get_sample_count' in args: self.stdout.write('Querying for sample count...') cursor = connections[GEO_DB].cursor() cursor.execute('SELECT cityid, COUNT(*) from samples where sampled=1 group by cityid') samples = dict(cursor.fetchall()) cursor.close() self.stdout.write('Sample query complete') for (table, ) in tables: split = table.split('_') if len(split) != 2: continue city_id = split[1] self.stdout.write('Computing city %s...' % city_id) city_id = int(city_id) city = City(city_id) if samples and city_id in samples: city.samples = samples[city_id] city.save_state() self.stdout.write('City %s state updated with samples' % city_id) <file_sep>/cars_cities/scripts/compute_all_zipcode_data.py from os import path import sys import shapefile from constants import CACHE_DIR, SHAPEFILE_DIR, CONVEXHULL_DIR, CITY_IDS, PROJECTION_FILE from utils import pickle_load, pickle_save def format_zipcode(zipcode): zipcode = str(zipcode) while len(zipcode) < 5: zipcode = '0' + zipcode return zipcode if __name__=='__main__': all_cars_data = pickle_load(path.join(CACHE_DIR, 'all_cars_data')) all_census_data = pickle_load(path.join(CACHE_DIR, 'all_census_data')) reader = shapefile.Reader(path.join(CACHE_DIR, 'zipcodes/zip_poly/zip_poly')) zipcodeList = {} for key, data in all_cars_data.iteritems(): zipcode = data[94] cityid = int(data[95]) formatted_zipcode = format_zipcode(zipcode) if formatted_zipcode not in zipcodeList: zipcodeList[formatted_zipcode] = 1 print 'Reading polygon file...' zip_poly = {} for sr in reader.shapeRecords(): if sr.record[0] in zipcodeList: polygon = sr.shape.points zip_poly[str(sr.record[0])] = map(lambda x: [x[1], x[0]], polygon) print 'Finished reading polygon file!' print 'Writing city zipcodes file' city_zipcode_data = {} for key, data in all_cars_data.iteritems(): zipcode = data[94] cityid = int(data[95]) formatted_zipcode = format_zipcode(zipcode) if (formatted_zipcode not in city_zipcode_data) and (formatted_zipcode in zip_poly): city_zipcode_data[formatted_zipcode] = {} poly = zip_poly[formatted_zipcode] city_zipcode_data[formatted_zipcode]['polygon'] = poly print "adding %s" % formatted_zipcode else: pass print 'Saving pickle files' pickle_save(city_zipcode_data, path.join(CACHE_DIR, 'zipcodes/pickled/allCities')) print 'Finished!'
b74596545d9330e414353f48542be5e27eb1842b
[ "Python", "Text" ]
53
Python
simonyilunw/cars_cities
49e4c522d44f9a21fa76687fd83366dec3f12b84
e8b5b630ec84c2edc6c5687cd40ab52f01d77c37
refs/heads/master
<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-slider-menu', templateUrl: './slider-menu.component.html', styleUrls: ['./slider-menu.component.scss'] }) export class SliderMenuComponent implements OnInit { @Input() showMenu: boolean; @Output() menuActive: EventEmitter<any> = new EventEmitter(); constructor() { } ngOnInit() { } public toggleMenu(): void { this.showMenu = !this.showMenu; this.menuActive.emit(); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { MatIconModule, MatButtonModule, MatButtonToggleModule, MatGridListModule, MatCardModule, MatRippleModule } from '@angular/material'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FlexLayoutModule } from '@angular/flex-layout'; import { SliderMenuComponent } from './slider-menu/slider-menu.component'; import { AppHeaderComponent } from './app-header/app-header.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { BookDetailComponent } from './book-detail/book-detail.component'; import { BookSearchComponent } from './book-search/book-search.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; @NgModule({ declarations: [ AppComponent, SliderMenuComponent, AppHeaderComponent, DashboardComponent, BookDetailComponent, BookSearchComponent, PageNotFoundComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, FlexLayoutModule, MatIconModule, MatButtonModule, MatButtonToggleModule, MatGridListModule, MatCardModule, MatRippleModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
cab0f64db820044f44f4b29fd497b4595f289c27
[ "TypeScript" ]
2
TypeScript
dlosh/github-showcase
90229df2baf077e8c1cb9f263194573a24c611c8
ec09b4c2fcb0470d49b6c4dca23f81fede6fbe05
refs/heads/master
<file_sep>class BlackJack def initialize nombre @nombre = nombre @pregunta = "" @opciones = "" @preguntas = [ "Escenario: Crupier tiene una carta tapada y una carta 5. Jugador tiene dos cartas, 8 y 2.", "Escenario: Crupier tiene una carta tapada y una carta 10, Jugador tiene dos cartas 8 y 5", "Escenario: Crupier tiene carta tapada y una carta Az, Jugador tiene un 8 y un 7" ] @opciones = [ ["Retirar apuesta", "Doblar apuesta", "Pedir carta"], ["Retirar apuesta", "Doblar apuesta", "Pedir carta hasta 17"], ["Retirar apuesta", "Doblar apuesta", "Pedir carta", "Pagar seguro"] ] @correctas = [1,0,3] # @pregunta = 0 # @opcion = 1 # @correcta = 1 end def mostrarNombre if @nombre == "" return "Error: Su nombre no puede ser vacio" end @nombre end def crearPregunta @i = rand(@preguntas.length) @pregunta = @preguntas[@i] @opcion = @opciones[@i] @correcta = @correctas[@i] end def verPregunta @pregunta end def verOpciones @opcion end def esCorrecta(seleccionado) if seleccionado.to_s == @correcta.to_s return 'Es correcto' else return 'Es incorrecto' end end end<file_sep>require 'sinatra' require './config' require './lib/BlackJack' get '/' do erb :index end post '/tecnicas' do session['bj'] = BlackJack.new params['nombre'] if session['bj'].mostrarNombre.include? "Error" session['mensaje'] = session['bj'].mostrarNombre erb :paginamensaje else erb :tecnicas end end post '/jugar' do session['resultado']="" session['bj'].crearPregunta erb :preguntasjuego end post '/validar' do session['resultado']="" session['resultado']= session['bj'].esCorrecta(params['opcion']) erb :preguntasjuego end<file_sep>require "./lib/BlackJack" describe BlackJack do it "Debe guardar el nombre del jugador" do #arrange bj = BlackJack.new "Juan" #act result = bj.mostrarNombre #assert expect(result).to eq "Juan" end it "El nombre no debe estar vacio" do #arrange bj = BlackJack.new "" #act result = bj.mostrarNombre #assert expect(result).to eq "Error: Su nombre no puede ser vacio" end it "Debo ver una pregunta" do #arrange bj = BlackJack.new "Juan" #act bj.crearPregunta result = bj.verPregunta #assert expect(result).not_to be_empty end it "Debo ver opciones" do #arrange bj = BlackJack.new "Juan" #act bj.crearPregunta result = bj.verOpciones #assert expect(result).not_to be_empty end end<file_sep> Given(/^que inicie el juego$/) do visit '/' end Then(/^debo ver "([^"]*)"$/) do |text| expect(page.body).to match /#{text}/m end When(/^ingrese el nombre "([^"]*)"$/) do |nombre| fill_in("nombre", :with => nombre) end When(/^lo configuro$/) do click_button("Enviar") end When(/^hago click en "([^"]*)"$/) do |textoboton| click_button("#{textoboton}") end
5a41532fc0b11078c2995f96d006ed2399f9aa21
[ "Ruby" ]
4
Ruby
AlexaMateus/blackjack
cf0714a09e33943a410151acb8dab3e0afab4a08
76decdde7ba2b7f1fd480ce0d07ad996733d27d0
refs/heads/master
<file_sep>// The timer updates only the required fields, and does not update all the components of the timer, at the interval of one second. var reset=0; var myTimer = 0; var message = function() { // Display end message, after the timer is over document.body.innerHTML = "<br/><br/><br/><br/> <center><h1> Welcome to Outer Space !! </center></h1>"; } var timer = function() { // Main timer function // Checks for the special cases in the timer if (document.getElementById('seconds').innerHTML === '0') { if( Number(document.getElementById('minutes').innerHTML) > 0) { // Decrement number of minutes by 1 document.getElementById('minutes').innerHTML -= 1; document.getElementById('seconds').innerHTML = '59'; return; } if( Number(document.getElementById('minutes').innerHTML) === 0 && Number(document.getElementById('hours').innerHTML) > 0) { // Decrement number of hours by 1 document.getElementById('minutes').innerHTML = '59'; document.getElementById('seconds').innerHTML = '59'; document.getElementById('hours').innerHTML -= 1; return; } if( Number(document.getElementById('hours').innerHTML) === 0 && Number(document.getElementById('days').innerHTML) > 0) { // Decrement number of days by 1 document.getElementById('hours').innerHTML = '23'; document.getElementById('seconds').innerHTML = '59'; document.getElementById('minutes').innerHTML = '59'; document.getElementById('days').innerHTML -= 1; return; } // Countdown over console.log("Timer Over !!") // Print a message to the console document.getElementById('whole').style.visibility = 'hidden'; document.body.style.backgroundImage = "url('outerspace.jpg')"; clearInterval(myTimer); // Stop the 'timer' setTimeout(message, 2000); // Display a message after 2 seconds of background change } else // If all the above conditions fail, then decrement timer by 1 second document.getElementById('seconds').innerHTML -= 1; }; var setNow = function() { stopTimer(); setToZero(); // Set all timer elements to 0 var now = new Date(); var dd = now.getDate(); var mm = now.getMonth()+1; // As months start from 0, i.e. January is 0 var yyyy = now.getFullYear(); var hh = now.getHours(); var min = now.getMinutes(); var ss = now.getSeconds(); if(dd<10) { dd = '0' + dd ; } if(mm<10) { mm = '0' + mm; } if(hh<10) { hh = '0' + hh; } if(min<10) { min = '0' + min; } if(ss<10) { ss = '0' + ss; } reset = 1; // Set reset flag to 1, as reset button has been clicked document.getElementById('date').value = yyyy+'-'+mm+'-'+dd; document.getElementById('time').value= (hh+1)+':'+min+':'+ss; document.getElementById('input-field').style.visibility='visible'; } var setToZero = function() { document.getElementById('days').innerHTML = '0'; document.getElementById('hours').innerHTML = '0'; document.getElementById('minutes').innerHTML = '0'; document.getElementById('seconds').innerHTML = '0'; } var stopTimer = function() { clearInterval(myTimer); myTimer=0; } var startTimer = function() { if(reset === 1) { // If Reset button has been clicked before clicking the Start button if(getTimeLeft()=== -1) { setToZero(); return ; } reset = 0; } if (!myTimer) myTimer = setInterval(timer,1000); document.getElementById('input-field').style.visibility='hidden'; } var getTimeLeft = function() { var eventDate = document.getElementById('date').value; var eventTime = document.getElementById('time').value; eventDate = eventDate.split("-") eventTime = eventTime.split(":"); if(verifyInput(eventDate,eventTime)=== -1) { alert("Please enter the date and time of the event properly.") setNow(); setToZero(); return -1; } var EventOn = new Date(eventDate[0],parseInt(eventDate[1])-1,eventDate[2],eventTime[0],eventTime[1],eventTime[2]); if(!EventOn) { console.log("Set proper value of event date"); return; } console.log(EventOn.toString()) var t = EventOn.getTime() - Date.now(); if(t<=0) { alert("The event date and time should be in the future.") return -1; } // Calculate the required time remaining for the event var seconds = Math.floor( (t/1000) % 60 ); var minutes = Math.floor( (t/1000/60) % 60 ); var hours = Math.floor( (t/(1000*60*60)) % 24 ); var days = Math.floor( t/(1000*60*60*24) ); document.getElementById('days').innerHTML = String(days); document.getElementById('hours').innerHTML = String(hours); document.getElementById('minutes').innerHTML = String(minutes); document.getElementById('seconds').innerHTML = String(seconds); // Return control to startTimer } var verifyInput = function(date,time) { yyyy = date[0]; mm = date[1]; dd = date[2]; hh = time[0]; min = time[1]; ss = time[2]; console.log("called") if ( isNaN(yyyy) || isNaN(mm) || isNaN(dd) || isNaN(hh) || isNaN(min) || isNaN(ss)) { return -1; } console.log("passed 1") if(Number(mm) < 1 || Number(mm) > 12 || Number(dd) < 1) return -1; if(Number(mm) === 2) { // Checking for leap years console.log("feb"); if (Number(dd)>29) { console.log(String(Number(dd)) + "feb more days"); return -1; } else if(Number(dd)===29) { if( Number(yyyy)%4===0 && Number(yyyy)%100!=0) { console.log("condn 1"); return 0; } else if ( Number(yyyy)%400 === 0) { console.log("condn 2"); return 0; } else return -1; } return 0; } if(mm in ['1','3','5','7','8','10','12']) { if (! dd <= '30') return -1; } else if (mm in ['4','6','9','11']){ if (! dd <= '31') return -1; } else if ((Number(hh)>23 || Number(hh)<0) || (Number(min)<0 || Number(min)>59) || (Number(ss)<0 || Number(ss)>59)) return -1; return 0; } // Adding event listeners for the buttons document.getElementById("stop").addEventListener("click", stopTimer ); document.getElementById("start").addEventListener("click", startTimer ); document.getElementById("reset").addEventListener("click", setNow ); setNow(); <file_sep># webdev-task1 Normal mode of Delta web dev Task 1 Theme - Space
e15dbd85f58143c794f18dae60ebc229bade24fc
[ "JavaScript", "Markdown" ]
2
JavaScript
digaru19/webdev-task1-advanced
cda51b563ec2e984d1b9909ac5a80f71cf5838c9
278d509befc0e5a1239ec2b5d45973dddab90ae7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CarBook.Data; using CarBook.Data.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace CarBook.Web.Controllers.Api { [Produces("application/json")] [Route("api/car")] public class CarController : Controller { private readonly CarBookDbContext _dbContext; public CarController(CarBookDbContext dbContext) { _dbContext = dbContext; } [HttpGet] [Route("getall")] public async Task<Car[]> GetAllAsync() { return await _dbContext.Set<Car>().ToArrayAsync(); } } }<file_sep>using System; using System.Collections.Generic; using System.Text; using CarBook.Data.Models; using Microsoft.EntityFrameworkCore; namespace CarBook.Data { public class CarBookDbContext: DbContext { public CarBookDbContext(DbContextOptions options):base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Car>().ToTable("Cars"); modelBuilder.Entity<Car>().HasKey(c => c.Id); modelBuilder.Entity<Car>().Property(c => c.Model).IsRequired(); modelBuilder.Entity<Car>().Property(c => c.Make).IsRequired(); modelBuilder.Entity<Feature>().ToTable("Features"); modelBuilder.Entity<Feature>().HasKey(f => f.Id); modelBuilder.Entity<Feature>().Property(f => f.Name).IsRequired(); modelBuilder.Entity<CarFeature>().ToTable("CarFeatures"); modelBuilder.Entity<CarFeature>().HasKey(cf => new {cf.CarId, cf.FeatureId}); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace CarBook.Data.Models { public class CarFeature { public int CarId { get; set; } public int FeatureId { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CarBook.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace CarBook.Web { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDbContext<CarBookDbContext>( (builder) => { builder.UseSqlite( @"Data Source=D:\Dropbox\work\carbook\CarBook.Web\CarBook.Data\carbook.db"); } ); services.AddMvc(); services.AddRouting(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller}/{action}/{id}"); }); } } }
5add1962429599bf0acb84982f30990f7d5840b0
[ "C#" ]
4
C#
MikhailMonchak/carbook
aeb9a1a8546ae73e4a42bc42ea9611d5d4a31d76
fc04653a12827f6c731617e72201e1fefceb509a
refs/heads/master
<repo_name>yvonturcotte/aws<file_sep>/Lambda/StopEC2/stop_instances.py # Hautement inspiré de cet article : http://www.cloudberrylab.com/blog/how-to-save-up-to-50-on-your-non-production-ec2-instances-using-lambda-and-resource-tagging/ from __future__ import print_function import boto3 def lambda_handler(event, context): ec2 = boto3.client("ec2", region_name="us-east-1") description = ec2.describe_instances() for instances in description["Reservations"]: for instance in instances["Instances"]: for tag in instance["Tags"]: if (tag["Key"] + tag["Value"]) == "autoshutdowntrue": if instance["State"]["Name"] == "running": print("Stopping : " + instance["InstanceId"]) ec2 = boto3.resource("ec2", region_name = "us-east-1") instance = ec2.Instance(instance["InstanceId"]) instance.stop()
cfa418b302a47c306d0b5685bec4300243afe54a
[ "Python" ]
1
Python
yvonturcotte/aws
96d92e2d694d9c48dfb2ba83d95a86d71c87192e
54dce6874f40c9f3ca87ee9d113f11c17b181aa3
refs/heads/master
<file_sep>package util import ( "encoding/json" "log" "os" ) // ReadJSON read JSON file into a struct func ReadJSON(jsonPath string, s interface{}) error { file, err := os.Open(jsonPath) if err != nil { log.Printf("unable to open '%s'", jsonPath) return err } decoder := json.NewDecoder(file) err = decoder.Decode(&s) if err != nil { log.Printf("unable to decode '%s' to '%v'", jsonPath, s) return err } return nil } <file_sep>package util import ( "archive/zip" "io" "io/ioutil" "log" "os" "path/filepath" "strings" ) // CopyFile copy file from src to dest func CopyFile(src, dest string) (err error) { in, err := os.Open(src) if err != nil { log.Printf("Unable to open file '%s'", src) return err } defer in.Close() parentdir := filepath.Dir(dest) exist, err := Exists(parentdir) if !exist { os.MkdirAll(parentdir, os.ModePerm) } out, err := os.Create(dest) if err != nil { log.Printf("Unable to create dest file '%s'", dest) return err } defer out.Close() if _, err = io.Copy(out, in); err != nil { log.Printf("Unable to copy file") return err } err = out.Sync() if err != nil { return err } return nil } // ListAllFiles Get file pathes from specific folder and sub folders func ListAllFiles(dir string) ([]string, error) { files := []string{} fileInfos, err := ioutil.ReadDir(dir) if err != nil { log.Printf("Unable to read dir '%s'", dir) return nil, err } for _, fileInfo := range fileInfos { currentfile := filepath.Join(dir, fileInfo.Name()) if fileInfo.IsDir() { subfiles, _ := ListAllFiles(currentfile) for _, f := range subfiles { files = append(files, f) } } else { files = append(files, currentfile) } } return files, err } // CopyDir copy folder from src to dest func CopyDir(src, dest string) (err error) { files, err := ListAllFiles(src) if err != nil { log.Printf("Unable list all files under '%s'", src) return err } for _, file := range files { relativepath, _ := filepath.Rel(src, file) _, dirname := filepath.Split(src) joinedDest := filepath.Join(dest, dirname, relativepath) CopyFile(file, joinedDest) } return nil } // Exists check file existance func Exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return true, err } // Unzip unzip zip file to dest folder func Unzip(src, dest string) error { r, err := zip.OpenReader(src) if err != nil { log.Printf("Unable to open reader to '%s'", src) return err } defer r.Close() os.MkdirAll(dest, os.ModePerm) // Closure to address file descriptors issue with all the deferred .Close() methods extractAndWriteFile := func(f *zip.File) error { rc, err := f.Open() if err != nil { log.Printf("Unable to open zip file '%s'", src) return err } defer rc.Close() path := filepath.Join(dest, f.Name) if f.FileInfo().IsDir() { os.MkdirAll(path, f.Mode()) } else { os.MkdirAll(filepath.Dir(path), f.Mode()) f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { log.Printf("Unable to open file '%s'", path) return err } defer f.Close() _, err = io.Copy(f, rc) if err != nil { log.Printf("Unable to copy file") return err } } return nil } for _, f := range r.File { err := extractAndWriteFile(f) if err != nil { log.Printf("Unable to extract and file") return err } } return nil } // Replace replace string content in file func Replace(filepath, oldstr, newstr string) error { read, err := ioutil.ReadFile(filepath) if err != nil { log.Printf("Unable to read file '%s'", filepath) return err } newContents := strings.Replace(string(read), oldstr, newstr, -1) err = ioutil.WriteFile(filepath, []byte(newContents), 0) if err != nil { log.Printf("Unable to write file '%s'", filepath) return err } return nil }
2179f351de441fea29f7988d9a9063ebda739940
[ "Go" ]
2
Go
oneryx/go-util
d36b5344b601ac373179846171e39c58188ebcc0
488cda849c93c586a3d247137ec4fffd8baebc16
refs/heads/master
<file_sep>Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get '/(:order)', to: 'application#index', as: :root resources :starred, only: [:update, :destroy] end <file_sep>class StarredController < ActionController::Base def update Influencers.update(params[:id], :starred => 1) redirect_to root_path end def destroy Influencers.update(params[:id], :starred => 0) redirect_to root_path end end<file_sep>class Influencers < ApplicationRecord end<file_sep>class ApplicationController < ActionController::Base def index if params[:order] == 'asc' order = :asc else order = :desc end @influencers = Influencers.where(starred: 0) @starred = Influencers.where(starred: 1).order(statistics_engagement: order) end end
6b1a1e00a7dc97b4b5c7fd9c294147d2512103cf
[ "Ruby" ]
4
Ruby
kabeersvohra/mv-coding-test
13dbaa5697c39e66eb82520276c6af2a5cfddfbf
4bc65d2a79b366e728a97393aeff0a43389afc8a
refs/heads/master
<repo_name>kenotron/repro-api-extractor<file_sep>/src/index.ts /** @public */ export const a = 5; <file_sep>/index.d.ts export declare const a = 5; export { }
08059518ff5e47e4132e380d66bd46d77640d510
[ "TypeScript" ]
2
TypeScript
kenotron/repro-api-extractor
5d77ba1fe9253d8018a8372d19ad7347d043f9ad
24995a853006192dc07defb7ac1bc6ac2bb09a2d
refs/heads/master
<repo_name>asalander/R0331-javascript<file_sep>/Projekti1/koodit.js //Lisää-nappi html-tiedostossa onclick=createNewElement var myToDo = document.getElementsByTagName("li"); var index; for (index = 0; index < myToDo.length; index++) { var span = document.createElement("SPAN"); var someTxt = document.createTextNode("POISTA"); span.className = "hide"; span.appendChild(someTxt); myToDo[index].appendChild(span); } //Poista-nappi piilottaa rivit (ajetetaan myös function ulkopuolella) var poistaButton = document.getElementsByClassName("hide"); var i; for (i = 0; i < poistaButton.length; i++) { poistaButton[i].onclick = function () { var TheDel = this.parentElement; TheDel.style.display = "none"; }; } //Etsitään luettelo(li) ja lisätään kuuntelija, joka klikkaamalla suorittaa funktion (ylivivaa, kts. CSS) var ulLista = document.querySelector("ul"); ulLista.addEventListener( "click", function (event) { if (event.target.tagName === "LI") { event.target.classList.toggle("checked"); } }, false ); //Luodaan uusi listaelementti (li) ja otetaan arvo input-kentästä (kirjoituskenttä) ja liitetään (append) teksti listaan(li) function createNewElement() { var li = document.createElement("li"); var newitem = document.getElementById("input").value; var textNode = document.createTextNode(newitem); li.appendChild(textNode); //mikäli input-kentässä ei ole arvoa, annetaan ilmoitus ja väri, muussa tapauksessa tehdään luettelo(ul) if (newitem === "") { input.style.borderColor = "DeepPink"; document.getElementById("feedback").innerHTML = "* Sinun tulee syöttää tekstiä"; } else { document.getElementById("lista").appendChild(li); } //muutetään input-kentän arvo tyhjäksi document.getElementById("input").value = ""; //luodaan poistomerkki (span) nimeltään POISTA ja lisätään se listaan(li) var span = document.createElement("SPAN"); var txt = document.createTextNode("POISTA"); span.classname = "hide"; span.appendChild(txt); li.appendChild(span); //luodaan silmukka, joka käy li-listan läpi ja poista-nappia painamalla rivi piilotetaan for (i = 0; i < poistaButton.length; i++) { poistaButton[i].onclick = function () { var TheDel = this.parentElement; TheDel.style.display = "none"; }; } } //Koko listan tyhjentäminen function removeAll() { var del = document.getElementsByTagName("ul"); del[0].innerHTML = ""; }
050ecdd4f25dfbf215ace628cefa282ffaf91aad
[ "JavaScript" ]
1
JavaScript
asalander/R0331-javascript
7e393e4963a19a868b08e2db281a143856facad4
efc88af714eeeb540c5d33be438b2068ae9f3f3e
refs/heads/master
<repo_name>ztnark/21Dashboard<file_sep>/21app2/SendViewController.swift // // SendViewController.swift // 21app2 // // Created by <NAME> on 1/6/16. // Copyright © 2016 <NAME>. All rights reserved. //IDEAS // Ability to add new endpoints //Ability to make and receive both on-chain and off-chain payments import UIKit import Alamofire import UIColor_Hex_Swift import SwiftyJSON import QRCode import QRCodeReader import AVFoundation class SendViewController: UIViewController, QRCodeReaderViewControllerDelegate, UITextFieldDelegate { @IBOutlet var amountField: UITextField! @IBOutlet var addressField: UITextField! var address = "" var url = "" lazy var readerVC: QRCodeReaderViewController = { let builder = QRCodeReaderViewControllerBuilder { $0.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObjectTypeQRCode], captureDevicePosition: .back) } return QRCodeReaderViewController(builder: builder) }() override func viewDidLoad() { super.viewDidLoad() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SendViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } @IBAction func cancel(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } @IBAction func send(_ sender: AnyObject) { let headers = [ "Content-Type": "application/json" ] let amount:Int? = Int(amountField.text!) let parameters : [String : AnyObject] = [ "address": self.addressField.text! as AnyObject, "amount": amount! as AnyObject, "code":MyVariables.auth as AnyObject, ] LoadingOverlay.shared.showOverlay(self.view) let url = MyVariables.url + "/send" Alamofire.request(url, method: .post,parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in LoadingOverlay.shared.hideOverlayView() if let value = response.result.value { let json = JSON(value) print("JSON: \(json)") if response.response!.statusCode == 401 { let text = json["text"].stringValue self.presentAlert(text) } } } } // lazy var reader = QRCodeReaderViewController(metadataObjectTypes: [AVMetadataObjectTypeQRCode]) @IBAction func scanAction(_ sender: AnyObject) { guard checkScanPermissions() else { return } // Retrieve the QRCode content // By using the delegate pattern readerVC.delegate = self as! QRCodeReaderViewControllerDelegate // Or by using the closure pattern readerVC.completionBlock = { (result: QRCodeReaderResult?) in self.address = result!.value self.addressField.text = self.address } // Presents the reader as modal form sheet readerVC.modalPresentationStyle = .formSheet present(readerVC, animated: true, completion: nil) } //Calls this function when the tap is recognized. func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } func presentAlert(_ alert: String){ let alert = UIAlertController(title: "Error", message: alert, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } // MARK: - QRCodeReader Delegate Methods func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) { self.dismiss(animated: true, completion: nil) } func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) { if let cameraName = newCaptureDevice.device.localizedName { print("Switching capturing to: \(cameraName)") } } func readerDidCancel(_ reader: QRCodeReaderViewController) { print("here"); self.dismiss(animated: true, completion: nil) } private func checkScanPermissions() -> Bool { do { return try QRCodeReader.supportsMetadataObjectTypes() } catch let error as NSError { let alert: UIAlertController? switch error.code { case -11852: alert = UIAlertController(title: "Error", message: "This app is not authorized to use Back Camera.", preferredStyle: .alert) alert?.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (_) in DispatchQueue.main.async { if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(settingsURL) } } })) alert?.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) case -11814: alert = UIAlertController(title: "Error", message: "Reader not supported by the current device", preferredStyle: .alert) alert?.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) default: alert = nil } guard let vc = alert else { return false } present(vc, animated: true, completion: nil) return false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { let defaults = UserDefaults.standard if let userData : AnyObject? = defaults.object(forKey: "test") as AnyObject?? { if (userData != nil && userData!.count > 0){ let endpoints = defaults.object(forKey: "test") as! NSArray self.url = endpoints[0] as! String } } } func textFieldShouldReturn(_ textField: UITextField!) -> Bool { //delegate method textField.resignFirstResponder() return true } } <file_sep>/Podfile # Uncomment this line to define a global platform for your project platform :ios, '10.0' # Uncomment this line if you're using Swift use_frameworks! target '21app2' do pod 'Alamofire', '~> 4.0' pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git' pod 'UIColor_Hex_Swift' pod 'QRCode', :git => 'https://github.com/aschuch/QRCode' pod 'QRCodeReader.swift' end target '21app2Tests' do end target '21app2UITests' do end <file_sep>/21app2/ViewController.swift // // ViewController.swift // 21app2 // // Created by <NAME> on 1/6/16. // Copyright © 2016 <NAME>. All rights reserved. //IDEAS // Ability to add new endpoints //Ability to make and receive both on-chain and off-chain payments import UIKit import Alamofire import UIColor_Hex_Swift import SwiftyJSON import QRCode struct MyVariables { static var url = "" static var auth = "" } class ViewController: UIViewController { @IBOutlet var qrImage: UIImageView! @IBOutlet var addressLabel: UILabel! @IBOutlet var onchainLabel: UILabel! @IBOutlet var offchainLabel: UILabel! @IBOutlet var flushingLabel: UILabel! @IBOutlet var hashrateLabel: UILabel! @IBOutlet var onchainBtn: UIButton! @IBOutlet var offchainBtn: UIButton! @IBOutlet var flushingBtn: UIButton! @IBOutlet var mineBtn: UIButton! @IBOutlet var flushBtn: UIButton! var splashScreen: UIImageView? var numberFormatter = NumberFormatter() var alamoFireManager : Alamofire.SessionManager? var url = "" var auth = "" override func viewDidLoad() { super.viewDidLoad() let screenRect = UIScreen.main.bounds let screenWidth = screenRect.size.width let screenHeight = screenRect.size.height numberFormatter.numberStyle = NumberFormatter.Style.decimal self.splashScreen = UIImageView(image: UIImage(named: "SplashScreen")) self.splashScreen?.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight) self.view.addSubview(splashScreen!) let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 30 // seconds self.alamoFireManager = Alamofire.SessionManager(configuration: configuration) } func get21Data(_ url: String){ let headers = [ "Content-Type": "application/json" ] let url = MyVariables.url + "/dashboard?code=" + MyVariables.auth self.alamoFireManager!.request(url, method: .get,parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in switch response.result { case .success(_): //LoadingOverlay.shared.hideOverlayView() if let value = response.result.value { let json = JSON(value) print("JSON: \(json)") let onChain = json["status_wallet"]["onchain"].int! as NSNumber let balance = json["status_wallet"]["twentyone_balance"].int! as NSNumber let flushing = json["status_wallet"]["flushing"].int! as NSNumber if response.response!.statusCode == 200 { self.addressLabel.text = json["status_account"]["address"].stringValue self.onchainLabel.text = self.numberFormatter.string(from: onChain) self.offchainLabel.text = self.numberFormatter.string(from: balance) self.flushingLabel.text = self.numberFormatter.string(from: flushing) self.hashrateLabel.text = json["status_mining"]["hashrate"].stringValue let qrCode = QRCode(json["status_account"]["address"].stringValue) self.qrImage.image = qrCode?.image self.splashScreen!.removeFromSuperview() } else if response.response!.statusCode == 401 { let text = json["text"].stringValue self.presentAlert(text) return } } case .failure(let error): self.splashScreen!.removeFromSuperview() print(error); } } } func presentAlert(_ alert: String){ let alert = UIAlertController(title: "Error", message: alert, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } @IBAction func onchainaction(_ sender: AnyObject) { offchainLabel.isHidden = true flushingLabel.isHidden = true onchainLabel.isHidden = false offchainBtn.setTitleColor(UIColor.gray, for: UIControlState()) flushingBtn.setTitleColor(UIColor.gray, for: UIControlState()) onchainBtn.setTitleColor(UIColor.white, for: UIControlState()) } @IBAction func offchainaction(_ sender: AnyObject) { flushingLabel.isHidden = true onchainLabel.isHidden = true offchainLabel.isHidden = false flushingBtn.setTitleColor(UIColor.gray, for: UIControlState()) onchainBtn.setTitleColor(UIColor.gray, for: UIControlState()) offchainBtn.setTitleColor(UIColor.white, for: UIControlState()) } @IBAction func flushingaction(_ sender: AnyObject) { onchainLabel.isHidden = true offchainLabel.isHidden = true flushingLabel.isHidden = false onchainBtn.setTitleColor(UIColor.gray, for: UIControlState()) offchainBtn.setTitleColor(UIColor.gray, for: UIControlState()) flushingBtn.setTitleColor(UIColor.white, for: UIControlState()) } @IBAction func mine(_ sender: AnyObject) { let headers = [ "Content-Type": "application/json" ] LoadingOverlay.shared.showOverlay(self.view) let url = MyVariables.url + "/mine?code=" + MyVariables.auth self.alamoFireManager!.request(url, method: .get,parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in LoadingOverlay.shared.hideOverlayView() switch response.result { case .success(_): if let value = response.result.value { let json = JSON(value) let onChain = json["status_wallet"]["onchain"].int! as NSNumber let balance = json["status_wallet"]["twentyone_balance"].int! as NSNumber let flushing = json["status_wallet"]["flushing"].int! as NSNumber print("JSON: \(json)") if response.response!.statusCode == 200 { self.addressLabel.text = json["status_account"]["address"].stringValue self.onchainLabel.text = self.numberFormatter.string(from: onChain) self.offchainLabel.text = self.numberFormatter.string(from: balance) self.flushingLabel.text = self.numberFormatter.string(from: flushing) self.hashrateLabel.text = json["status_mining"]["hashrate"].stringValue let qrCode = QRCode(json["status_account"]["address"].stringValue) self.qrImage.image = qrCode?.image } else if response.response!.statusCode == 401 { let text = json["text"].stringValue self.presentAlert(text) return } } case .failure(let error): self.presentAlert(error.localizedDescription) } } } @IBAction func flush(_ sender: AnyObject) { let headers = [ "Content-Type": "application/json" ] LoadingOverlay.shared.showOverlay(self.view) let url = MyVariables.url + "/flush?code=" + MyVariables.auth self.alamoFireManager!.request(url, method: .get,parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in LoadingOverlay.shared.hideOverlayView() if let value = response.result.value { let json = JSON(value) let onChain = json["status_wallet"]["onchain"].int! as NSNumber let balance = json["status_wallet"]["twentyone_balance"].int! as NSNumber let flushing = json["status_wallet"]["flushing"].int! as NSNumber if response.response!.statusCode == 200 { self.addressLabel.text = json["status_account"]["address"].stringValue self.onchainLabel.text = self.numberFormatter.string(from: onChain) self.offchainLabel.text = self.numberFormatter.string(from: balance) self.flushingLabel.text = self.numberFormatter.string(from: flushing) self.hashrateLabel.text = json["status_mining"]["hashrate"].stringValue let qrCode = QRCode(json["status_account"]["address"].stringValue) self.qrImage.image = qrCode?.image } else if response.response!.statusCode == 401 { let text = json["text"].stringValue self.presentAlert(text) return } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { //self.navigationController?.navigationBar.tintColor = UIColor.whiteColor(); let headerView = UIView(frame:CGRect(x: 0, y: 0, width: 40, height: 40)) let image = UIImage(named:"21co.png") let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) imageView.image = image headerView.addSubview(imageView) self.navigationItem.titleView = headerView navigationController?.navigationBar.barTintColor = UIColor.black //UIColor(colorLiteralRed: 205.0/255.0, green: 0.0/255.0, blue: 15.0/255.0, alpha: 1.0) self.navigationController?.navigationBar.isTranslucent = false let defaults = UserDefaults.standard if let userData : AnyObject? = defaults.object(forKey: "test") as AnyObject?? { if (userData != nil && userData!.count > 0){ let endpoints = defaults.object(forKey: "test") as! NSArray MyVariables.url = endpoints[0] as! String MyVariables.auth = endpoints[1] as! String get21Data(url) }else{ self.splashScreen!.removeFromSuperview() changePrefs() } } } @IBAction func settings(_ sender: AnyObject) { changePrefs() } func changePrefs(){ let defaults = UserDefaults.standard var endArr: [NSString] = [NSString]() let alert = UIAlertController(title: "New Endpoint", message: "Enter the endpoint for your 21 computer.", preferredStyle: UIAlertControllerStyle.alert) alert.addTextField { (textField) in textField.placeholder = "21 Endpoint" } alert.addTextField { (textField) in textField.isSecureTextEntry = true textField.placeholder = "Authorization Code" } alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler:{ (alertAction:UIAlertAction!) in let textf = alert.textFields![0] as UITextField let authf = alert.textFields![1] as UITextField MyVariables.url = textf.text! MyVariables.auth = authf.text! endArr.append(MyVariables.url as NSString) endArr.append(MyVariables.auth as NSString) defaults.set(endArr, forKey: "test") self.get21Data(MyVariables.url) })) self.present(alert, animated: true, completion: nil) } }
727aab17bbab449357973bf29815992bb19c3ce9
[ "Swift", "Ruby" ]
3
Swift
ztnark/21Dashboard
c29e1d99e567b3a91383093dcf8ecfa6c69cb6d3
ea66c660bd651e650ca456a1761c824b022d381e
refs/heads/master
<file_sep>'use strict'; var expect = require('chai').expect, getOutput = require('../../lib/get_output'); describe('getOutput', function() { it('handles the case where there are no groups', function() { var output = [], formatted = 'formatted default task name'; getOutput(output, {}, 'default', formatted); expect(output).to.have.length(1); expect(output[0]).to.eql({ log: formatted }); }); });
80eeedb593b681f473fb893d4b37cd8b80b89e6e
[ "JavaScript" ]
1
JavaScript
NickHeiner/grunt-available-tasks
3cc070aba37612c15c04e374a53f114801b2a315
3a9d6d65d37b835825d92e449ffc05ecbc841124
refs/heads/master
<file_sep><?php /** * Plugin Name: Google Time Sharing * Plugin URI: http://local.git * Description: This plugin should add several pages to view schedule data stored in a database and block off your own and request others. * Version: 0.0.1 * Author: <NAME> * Author URI: http://theripper.info * License: GPL2 */ <file_sep><?php // This file will house my utility functions allowing the main file to include it and handle the interfacing with wordpress ?> <file_sep>## WP plugin for block schedules ## So the plan here is to add a couple of pages: * View your upcoming schedule monthly * Block off time on your schedule with a reason (doesn't require approval by anyone) * View schedule of chosen member (either from link in their profile or a search box on the schedule page) * Request block of time from other user (requires their approval) I'll try to remember to strike through that list as I manage to create the functionality. The main reason for this repo is to easily share my codebase with my lovely gf @senkarose so she can work with me on it.
55c571b7278e1303d667626ea92ab95b642bf223
[ "Markdown", "PHP" ]
3
PHP
SirDianthus/cTimeShare
42af5681cdbef8b4938abb890d765ded7433a749
24bf00a4cd5b9db5e7c63ccb4ae1f7011f4fcfe4
refs/heads/master
<file_sep>mkdir -p bin cwd=$(pwd) version='0.9.4' pushd $GOPATH/src/github.com/influxdb/influxdb # get the correct branch to work with git checkout $version git pull origin $version # get the latest packages go get -u -f -d ./... # switch back to the current branch that the go get above just changed to master on us :-( git checkout $version commit=`git rev-parse HEAD` branch=`git rev-parse --abbrev-ref HEAD` # build the binaries echo "executing: GOOS=windows GOARCH=amd64 go build -o $cwd/bin/influxd.exe -ldflags=-X main.version=$version -X main.branch=$branch -X main.commit=$commit ./cmd/influxd" GOOS=windows GOARCH=amd64 go build -o $cwd/bin/influxd.exe -ldflags="-X main.version=$version -X main.branch=$branch -X main.commit=$commit" ./cmd/influxd echo "executing: GOOS=windows GOARCH=amd64 go build -o $cwd/bin/influx.exe -ldflags=-X main.version=$version -X main.branch=$branch -X main.commit=$commit ./cmd/influx" GOOS=windows GOARCH=amd64 go build -o $cwd/bin/influx.exe -ldflags="-X main.version=$version -X main.branch=$branch -X main.commit=$commit" ./cmd/influx popd <file_sep># Telegraf configuration # Telegraf is entirely plugin driven. All metrics are gathered from the # declared plugins. # Even if a plugin has no configuration, it must be declared in here # to be active. Declaring a plugin means just specifying the name # as a section with no variables. To deactivate a plugin, comment # out the name and any variables. # Use 'telegraf -config telegraf.toml -test' to see what metrics a config # file would generate. # One rule that plugins conform to is wherever a connection string # can be passed, the values '' and 'localhost' are treated specially. # They indicate to the plugin to use their own builtin configuration to # connect to the local system. # NOTE: The configuration has a few required parameters. They are marked # with 'required'. Be sure to edit those to make this configuration work. # Tags can also be specified via a normal map, but only one form at a time: [tags] # dc = "us-east-1" # Configuration for telegraf agent [agent] # Default data collection interval for all plugins interval = "10s" # If utc = false, uses local time (utc is highly recommended) utc = true # Precision of writes, valid values are n, u, ms, s, m, and h # note: using second precision greatly helps InfluxDB compression precision = "s" # run telegraf in debug mode debug = false # Override default hostname, if empty use os.Hostname() hostname = "" ############################################################################### # OUTPUTS # ############################################################################### [outputs] # Configuration for influxdb server to send metrics to [outputs.influxdb] # The full HTTP endpoint URL for your InfluxDB instance # Multiple urls can be specified for InfluxDB cluster support. Server to # write to will be randomly chosen each interval. urls = ["http://localhost:8086"] # required. # The target database for metrics. This database must already exist database = "telegraf" # required. # Connection timeout (for the connection with InfluxDB), formatted as a string. # Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". # If not provided, will default to 0 (no timeout) # timeout = "5s" # username = "telegraf" # password = "<PASSWORD>" # Set the user agent for the POSTs (can be useful for log differentiation) # user_agent = "telegraf" ############################################################################### # PLUGINS # ############################################################################### # Read metrics about cpu usage [cpu] # Whether to report per-cpu stats or not percpu = true # Whether to report total system cpu stats or not totalcpu = true # Comment this line if you want the raw CPU time metrics drop = ["cpu_time"] # Read metrics about memory usage [mem] # no configuration # Read metrics about network interface usage [net] # By default, telegraf gathers stats from any up interface (excluding loopback) # Setting interfaces will tell it to gather these explicit interfaces, # regardless of status. # # interfaces = ["eth0", ... ] # Read metrics about swap memory usage [swap] # no configuration <file_sep># Chronograf configuration # TCP address that Chronograf should bind to. # Bind to localhost by default, so that Chronograf should be inaccessible from the public internet. # Can be overridden with environment variable CHRONOGRAF_BIND. Bind = "127.0.0.1:9090" # Path to local database file to use or create for storing Chronograf application data. # Can be overridden with environment variable CHRONOGRAF_LOCAL_DATABASE. LocalDatabase = "chronograf.db" # DSN to connect to MySQL for storing Chronograf application data. # If set, takes precedence over LocalDatabase setting. # Can be overridden with environment variable CHRONOGRAF_MYSQL_DSN. # Uncomment and update if you want to use MySQL. # MySQLDSN = "user:password@tcp(192.0.2.1:3306)/some_database" <file_sep>version=`git describe --always --tags` GOARCH=amd64 GOOS=windows godep go build -ldflags "-X main.Version=$version" ./cmd/telegraf/ <file_sep># Windows Package Managers This project houses the windows install packages for [InfulxDB](https://github.com/influxdb/influxdb), [Chronograf](https://influxdb.com/chronograf/index.html), and [Telegraf](https://github.com/influxdb/telegraf)](https://github.com/influxdb/telegraf). ## Future Features - [ ] Install executables as services - [ ] Log events to event log - [ ] Allow configuration of services via install ## InfluxDB Windows Packager This project uses the [Wix Toolset](http://wixtoolset.org/) to generate a windows msi installer. All of the scripts to build the InfluxDB MSI installer are located in the `influxdb` directory ### GUID You need to generate some GUIDs for the installer. I used [guidgen.com](http://www.guidgen.com/) referenced in the [generate guids guide](http://wixtoolset.org/documentation/manual/v3/howtos/general/generate_guids.html) NOTE: You have to uppercase the GUID's that this site generates to be fully compatible with the installer. ### Generating InfluxDB Binaries To generate the necessary InfluxDB binaries, pull down the [project](http://github.com/influxdb/influxdb). Then with a valid [go](http://golang.org) environment set up, run the following script: ```sh ./build.sh ``` ### Generating the MSI First, we need to use candle to create our intermmediate object that will turn into an msi file. ``` candle.exe -nologo influxdb.wxs -out influxdb.wixobj -ext WixUtilExtension -ext WixUIExtension ``` Now we can generate the msi file with this command: ``` light.exe -nologo influxdb.wixobj -out influxdb.msi -ext WixUtilExtension -ext WixUIExtension ``` ## Chronograf Windows Packager This project uses the [Wix Toolset](http://wixtoolset.org/) to generate a windows msi installer. All of the scripts to build the Chronograf MSI installer are located in the `chronograf` directory ### Generating the MSI First, we need to use candle to create our intermmediate object that will turn into an msi file. ``` candle.exe -nologo chronograf.wxs -out chronograf.wixobj -ext WixUtilExtension -ext WixUIExtension ``` Now we can generate the msi file with this command: ``` light.exe -nologo chronograf.wixobj -out chronograf.msi -ext WixUtilExtension -ext WixUIExtension ``` ## Telegraf Windows Packager This project uses the [Wix Toolset](http://wixtoolset.org/) to generate a windows msi installer. All of the scripts to build the Telegraf MSI installer are located in the `telegraf` directory ### Generating the MSI First, we need to use candle to create our intermmediate object that will turn into an msi file. ``` candle.exe -nologo telegraf.wxs -out telegraf.wixobj -ext WixUtilExtension -ext WixUIExtension ``` Now we can generate the msi file with this command: ``` light.exe -nologo telegraf.wixobj -out telegraf.msi -ext WixUtilExtension -ext WixUIExtension ```
92a3df9efaaafdedb86e31c801603081ba5d7297
[ "TOML", "Markdown", "Shell" ]
5
Shell
influxdata/windows-packager
0e6cad9b403f75096522f0e3485a496f4c6dea8c
16fcbd6dd69029a1203d0f9053cfdd24b196a646
refs/heads/main
<repo_name>kvfasoulakos/Mean-Variance-Standard-Deviation-CalculatorPassed<file_sep>/mean_var_std.py import numpy as np def calculate(list): if len(list) != 9: raise ValueError("List must contain nine numbers.") new_list = np.array(list) print(new_list) mean_axis1 = [new_list[[0,3,6]].mean(), new_list[[1,4,7]].mean(),new_list[[2,5,8]].mean()] mean_axis2 = [new_list[[0,1,2]].mean(), new_list[[3,4,5]].mean(),new_list[[6,7,8]].mean()] var_axis1 = [new_list[[0,3,6]].var(), new_list[[1,4,7]].var(),new_list[[2,5,8]].var()] var_axis2 = [new_list[[0,1,2]].var(), new_list[[3,4,5]].var(),new_list[[6,7,8]].var()] std_axis1 = [new_list[[0,3,6]].std(), new_list[[1,4,7]].std(),new_list[[2,5,8]].std()] std_axis2 = [new_list[[0,1,2]].std(), new_list[[3,4,5]].std(),new_list[[6,7,8]].std()] max_axis1 = [new_list[[0,3,6]].max(), new_list[[1,4,7]].max(),new_list[[2,5,8]].max()] max_axis2 = [new_list[[0,1,2]].max(), new_list[[3,4,5]].max(),new_list[[6,7,8]].max()] min_axis1 = [new_list[[0,3,6]].min(), new_list[[1,4,7]].min(),new_list[[2,5,8]].min()] min_axis2 = [new_list[[0,1,2]].min(), new_list[[3,4,5]].min(),new_list[[6,7,8]].min()] sum_axis1 = [new_list[[0,3,6]].sum(), new_list[[1,4,7]].sum(),new_list[[2,5,8]].sum()] sum_axis2 = [new_list[[0,1,2]].sum(), new_list[[3,4,5]].sum(),new_list[[6,7,8]].sum()] return { 'mean': [mean_axis1, mean_axis2, new_list.mean()], 'variance': [var_axis1, var_axis2, new_list.var()], 'standard deviation': [std_axis1, std_axis2, new_list.std()], 'max': [max_axis1, max_axis2, new_list.max()], 'min': [min_axis1, min_axis2, new_list.min()], 'sum': [sum_axis1, sum_axis2, new_list.sum()] } #calculations
1af1eea66ae343bb06f69ed6b25a15ec82e8c8ea
[ "Python" ]
1
Python
kvfasoulakos/Mean-Variance-Standard-Deviation-CalculatorPassed
84930c2b817dc9702f9426aa8bfe70f6823ad203
95bae374096613a003b71583d911470d94b26717
refs/heads/master
<repo_name>hirohito-protagonist/snake<file_sep>/src/ui.rs extern crate piston_window; extern crate find_folder; use piston_window::*; use crate::theme; pub struct UI { width: i32, height: i32, } impl UI { pub fn new(viewport: (u32, u32)) -> UI { let (width, height) = viewport; UI{ width: width as i32, height: height as i32, } } pub fn render_game_over(&self, context: &Context, g: &mut G2d, glyphs: &mut piston_window::glyph_cache::rusttype::GlyphCache<GfxFactory, G2dTexture>) { let pos_x = (((self.width * 10) as f32 / 2.0) - 60.0).into(); let pos_y = (((self.height * 10) as f32 / 2.0) + 16.0).into(); let game_over_pos = context.transform.trans(pos_x, pos_y); let reset_information_pos = context.transform.trans(pos_x - 25.0, pos_y + 18.0); text::Text::new_color(theme::TEXT_COLOR, 32).draw( "Game Over", glyphs, &context.draw_state, game_over_pos, g ).unwrap(); text::Text::new_color(theme::TEXT_COLOR, 18).draw( "Press SPACEBAR to reset", glyphs, &context.draw_state, reset_information_pos, g ).unwrap(); } pub fn render_pause(&self, context: &Context, g: &mut G2d, glyphs: &mut piston_window::glyph_cache::rusttype::GlyphCache<GfxFactory, G2dTexture>) { let pos_x = (((self.width * 10) as f32 / 2.0) - 60.0).into(); let pos_y = (((self.height * 10) as f32 / 2.0) + 16.0).into(); let pause_pos = context.transform.trans(pos_x, pos_y); text::Text::new_color(theme::TEXT_COLOR, 32).draw( "Pause", glyphs, &context.draw_state, pause_pos, g ).unwrap(); } pub fn render_score(&self, score: u32, context: &Context, g: &mut G2d, glyphs: &mut piston_window::glyph_cache::rusttype::GlyphCache<GfxFactory, G2dTexture>) { let transform = context.transform.trans((self.width * 10 - 200).into(), (self.height * 10 + 15).into()); text::Text::new_color(theme::TEXT_COLOR, 18).draw( &format!("Score: {}", score), glyphs, &context.draw_state, transform, g ).unwrap(); } pub fn render_title(&self, context: &Context, g: &mut G2d, glyphs: &mut piston_window::glyph_cache::rusttype::GlyphCache<GfxFactory, G2dTexture>) { let transform = context.transform.trans(10.0, (self.height * 10 + 15).into()); text::Text::new_color(theme::TEXT_COLOR, 18).draw( "Snake v0.0.1", glyphs, &context.draw_state, transform, g ).unwrap(); } }<file_sep>/src/food.rs use piston_window::{Context, G2d}; use crate::draw::{draw_block}; use rand::{thread_rng, Rng}; use rand::rngs::{ThreadRng}; use crate::theme; pub struct Food { x: u32, y: u32, rng: ThreadRng, } impl Food { pub fn new(x: u32, y: u32) -> Food { Food{ x, y, rng: thread_rng(), } } pub fn render(&self, context: &Context, g: &mut G2d) { draw_block(theme::FOOD_COLOR, self.x, self.y, context, g); } pub fn reposition(&mut self, width: u32, height: u32) { let new_x = self.rng.gen_range(1, width - 1); let new_y = self.rng.gen_range(1, height - 1); self.x = new_x; self.y = new_y; } pub fn position(&self) -> (u32, u32) { (self.x, self.y) } } #[cfg(test)] mod food_tests { use crate::food::{Food}; #[test] fn it_should_reposition_in_the_field_boundaries() { // Given let field_width = 10; let field_height = 10; let mut food = Food::new(200, 300); // When food.reposition(field_width, field_height); // Then let (food_x, food_y) = food.position(); assert!(food_x <= field_width); assert!(food_y <= field_height); } }<file_sep>/README.md # snake This is a classic Snake game. ![](/docs/screenshots/snake.png) # Prerequisites * OS X, Windows or Linux * [Rust](https://www.rust-lang.org/learn/get-started) # Getting Started **Step 1**. Clone the latest version of **snake** on your local machine by running: ```shell $ git clone https://github.com/hirohito-protagonist/snake.git $ cd snake ``` **Step 2**. Run the game: ```shell $ cargo run ``` # How to play Move the Snake around using the keyboard arrows and eat food. The more food you eat the more points you gain and the more the Snake goes faster. * <kbd>&#8592;</kbd> <kbd>&#8593;</kbd> <kbd>&#8594;</kbd> <kbd>&#8595;</kbd> -move around * <kbd>esc</kbd> - quit * <kbd>p</kbd> - pause * <kbd>r</kbd> - reset * <kbd>spacebar</kbd> - reset after game over # License [UNLICENSE](/LICENSE)<file_sep>/src/main.rs extern crate piston_window; extern crate find_folder; mod types; mod draw; mod theme; mod food; mod snake; mod ui; mod game; mod window; fn main() { let viewport: (u32, u32) = (80, 58); let mut game = game::Game::new(viewport); let mut game_window = window::GameWindow::new(viewport); game_window.game_loop(&mut game); } <file_sep>/src/theme.rs use piston_window::types::Color; const INVERSE_255: f32 = 1.0f32 / 255.0f32; pub const TEXT_COLOR: Color = [51.0 * INVERSE_255, 101.0 * INVERSE_255, 68.0 * INVERSE_255, 1.0]; pub const BACKGROUND_COLOR: Color = [17.0 * INVERSE_255, 57.0 * INVERSE_255, 48.0 * INVERSE_255, 1.0]; pub const SNAKE_COLOR: Color = [65.0 * INVERSE_255, 130.0 * INVERSE_255, 88.0 * INVERSE_255, 1.0]; pub const FOOD_COLOR: Color = [71.0 * INVERSE_255, 143.0 * INVERSE_255, 94.0 * INVERSE_255, 1.0]; pub const BORDER_COLOR: Color = [35.0 * INVERSE_255, 82.0 * INVERSE_255, 57.0 * INVERSE_255, 1.0];<file_sep>/src/window.rs use piston_window::*; use crate::game::{Game}; use crate::theme; pub struct GameWindow { window: PistonWindow, events: Events, font: Glyphs } impl GameWindow { pub fn new(viewport: (u32, u32)) -> GameWindow { const UPDATES_PER_SECOND: u64 = 60; let window_resolution: (u32, u32) = (viewport.0 * 10, (viewport.1 * 10) + 20); let window: PistonWindow = WindowSettings::new("Snake", window_resolution) .exit_on_esc(true) .vsync(true) .resizable(false) .build() .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) }); let assets = find_folder::Search::ParentsThenKids(3, 3).for_folder("assets").unwrap(); let ref font = assets.join("FiraSans-Regular.ttf"); let factory = window.factory.clone(); let font = Glyphs::new(font, factory, TextureSettings::new()).unwrap(); let events = Events::new(EventSettings::new()) .max_fps(UPDATES_PER_SECOND) .ups(UPDATES_PER_SECOND); GameWindow{ window, events, font } } pub fn game_loop(&mut self, game: &mut Game) { let events = &mut self.events; let window = &mut self.window; let font = &mut self.font; while let Some(e) = events.next(window) { if let Some(Button::Keyboard(key)) = e.press_args() { game.key_pressed(key); } window.draw_2d(&e, |_c, g| { clear(theme::BACKGROUND_COLOR, g); game.render(&_c, g, font); }); e.update(|arg| { game.update(arg.dt); }); } } }<file_sep>/src/snake.rs use std::collections::LinkedList; use piston_window::{Context, G2d}; use crate::draw::{draw_block}; use crate::types::{Block, Direction}; use crate::theme; pub struct Snake { body: LinkedList<Block>, direction: Direction, last_tail_block: Option<Block> } impl Snake { pub fn new(x: u32, y: u32) -> Snake { let mut body = LinkedList::new(); body.push_back(Block { x: x + 2, y, }); body.push_back(Block { x: x + 1, y, }); body.push_back(Block { x, y, }); Snake { body, direction: Direction::Right, last_tail_block: None, } } pub fn render(&self, context: &Context, g: &mut G2d) { for block in &self.body { draw_block(theme::SNAKE_COLOR, block.x, block.y, context, g); } } pub fn move_forward(&mut self, direction: Option<Direction>) { match direction { Some(d) => self.direction = d, None => (), } self.body.push_front(self.create_block()); let tail = self.body.pop_back().unwrap(); self.last_tail_block = Some(tail); } pub fn head_position(&self) -> (u32, u32) { let head_block = self.body.front().unwrap(); (head_block.x, head_block.y) } pub fn next_head(&self, dir: Option<Direction>) -> (u32, u32) { let (head_x, head_y): (u32, u32) = self.head_position(); let mut moving_dir = self.direction; match dir { Some(d) => moving_dir = d, None => {} } match moving_dir { Direction::Up => (head_x, head_y - 1), Direction::Down => (head_x, head_y + 1), Direction::Left => (head_x - 1, head_y), Direction::Right => (head_x + 1, head_y), } } pub fn head_direction(&self) -> Direction { self.direction } pub fn is_tail_collision(&self, x: u32, y: u32) -> bool { let mut ch = 0; for block in &self.body { if x == block.x && y == block.y { return true; } ch += 1; if ch == self.body.len() - 1 { break; } } return false; } pub fn add_tail(&mut self) { match &self.last_tail_block { Some(block) => self.body.push_back(block.clone()), None => (), } } pub fn is_alive(&self, dir: Option<Direction>, viewport: (u32, u32)) -> bool { let (next_x, next_y) = self.next_head(dir); if self.is_tail_collision(next_x, next_y) { return false; } next_x > 0 && next_y > 0 && next_x < viewport.0 - 1 && next_y < viewport.1 - 1 } fn create_block(&self) -> Block { let (last_x, last_y): (u32, u32) = self.head_position(); let new_block = match self.direction { Direction::Up => Block { x: last_x, y: last_y - 1, }, Direction::Down => Block { x: last_x, y: last_y + 1, }, Direction::Left => Block { x: last_x - 1, y: last_y, }, Direction::Right => Block { x: last_x + 1, y: last_y, }, }; new_block } } #[cfg(test)] mod snake_tests { use crate::snake::{Snake}; use crate::types::{Direction}; #[test] fn it_should_be_created_from_3_segments_on_initial() { // Given let mut snake = Snake::new(0, 0); // When let (head_x, head_y) = snake.head_position(); // Then assert_eq!(snake.body.len(), 3); assert_eq!(head_x, 2); assert_eq!(head_y, 0); } #[test] fn it_move_snake_and_store_lat_tail_position() { // Given let mut snake = Snake::new(0, 0); // When snake.move_forward(Some(Direction::Right)); let (head_x, head_y) = snake.head_position(); // Then assert_eq!(snake.direction, Direction::Right); assert_eq!(head_x, 3); assert_eq!(head_y, 0); } #[test] fn it_should_calculate_next_head_snake_position() { // Given let snake = Snake::new(0, 0); // When let actual_head_position = snake.head_position(); let future_head_position = snake.next_head(Some(Direction::Right)); // Then assert_eq!(actual_head_position.0, 2); assert_eq!(actual_head_position.1, 0); assert_eq!(future_head_position.0, 3); assert_eq!(future_head_position.1, 0); } #[test] fn it_should_add_tail_only_when_snake_was_moved_at_least_in_one_position() { // Given let mut snake = Snake::new(0, 0); // When snake.add_tail(); snake.add_tail(); snake.add_tail(); snake.add_tail(); snake.move_forward(Some(Direction::Right)); snake.add_tail(); snake.move_forward(Some(Direction::Right)); snake.add_tail(); // Then assert_eq!(snake.body.len(), 5); } #[test] fn it_should_return_false_when_body_is_not_in_collision_with_head() { // Given let mut snake = Snake::new(0, 0); let (head_x, head_y) = snake.next_head(Some(Direction::Right)); // When let is_tail_collision = snake.is_tail_collision(head_x, head_y); // Then assert_eq!(is_tail_collision, false); } #[test] fn it_should_return_true_when_body_is_in_collision_with_head() { // Given let mut snake = Snake::new(0, 0); // When snake.move_forward(Some(Direction::Right)); snake.add_tail(); snake.add_tail(); snake.add_tail(); snake.add_tail(); snake.move_forward(Some(Direction::Down)); snake.move_forward(Some(Direction::Down)); snake.move_forward(Some(Direction::Left)); snake.move_forward(Some(Direction::Up)); let (head_x, head_y) = snake.next_head(Some(Direction::Right)); let is_tail_collision = snake.is_tail_collision(head_x, head_y); // Then assert_eq!(is_tail_collision, true); } }<file_sep>/src/game.rs extern crate piston_window; extern crate find_folder; use piston_window::*; use crate::draw::{draw_rectangle}; use crate::types::{Direction, State}; use crate::snake::{Snake}; use crate::food::{Food}; use crate::theme; use crate::ui::{UI}; pub struct Game { snake: Snake, width: u32, height: u32, ui: UI, food: Food, state: State, } impl Game { pub fn new(viewport: (u32, u32)) -> Game { let (width, height) = viewport; Game{ snake: Snake::new(1, 1), width, height, ui: UI::new(viewport), state: State::new(), food: Food::new(10, 20), } } pub fn render(&self, context: &Context, g: &mut G2d, glyphs: &mut piston_window::glyph_cache::rusttype::GlyphCache<GfxFactory, G2dTexture>) { if self.state.is_pause() && !self.state.is_game_over() { self.ui.render_pause(context, g, glyphs); } if !self.state.is_game_over() { self.snake.render(context, g); } if self.state.is_food_exists() { self.food.render(context, g); } draw_rectangle(theme::BORDER_COLOR, 0, 0, self.width, 1, context, g); draw_rectangle(theme::BORDER_COLOR, 0, self.height - 1, self.width, 1, context, g); draw_rectangle(theme::BORDER_COLOR, 0, 0, 1, self.height, context, g); draw_rectangle(theme::BORDER_COLOR, self.width - 1, 0, 1, self.height, context, g); self.ui.render_score(self.state.get_score(), context, g, glyphs); self.ui.render_title(context, g, glyphs); if self.state.is_game_over() { self.ui.render_game_over(context, g, glyphs); } } pub fn key_pressed(&mut self, key: Key) { if key == Key::P { self.state.set_pause(!self.state.is_pause()); } if self.state.is_pause() && !self.state.is_game_over() { return; } if !self.state.is_pause() && !self.state.is_game_over() && key == Key::R { self.restart(); } if self.state.is_game_over() { match key { Key::Space => self.restart(), _ => {} } } let direction = match key { Key::Up => Some(Direction::Up), Key::Down => Some(Direction::Down), Key::Left => Some(Direction::Left), Key::Right => Some(Direction::Right), _ => Some(self.snake.head_direction()) }; if direction.unwrap() == self.snake.head_direction().opposite() { return; } self.update_snake(direction); } pub fn update(&mut self, delta_time: f64) { if self.state.is_pause() { return; } self.state.add_waiting_time(delta_time); if self.state.get_waiting_time() > self.state.get_snake_speed() { self.update_snake(None); } if !self.state.is_food_exists() { self.add_food(); } } fn update_snake(&mut self, direction: Option<Direction>) { if self.snake.is_alive(direction, (self.width, self.height)) { self.snake.move_forward(direction); self.check_eating(); } else { self.state.set_game_over(true); } self.state.set_waiting_time(0.0); } fn add_food(&mut self) { self.food.reposition(self.width, self.height); let (mut food_x, mut food_y): (u32, u32) = self.food.position(); while self.snake.is_tail_collision(food_x, food_y) { self.food.reposition(self.width, self.height); let new_food_position = self.food.position(); food_x = new_food_position.0; food_y = new_food_position.1; } self.state.set_food_exists(true); } fn check_eating(&mut self) { let (head_x, head_y): (u32, u32) = self.snake.head_position(); let (food_x, food_y): (u32, u32) = self.food.position(); if self.state.is_food_exists() && food_x == head_x && food_y == head_y { self.state.set_food_exists(false); self.snake.add_tail(); self.state.increase_score(); self.state.speed_up_snake(); } } fn restart(&mut self) { self.snake = Snake::new(1, 1); self.state = State::new(); self.food = Food::new(10, 20); } }<file_sep>/src/types.rs #[derive(Debug, Copy, Clone, PartialEq)] pub struct Block { pub x: u32, pub y: u32, } #[derive(Debug, Copy, Clone, PartialEq)] pub enum Direction { Up, Down, Left, Right, } impl Direction { pub fn opposite(&self) -> Direction { match *self { Direction::Up => Direction::Down, Direction::Down => Direction::Up, Direction::Left => Direction::Right, Direction::Right => Direction::Left, } } } pub struct State { waiting_time: f64, is_game_over: bool, food_exist: bool, pub score: u32, snake_speed: f64, is_pause: bool, } impl State { pub fn new() -> State { State{ waiting_time: 0.0, is_game_over: false, food_exist: false, score: 0, snake_speed: 0.1, is_pause: false, } } pub fn speed_up_snake(&mut self) { if self.snake_speed > 0.04 { self.snake_speed = self.snake_speed - 0.01; } } pub fn get_snake_speed(&self) -> f64 { self.snake_speed } pub fn increase_score(&mut self) { self.score = self.score + 1; } pub fn get_score(&self) -> u32 { self.score } pub fn add_waiting_time(&mut self, t: f64) { self.waiting_time = self.waiting_time + t; } pub fn set_waiting_time(&mut self, t: f64) { self.waiting_time = t; } pub fn get_waiting_time(&self) -> f64 { self.waiting_time } pub fn is_game_over(&self) -> bool { self.is_game_over } pub fn set_game_over(&mut self, game_over: bool) { self.is_game_over = game_over; } pub fn is_pause(&self) -> bool { self.is_pause } pub fn set_pause(&mut self, pause: bool) { self.is_pause = pause; } pub fn is_food_exists(&self) -> bool { self.food_exist } pub fn set_food_exists(&mut self, food_exists: bool) { self.food_exist = food_exists; } } #[cfg(test)] mod state_tests { use crate::types::{State}; #[test] fn it_should_increase_score_by_one_point() { // Given let mut state = State::new(); // When state.increase_score(); state.increase_score(); // Then assert_eq!(state.score, 2); } #[test] fn it_should_speed_up_snake_until_reach_max_speed() { // Given let mut state = State::new(); // When state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); state.speed_up_snake(); // Then assert_eq!(state.snake_speed, 0.030000000000000013); } }
b4707dcf08b4cd6f48816c206ce38fd43b995256
[ "Markdown", "Rust" ]
9
Rust
hirohito-protagonist/snake
ff2cf3a8577ef67d7f8bd2e0542c9ff877d41515
323390712f6ef178f3cbdda46af7871fe204c554
refs/heads/master
<file_sep> module.exports.controller = function(app, passport) { app.get('/', function(req, res) { res.send('respond with a resource'); }); }<file_sep>var socket = io.connect(); var imageID = null var userData = null var mode = "RECTANGLE"; var imageObj = null; var img = null; var lastMouseDownX = null; var lastMouseDownY = null; var objectStack = []; var eventStack = []; var tmpRect = null; var actionCounter = 0; var currentObjectID = 0; var globalBrightness = 0; var users = ['0']; function hsvToRgb(h, s, v){ var r, g, b; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch(i % 6){ case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return [r * 255, g * 255, b * 255]; } function getColor(index) { var oneTwenties = index % 3; var offsetIterations = Math.floor(index / 3); var offset = 0; var currentPartOffset = 60; if(offsetIterations > 0) { while(offsetIterations>0) { console.log("Iteration!") offset += currentPartOffset; currentPartOffset /= 2; offsetIterations -= 1; } } return hsvToRgb((oneTwenties*120 + offset) % 360 / 360, 1, 1); } var joinToRoom = function(imageID) { socket.emit("joinToRoom", imageID); } var prepareDataToSend = function(data) { data = $.extend({}, data, { "imageID":imageID, "userID": userData.id, }) return {data: data, email:userData.email}; } $('#chat-form').submit(function(){ var msg = $('#message-to-send').val() var data = prepareDataToSend({"msg":msg}); socket.emit('message', data); $('#messages').append($('<li class="alert alert-info">').text(msg)); $(".chat-wrapper").scrollTop($(".chat-wrapper")[0].scrollHeight); $('#message-to-send').val(''); return false; }); $('#send-chat-form').click(function(){ $('#chat-form').submit() return false; }); socket.on('message-from-others', function(data){ var email = data.email var msg = data.data.msg $('#messages').append($('<li class="alert alert-info">').text(msg.toString())); $(".chat-wrapper").scrollTop($(".chat-wrapper")[0].scrollHeight); }); function getObjectByID(id) { for(var i = 0; i<objectStack.length; i++) { if(objectStack[i].hasOwnProperty('orderID')) { if(objectStack[i].orderID == id) { return objectStack[i]; } } } return null; } function addSimpleCircle(x,y,l, objectID, userID) { var index = 0; if(users.indexOf(userID) == -1) { users.push(userID); index = users.length -1; } else { index = users.indexOf(userID); } var rgb = getColor(index); var circle = new Kinetic.Circle({ x: x, y: y, radius: 5, fill: 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')', stroke: 'black', strokeWidth: 2, draggable: true }); circle.orderID = objectID; circle.on('dragend', function() { actionCounter += 1; var data = { mode: "update", x: circle.x(), y: circle.y(), objectID: circle.orderID }; eventStack.push(data); data = prepareDataToSend(data); socket.emit('draw', data); //$.post( "server.php", data); $('#historyitems').append("<li>"+ data.mode + ", objID: " + data.objectID + "</li>"); console.log("POST request sent with data: "); console.log(data); }); l.add(circle); objectStack.push(circle); l.draw(); $('#historyitems').append("<li>create, objID: " + objectID + "</li>"); } function addSimpleTooltip(x,y,l, text, objectID, userID) { var index = 0; if(users.indexOf(userID) == -1) { users.push(userID); index = users.length -1; } else { index = users.indexOf(userID); } var rgb = getColor(index); var tooltip = new Kinetic.Label({ x: x, y: y, opacity: 0.75 }); tooltip.add(new Kinetic.Tag({ fill: 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')', pointerDirection: 'down', pointerWidth: 10, pointerHeight: 10, lineJoin: 'round', shadowColor: 'black', shadowBlur: 10, shadowOffset: {x:10,y:20}, shadowOpacity: 0.5 })); tooltip.add(new Kinetic.Text({ text: text, fontFamily: 'Calibri', fontSize: 18, padding: 5, fill: 'white' })); tooltip.orderID = objectID; l.add(tooltip); objectStack.push(tooltip); l.draw(); $('#historyitems').append("<li>create, objID: " + objectID + "</li>"); } function addSimpleRectangle(x, y, width, height, layer, objectID, userID) { var index = 0; if(users.indexOf(userID) == -1) { users.push(userID); index = users.length -1; } else { index = users.indexOf(userID); } var rgb = getColor(index); var rect = new Kinetic.Rect({ x: x, y: y, width: width, height: height, fill: 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')', stroke: 'black', strokeWidth: 4, draggable: true, opacity: 0.4 }); rect.orderID = objectID; rect.on('dragend', function() { actionCounter +=1; var data = { mode: "update", x: rect.x(), y: rect.y(), objectID: rect.orderID}; eventStack.push(data); //$.post( "server.php", data); data = prepareDataToSend(data); socket.emit('draw', data); $('#historyitems').append("<li>"+ data.mode + ", objID: " + data.objectID + "</li>"); console.log("POST request sent with data: "); console.log(data); }); layer.add(rect); objectStack.push(rect); layer.draw(); } var performAction = function(obj) { if(obj.mode == "create") { if(obj.type == "circle") { actionCounter += 1; addSimpleCircle(obj.x, obj.y, layer, obj.objectID, obj.userID); currentObjectID = obj.objectID + 1; } else if(obj.type == "tooltip") { actionCounter += 1; addSimpleTooltip(obj.x, obj.y, layer, obj.content, obj.objectID, obj.userID); currentObjectID = obj.objectID + 1; } else if(obj.type == "rectangle") { actionCounter += 1; addSimpleRectangle(obj.x, obj.y, obj.width, obj.height, layer, obj.objectID, obj.userID); currentObjectID = obj.objectID + 1; } } else if(obj.mode == "update") { actionCounter += 1; eventStack.push(obj); var o = getObjectByID(obj.objectID); o.x(obj.x); o.y(obj.y); layer.draw(); } else if(obj.mode == "delete") { actionCounter += 1; eventStack.push(obj); var o = getObjectByID(obj.objectID); if(o != null) { o.remove(); layer.draw(); } } } //ACTION OF OTHER USERS socket.on('draw', function(obj){ var email = obj.email console.log(email) obj = obj.data console.log(obj) performAction(obj) }); var stage = new Kinetic.Stage({ container: 'container', width: 1024, height: 768 }); var layer = new Kinetic.Layer(); var imageLayer = new Kinetic.Layer(); var rect = new Kinetic.Rect({ x: 239, y: 75, width: 100, height: 20, fill: 'green', stroke: 'black', strokeWidth: 4, draggable: true }); function addCircle(x,y,l) { var rgb = getColor(0); var circle = new Kinetic.Circle({ x: x, y: y, radius: 5, fill: 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')', stroke: 'black', strokeWidth: 2, draggable: true }); circle.on('dragend', function() { actionCounter += 1; var data = { mode: "update", x: circle.x(), y: circle.y(), objectID: circle.orderID }; eventStack.push(data); dataToSend = prepareDataToSend(data); socket.emit('draw', dataToSend); //$.post( "server.php", data); $('#historyitems').append("<li>"+ data.data.mode + ", objID: " + data.data.objectID + "</li>"); console.log("POST request sent with data: "); console.log(data.data); }); circle.orderID = currentObjectID; currentObjectID += 1; l.add(circle); objectStack.push(circle); actionCounter += 1 l.draw(); var data = { type: "circle", mode: "create", x: x, y: y, objectID: circle.orderID}; eventStack.push(data); data = prepareDataToSend(data); socket.emit('draw', data); //$.post( "server.php", data); $('#historyitems').append("<li>"+ data.data.mode + ", objID: " + data.data.objectID + "</li>"); console.log("POST request sent with data: "); console.log(data.data); } function addTooltip(x,y,l, text) { var rgb = getColor(0); var tooltip = new Kinetic.Label({ x: x, y: y, opacity: 0.75 }); tooltip.add(new Kinetic.Tag({ fill: 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')', pointerDirection: 'down', pointerWidth: 10, pointerHeight: 10, lineJoin: 'round', shadowColor: 'black', shadowBlur: 10, shadowOffset: {x:10,y:20}, shadowOpacity: 0.5 })); tooltip.add(new Kinetic.Text({ text: text, fontFamily: 'Calibri', fontSize: 18, padding: 5, fill: 'white' })); tooltip.orderID = currentObjectID; currentObjectID += 1; l.add(tooltip); objectStack.push(tooltip); l.draw(); actionCounter += 1; var data = { type: "tooltip", mode: "create", content: text, x: x, y: y, objectID: tooltip.orderID }; //$.post( "server.php", data); data = prepareDataToSend(data); socket.emit('draw', data); $('#historyitems').append("<li>"+ data.data.mode + ", objID: " + data.data.objectID + "</li>"); eventStack.push(data.data); console.log("POST request sent with data: "); console.log(data.data); } function loadSampleImage() { imageObj = new Image(); imageObj.onload = function() { img = new Kinetic.Image({ x: 0, y: 0, image: imageObj, width: 1000, height: 500 }); //img.cache(); img.filters([Kinetic.Filters.Brighten]); imageLayer.add(img); imageLayer.draw(); }; //imageObj.src = 'sampleimage.jpg'; //console.log($('#editor-panel .image-buffer img').attr('src')); imageObj.src = $('#editor-panel .image-buffer img').attr('src'); } function loadImage() { imageObj = new Image(); imageObj.onload = function() { img = new Kinetic.Image({ x: 0, y: 0, image: imageObj, width: 1000, height: 500 }); //img.cache(); img.filters([Kinetic.Filters.Brighten]); imageLayer.add(img); imageLayer.draw(); }; imageID =$('#editor-panel .image-buffer')[0].getAttribute("data-id").toString() $.getJSON('/api/actions/' + imageID, function(data){ if (data.status && data.status == "OK") { var actions = data.actions $.each( actions, function( key, val ) { if (val.userID == userData.id) { $('#historyitems').append("<li>"+ val.mode + ", objID: " + val.objectID + "</li>"); } performAction(val) }); } }) joinToRoom(imageID) imageObj.src = $('#editor-panel .image-buffer img').attr('src'); // console.log($('#editor-panel .image-buffer img').attr('src')); } function invertImage() { img.cache(); img.filters([Kinetic.Filters.Invert, Kinetic.Filters.Brighten]); imageLayer.draw(); } function grayscaleImage() { img.cache(); img.filters([Kinetic.Filters.Grayscale, Kinetic.Filters.Brighten]); imageLayer.draw(); } function brightenImage() { img.cache(); img.filters([Kinetic.Filters.Grayscale, Kinetic.Filters.Brighten]); imageLayer.draw(); } $('#container').on('click', function(e) { var posX = e.clientX - $(this).offset().left; var posY = e.clientY - $(this).offset().top; if(mode == "POINT") addCircle(posX, posY, layer); if(mode == "TEXT") { var text = prompt("Please enter your text", ""); if(text != null) addTooltip(posX, posY, layer, text); } }); $(document).ready( function() { loadImage(); userData = JSON.parse(sessionStorage.getItem('user')) $(".back-to-images-button").click(function(){ socket.emit("leaveRoom", imageID) }) }); $('#container').on('mousedown', function(e) { if(mode != "RECTANGLE") return; lastMouseDownX = e.clientX - $(this).offset().left; lastMouseDownY = e.clientY - $(this).offset().top; var rgb = getColor(0); var rect = new Kinetic.Rect({ x: lastMouseDownX, y: lastMouseDownY, width: 1, height: 1, fill: 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')', stroke: 'black', strokeWidth: 4, draggable: true, opacity: 0.4 }); rect.on('dragend', function() { actionCounter +=1; var data = { mode: "update", x: rect.x(), y: rect.y(), objectID: rect.orderID}; eventStack.push(data); //$.post( "server.php", data); data = prepareDataToSend(data); socket.emit('draw', data); $('#historyitems').append("<li>"+ data.data.mode + ", objID: " + data.data.objectID + "</li>"); console.log("POST request sent with data: "); console.log(data.data); }); rect.orderID = currentObjectID; currentObjectID += 1; layer.add(rect); objectStack.push(rect); tmpRect = rect; layer.draw(); }); $('#container').on('mouseup', function(e) { if(mode == "RECTANGLE") { actionCounter += 1; var data = { type: "rectangle", mode: "create", width: tmpRect.width(), height: tmpRect.height(), x: tmpRect.x(), y: tmpRect.y(), objectID: tmpRect.orderID}; eventStack.push(data); //$.post( "server.php", data); data = prepareDataToSend(data); socket.emit('draw', data); $('#historyitems').append("<li>"+ data.data.mode + ", objID: " + data.data.objectID + "</li>"); console.log("POST request sent with data: "); console.log(data.data); tmpRect = null; } }); $('#container').on('mousemove', function(e) { var posX = e.clientX - $(this).offset().left; var posY = e.clientY - $(this).offset().top; if(mode == "RECTANGLE" && tmpRect != null) { tmpRect.width(Math.abs(posX - lastMouseDownX)); tmpRect.height(Math.abs(posY - lastMouseDownY)); layer.draw(); } }); $('#rectangle').on('click', function(e) { $('#modes').children('button').each(function () { $(this).css('font-weight', 'normal'); }); $(this).css('font-weight', 'bolder'); mode = "RECTANGLE"; }); $('#point').on('click', function(e) { $('#modes').children('button').each(function () { $(this).css('font-weight', 'normal'); }); $(this).css('font-weight', 'bolder'); mode = "POINT"; }); $('#text').on('click', function(e) { $('#modes').children('button').each(function () { $(this).css('font-weight', 'normal'); }); $(this).css('font-weight', 'bolder'); mode = "TEXT"; }); $('#none').on('click', function(e) { $('#modes').children('button').each(function () { $(this).css('font-weight', 'normal'); }); $(this).css('font-weight', 'bolder'); mode = "NONE"; }); $('#loadImage').on('click', function(e) { loadSampleImage(); }); $('#invertFilter').on('click', function(e) { invertImage(); }); $('#grayscaleFilter').on('click', function(e) { grayscaleImage(); }); $('#brightenFilterUP').on('click', function(e) { img.cache(); globalBrightness += 0.1; img.brightness(globalBrightness); imageLayer.batchDraw(); }); $('#brightenFilterDOWN').on('click', function(e) { img.cache(); globalBrightness -= 0.1; img.brightness(globalBrightness); imageLayer.batchDraw(); }); $('#download').on('click', function(e) { /*var canvasData = stage.toDataURL("image/jpeg"); var ajax = new XMLHttpRequest(); ajax.open("POST","/api/images/" + imageID + "/download",false); ajax.setRequestHeader('Content-Type', 'application/upload'); ajax.send(canvasData); */ stage.toDataURL({ mimeType: "image/jpeg", quality: 1.0, callback: function(dataUrl) { var formData = new FormData(); formData.append('images', dataUrl); console.log("start") $.ajax({ type: "POST", url: '/api/images/' + imageID + '/download', data: formData, processData: false, contentType: false, success: function(data){ if (data.status == "OK") { data = JSON.parse(sessionStorage.getItem('user')); window.location = "/api/images/" + imageID+ "/download?token=" + data.token } } }); //window.open(dataUrl); } }); }); $('#undo').on('click', function(e) { var lastEvent = eventStack.pop(); if(lastEvent != null) { if(lastEvent.mode == "create") { var item = objectStack.pop(); if(item != null) { actionCounter +=1; var data = { mode: "delete", objectID: item.orderID}; //$.post( "server.php", data); data = prepareDataToSend(data); socket.emit('draw', data); $('#historyitems').append("<li>"+ data.data.mode + ", objID: " + data.data.objectID + "</li>"); console.log("POST request sent with data: "); console.log(data.data); item.remove(); layer.draw(); } } else if(lastEvent.mode == "update") { actionCounter += 1; var id = lastEvent.objectID; for(var i = eventStack.length -1; i >= 0; i--) { if((eventStack[i].mode == "create" || eventStack[i].mode == "update") && eventStack[i].objectID == id) { var obj = getObjectByID(id); obj.x(eventStack[i].x); obj.y(eventStack[i].y); layer.draw(); actionCounter +=1; $('#historyitems').append("<li>"+ data.mode + ", objID: " + data.objectID + "</li>"); var data = { mode: "update", x: obj.x(), y: obj.y(), objectID: obj.orderID}; //$.post( "server.php", data); data = prepareDataToSend(data); socket.emit('draw', data); break; } } } } }); rect.on('mouseover', function() { document.body.style.cursor = 'pointer'; }); rect.on('mouseout', function() { document.body.style.cursor = 'default'; }); stage.add(imageLayer); stage.add(layer); <file_sep>var Account = require('../models/account'); module.exports.controller = function(app, passport) { app.post('/sign-in', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { res.render('messages', {error: 'Unknown Error.'}); } if (!user) { res.render('messages', {error: 'Incorrect login or password!'}); } if (!err && user) { Account.createToken(user.email, function(err, createdToken) { if (err) { res.render('messages',{error: 'Error during token generating'}); } else { console.log({email: user.email, id: user._id, token : createdToken}) res.json({email: user.email, id: user._id, token : createdToken}); } }); } })(req, res, next); }) app.get('/sign-in', function(req, res) { res.render('sign-in') }); app.get('/logout(\\?)?', function(req, res) { var messages = flash('Logged out', null); var incomingToken = req.headers.token; if (incomingToken) { var decoded = Account.decode(incomingToken); if (decoded && decoded.email) { Account.invalidateUserToken(decoded.email, function(err, user) { if (err) { console.log(err); res.json({error: 'Issue finding user (in unsuccessful attempt to invalidate token).'}); } else { console.log("sending 200") res.json({message: 'logged out'}); } }); } else { console.log('Whoa! Couldn\'t even decode incoming token!'); res.json({error: 'Issue decoding incoming token.'}); } } }); }<file_sep>var Account = require('../models/account'); module.exports.controller = function(app, passport) { var getUser = function(req, res, next) { console.log("getUser") var token = req.headers['x-token'] || req.param('token') || null; if (token !== null) { Account.checkUserToken(token, function(isLoggedIn, usr) { if (isLoggedIn) { req.user = usr next(); } else { res.redirect('/sign-in') } }) } else { res.redirect('/sign-in') } } app.all('/api', function(req, res, next) { console.log("/API") getUser(req,res,next) }); app.all('/api/*', function(req, res, next) { console.log("/API/*") getUser(req,res,next) }); app.get('/api', function(req, res) { user = req.user || false//app.get('user') res.render('api', { title: 'Image TeleConsult', success: req.param('success'), email:user.email}); }); app.get('/', function(req, res) { res.redirect('/api'); }); app.get('/api/sign-out', function(req, res) { var token = req.headers['x-token'] || req.param('token') || null; if (token) { Account.removeToken(token, function(err, usr) { if (!err) { //app.set('user', false) res.json({isLoggedOut: true}); } else { console.log("Error during log out.") } }) } }); }<file_sep>var mongoose = require('mongoose') Schema = mongoose.Schema var permissionSchema = new Schema({ imageID: { type: Schema.Types.ObjectId, required: true }, userID: { type: Schema.Types.ObjectId, required: true }, }) permissionSchema.index({imageID: 1, userID: 1}, {unique: true, dropDups: true }); var Permission = mongoose.model('Permission', permissionSchema); module.exports = Permission; <file_sep>var isEmail = function(value) { if (value == '') { return true; } var emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return emailRegExp.test(value); } var ajaxWithLoader = function(obj) { var settings = { beforeSend: function(xhr, settings) { $.loader({ className:"blue-with-image-2", content:'' }); }, complete: function(xhr, textStatus) { $.loader('close') } } var object = $.extend(obj, settings); $.ajax(object) } $('document').ready(function() { $.ajaxSetup({ beforeSend: function(xhr, settings) { user = sessionStorage.getItem('user'); if (user) { user = JSON.parse(user) if (user && user.token) { xhr.setRequestHeader('X-Token', user.token); } console.log(user) } else { console.log("Unknown user") } }, }); $("#form-sign-up").bootstrapValidator(); $("#form-sign-in").bootstrapValidator(); $('#list-of-tabs a').click(function (e) { e.preventDefault() console.log("click") $(this).tab('show') }); $("#cooperators-filter-text").on("change", function(evt){ $(".search-user-help").removeClass("text-danger") if (!isEmail($(this).val())) { $("#add-permission").prop('disabled', true) $(".search-user-help").addClass("text-danger") $(".search-user-help").html("Value is not a correct email addres") } else { $("#add-permission").prop('disabled', false) $(".search-user-help").html("") } }) $("#form-sign-in").submit(function() { var self = this ajaxWithLoader({ type: "POST", url: "/sign-in", data: $("#form-sign-in").serialize(), success: function(data){ if (data.token) { sessionStorage.setItem('user', JSON.stringify({email: data.email, id: data.id, token: data.token})); window.location.replace("/api?token=" + data.token ); } else { $(self).find("#messages").html(data) } }, }); return false; }); $("#form-sign-up").submit(function() { var self = this ajaxWithLoader({ type: "POST", url: "/sign-up", data: $("#form-sign-up").serialize(), success: function(data){ if (data.token) { sessionStorage.setItem('user', JSON.stringify({email: data.email, token: data.token})); window.location.replace("/api?token=" + data.token ); } else { $(self).find("#messages").html(data) } }, }); return false; }); $("#delete-account-confirm-button").click(function(){ $.ajax({ type: "DELETE", url: "/api/accounts", success: function(data){ if (data.status=="OK") { sessionStorage.removeItem('user'); window.location.replace("sign-up"); } }, }); }) $("#sign-out-button").click(function() { $.ajax({ type: "GET", url: "/api/sign-out", success: function(data){ if (data.isLoggedOut) { sessionStorage.removeItem('user'); window.location.replace("sign-in"); } }, }); return false; }) $("#image-upload-form").submit(function(event) { var self = this event.stopPropagation(); event.preventDefault(); var fileSelect = $(this).find("#image-select")[0] var formData = new FormData(); var files = fileSelect.files if (files.length > 0) { for (var i = 0; i < files.length; i++) { var file = files[i]; if (file.type.match('image.*') || file.type.match('.*dicom')) { formData.append('images', file, file.name); } } $.ajax({ type: "POST", url: "/api/images", data: formData, xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentage = Math.round((evt.position / evt.total) * 100) $("#progress-image-upload").val(percentage) } }, false); xhr.upload.addEventListener("load", function(evt) { if (evt.lengthComputable) { $("#progress-image-upload").val(0) } }, false); return xhr; }, processData: false, contentType: false, success: function(data){ if (data.status == "OK") { $("#images").load('/api/images', function(err){ $(this).trigger("load") }); } }, }); } return false; }); $("#cooperators-list").load(function(evt) { $(this).find(".remove-cooperator").click(function(e) { var id = $(this)[0].getAttribute("data-id").toString() var imageID = $(this)[0].getAttribute("data-image").toString() $.ajax({ type: "DELETE", url: "/api/cooperators/" + imageID + "/" + id, success: function(data){ if (data.status == "OK") { $("#cooperators-list").load("/api/cooperators/" + imageID, function(err) { $(this).trigger("load") }) } }, }); }) }) $("#editor-panel").on("load", function(evt){ var self = this console.log("on load editor") backToImages = $(this).find(".back-to-images-button") $(this).find(".back-to-images-button").click(function(evt){ $(self).empty() $("#images-panel").show() }) }) $("#images").on("load", function(event){ $(this).find(".remove-image").click(function(event){ var id = $(this)[0].getAttribute("data-id").toString() $('#delete-confirm').off(); $('#delete-confirm').click(function(){ event.stopPropagation(); event.preventDefault(); $.ajax({ type: "DELETE", url: "/api/images/" + id, processData: false, contentType: false, success: function(data){ if (data.status == "OK") { $("#images").load('/api/images', function(err){ $(this).trigger("load") }); } }, }); }); }) $(this).find(".edit-image").click(function(event){ console.log("click") var id = $(this)[0].getAttribute("data-id").toString() $("#images-panel").hide() $("#editor-panel").load('/api/images/'+id+"/editor", function(){ $("#editor-panel").trigger("load") }); }) $(this).find(".download-image").click(function(event){ var id = $(this)[0].getAttribute("data-id").toString() data = JSON.parse(sessionStorage.getItem('user')); window.location = "/api/images/" + id + "/download?token=" + data.token }) $(this).find(".select-cooperators").click(function(event){ console.log("select-cooperators") var id = $(this)[0].getAttribute("data-id").toString() var name = $(this)[0].getAttribute("data-image").toString() $("#modal-file-name").html(name) $("#cooperators-list").load("/api/cooperators/" + id, function(){ $(this).trigger("load") }) $("#add-permission").click(function(evt){ userInput = $("#cooperators-filter-text")[0] email = $(userInput).val() if (email.length > 0) { $.ajax({ type: "POST", url: "/api/cooperators/" + id +"/" + email, success: function(data){ if (data.iscomplete) { $(".search-user-help").addClass("text-success") $(".search-user-help").html(data.message) $("#cooperators-list").load("/api/cooperators/" + id, function(){ $(this).trigger("load") }) } else { $(".search-user-help").addClass("text-danger") $(".search-user-help").html(data.message) } }, }); } else { $(".search-user-help").addClass("text-danger") $(".search-user-help").html("Please enter a correct email addres") } }) }) }); $("#images").load('/api/images', function(err) { $(this).trigger("load"); }); $("#image-select").on("change", function(){ var files = this.files; if (files.length > 1) { $("#selected-image-name").html(files.length + " files selected"); } else if(files.length == 1) { $("#selected-image-name").html(files[0].name); } else { $("#selected-image-name").html("No file selected"); } }) $("#select-cooperators").ready(function(event){ console.log("load cooperators") $.ajax({ type: "GET", url: "/api/accounts", processData: false, contentType: false, success: function(data){ /*$("#images").load('/api/accounts', function(data){ console.log(data) });*/ if (data.status == "OK") { users = data.accounts.map(function(user){ return(user.email) }) console.log(users) $('input.typeahead').typeahead({ source: users }); } }, }); //var users = $.load("/api/accounts") //console.log(users) /*$(this).find(".remove-image").click(function(event){ var id = $(this)[0].getAttribute("data-id").toString() $('#delete-confirm').off(); $('#delete-confirm').click(function(){ event.stopPropagation(); event.preventDefault(); $.ajax({ type: "DELETE", url: "/api/images/" + id, processData: false, contentType: false, success: function(data){ if (data.status == "OK") { $("#images").load('/api/images', function(err){ $(this).trigger("load") }); } }, }); }); })*/ }); })<file_sep>var mongoose = require('mongoose') Schema = mongoose.Schema var imageSchema = new Schema({ originalname: {type: String, required: true}, name: { type: String, required: true }, user: { type: Schema.Types.ObjectId, required: true}, created: {type: Date, default: Date.now }, image: {type: Buffer, required:true}, size: {type: Number, required:true}, mimetype: {type: String, required: true} }) var Image = mongoose.model('Image', imageSchema); module.exports = Image; <file_sep>var mongoose = require('mongoose') var passportLocalMongoose = require('passport-local-mongoose') var Token = require('./token') var jwt = require('jwt-simple') secretString = ".,<KEY>" Schema = mongoose.Schema var accountSchema = new Schema({ email: { type: String, required: true, index: {unique:true }, lowercase:true }, created: {type: Date, default: Date.now }, token: {type: Object}, }) accountSchema.plugin(passportLocalMongoose, { usernameField: 'email' }) accountSchema.statics.createToken = function(email, callback) { var self = this; this.findOne({email: email}, function(err, usr) { var token = jwt.encode({email: email}, secretString); usr.token = new Token({token:token}); usr.save(function(err, usr) { if (err) { callback(err, null); } else { callback(false, usr.token.token); } }); }); }; accountSchema.statics.checkUserToken = function(token, callback) { var dataFromToken = false try{ var dataFromToken = jwt.decode(token, secretString); } catch(err) { dataFromToken = false } if (dataFromToken && dataFromToken.email) { var self = this; this.findOne({email: dataFromToken.email}, function(err, usr) { usr.token = new Token(usr.token) if(!err && usr && usr.token.token && token === usr.token.token && !usr.token.hasExpired()) { callback(true, usr); } else { callback(false, null); } }); } else { callback(false, null); } }; accountSchema.statics.removeToken = function(token, callback) { var dataFromToken = false try{ var dataFromToken = jwt.decode(token, secretString); } catch(err) { dataFromToken = false } if (dataFromToken && dataFromToken.email) { var self = this; this.findOne({email: dataFromToken.email}, function(err, usr) { usr.token = null; usr.save(function(err, usr) { console.log("removing...") if (err) { console.log('callback err') callback(err, null); } else { console.log('callback ok') callback(false, 'removed'); } }); }); } else { callback(false, 'incorrect token'); } }; var Account = mongoose.model('Account', accountSchema); module.exports = Account; <file_sep> var path = require('path'); var Account = require(path.join(__dirname, '..', '/models/account')); module.exports.controller = function(app, passport) { app.get('/sign-up', function(req, res) { res.render('sign-up', { title: 'Image TeleConsult' }); }); app.post('/sign-up', function(req, res) { var email = req.body.email; var password = <PASSWORD>; var user = new Account({email: email}); Account.register(user, password, function(error, account) { if (error) { res.render('messages', { error: error.message }); } else { console.log(account) Account.createToken(account.email, function(err, createdToken) { if (err) { res.render('messages',{error: 'Error during token generating'}); } else { res.json({email: user.email, token : createdToken}); } }); } }); }) }<file_sep>var mode = "RECTANGLE"; var imageObj = null; var img = null; var lastMouseDownX = null; var lastMouseDownY = null; var actionStack = []; var tmpRect = null; var actionCounter = 0; var globalBrightness = 0; var stage = new Kinetic.Stage({ container: 'container', width: 1024, height: 768 }); var layer = new Kinetic.Layer(); var imageLayer = new Kinetic.Layer(); var rect = new Kinetic.Rect({ x: 239, y: 75, width: 100, height: 20, fill: 'green', stroke: 'black', strokeWidth: 4, draggable: true }); function addBox(x,y,w,h,l) { var rect = new Kinetic.Rect({ x: x, y: y, width: w, height: h, fill: 'green', stroke: 'black', strokeWidth: 4, draggable: true }); l.add(rect); actionStack.push(rect); l.draw(); } function addCircle(x,y,l) { var circle = new Kinetic.Circle({ x: x, y: y, radius: 5, fill: 'red', stroke: 'black', strokeWidth: 2, draggable: true }); circle.on('dragend', function() { var data = { mode: "update", x: circle.x(), y: circle.y(), id: actionCounter}; $.post( "server.php", data); console.log("POST request sent with data: "); console.log(data); }); l.add(circle); actionStack.push(circle); actionCounter += 1 l.draw(); var data = { type: "circle", mode: "create", radius: 5, x: x, y: y, id: actionCounter}; $.post( "server.php", data); console.log("POST request sent with data: "); console.log(data); } function addTooltip(x,y,l, text) { var tooltip = new Kinetic.Label({ x: x, y: y, opacity: 0.75 }); tooltip.add(new Kinetic.Tag({ fill: 'red', pointerDirection: 'down', pointerWidth: 10, pointerHeight: 10, lineJoin: 'round', shadowColor: 'black', shadowBlur: 10, shadowOffset: {x:10,y:20}, shadowOpacity: 0.5 })); tooltip.add(new Kinetic.Text({ text: text, fontFamily: 'Calibri', fontSize: 18, padding: 5, fill: 'white' })); l.add(tooltip); actionStack.push(tooltip); l.draw(); actionStack += 1; var data = { type: "tooltip", mode: "create", text: text, x: x, y: y, id: actionCounter}; $.post( "server.php", data); console.log("POST request sent with data: "); console.log(data); } function loadSampleImage() { imageObj = new Image(); imageObj.onload = function() { img = new Kinetic.Image({ x: 0, y: 0, image: imageObj, width: 1000, height: 500 }); //img.cache(); img.filters([Kinetic.Filters.Brighten]); imageLayer.add(img); imageLayer.draw(); }; imageObj.src = 'sampleimage.jpg'; } function invertImage() { img.cache(); img.filters([Kinetic.Filters.Invert]); imageLayer.draw(); } function grayscaleImage() { img.cache(); img.filters([Kinetic.Filters.Grayscale]); imageLayer.draw(); } function brightenImage() { img.cache(); img.filters([Kinetic.Filters.Grayscale]); imageLayer.draw(); } $('#container').on('click', function(e) { var posX = e.clientX - $(this).offset().left; var posY = e.clientY - $(this).offset().top; if(mode == "POINT") addCircle(posX, posY, layer); if(mode == "TEXT") { var text = prompt("Please enter your text", ""); if(text != null) addTooltip(posX, posY, layer, text); } }); $('#container').on('mousedown', function(e) { if(mode != "RECTANGLE") return; lastMouseDownX = e.clientX - $(this).offset().left; lastMouseDownY = e.clientY - $(this).offset().top; var rect = new Kinetic.Rect({ x: lastMouseDownX, y: lastMouseDownY, width: 1, height: 1, fill: 'green', stroke: 'black', strokeWidth: 4, draggable: true }); rect.on('dragend', function() { var data = { mode: "update", x: rect.x(), y: rect.y(), id: actionCounter}; $.post( "server.php", data); console.log("POST request sent with data: "); console.log(data); }); layer.add(rect); actionStack.push(rect); tmpRect = rect; layer.draw(); }); $('#container').on('mouseup', function(e) { if(mode == "RECTANGLE") { actionCounter += 1; var data = { type: "rectangle", mode: "create", width: tmpRect.width(), height: tmpRect.height(), x: tmpRect.x(), y: tmpRect.y(), id: actionCounter}; $.post( "server.php", data); console.log("POST request sent with data: "); console.log(data); tmpRect = null; } }); $('#container').on('mousemove', function(e) { var posX = e.clientX - $(this).offset().left; var posY = e.clientY - $(this).offset().top; if(mode == "RECTANGLE" && tmpRect != null) { tmpRect.width(Math.abs(posX - lastMouseDownX)); tmpRect.height(Math.abs(posY - lastMouseDownY)); layer.draw(); } }); $('#rectangle').on('click', function(e) { $('#modes').children('button').each(function () { $(this).css('font-weight', 'normal'); }); $(this).css('font-weight', 'bolder'); mode = "RECTANGLE"; }); $('#point').on('click', function(e) { $('#modes').children('button').each(function () { $(this).css('font-weight', 'normal'); }); $(this).css('font-weight', 'bolder'); mode = "POINT"; }); $('#text').on('click', function(e) { $('#modes').children('button').each(function () { $(this).css('font-weight', 'normal'); }); $(this).css('font-weight', 'bolder'); mode = "TEXT"; }); $('#none').on('click', function(e) { $('#modes').children('button').each(function () { $(this).css('font-weight', 'normal'); }); $(this).css('font-weight', 'bolder'); mode = "NONE"; }); $('#loadImage').on('click', function(e) { loadSampleImage(); }); $('#invertFilter').on('click', function(e) { invertImage(); }); $('#grayscaleFilter').on('click', function(e) { grayscaleImage(); }); $('#brightenFilterUP').on('click', function(e) { img.cache(); globalBrightness += 0.1; img.brightness(globalBrightness); imageLayer.batchDraw(); }); $('#brightenFilterDOWN').on('click', function(e) { img.cache(); globalBrightness -= 0.1; img.brightness(globalBrightness); imageLayer.batchDraw(); }); $('#undo').on('click', function(e) { var item = actionStack.pop(); if(item != null) { var data = { mode: "delete", id: actionCounter}; actionCounter -= 1; $.post( "server.php", data); console.log("POST request sent with data: "); console.log(data); item.remove(); layer.draw(); } }); rect.on('mouseover', function() { document.body.style.cursor = 'pointer'; }); rect.on('mouseout', function() { document.body.style.cursor = 'default'; }); stage.add(imageLayer); stage.add(layer);<file_sep>mongoose = require('mongoose'); Schema = mongoose.Schema tokenLifeTime = 7200000 var tokenSchema = new Schema({ token: {type: String}, created: {type: Date, default: Date.now} }) tokenSchema.methods.hasExpired = function() { var now = new Date(); var diff = (now.getTime() - this.created); return diff > tokenLifeTime; }; var Token = mongoose.model('Token', tokenSchema) module.exports = Token;<file_sep>#!/usr/bin/env node var debug = require('debug')('my-application'); var app = require('../app').app; var https_options = require('../app').https_options var https = require('https') var io = require('socket.io') var Action = require('../models/action') var httpsForWebsockets = https.createServer(https_options, app).listen(process.env.PORT || 3000) // = https.createServer(https_options, app) var websocket = io.listen(httpsForWebsockets) console.log(httpsForWebsockets) require("http").createServer(function(req, res){ console.log(req.headers.host) console.log(req.headers) host = req.headers.host.split(":") host[1] = 3000; host = host.join(":") console.log(host) res.writeHead(301, { 'Content-Type': 'text/plain', 'Location':'https://'+host+req.url}); res.end('Redirecting to SSL\n'); }).listen(3001); websocket.sockets.on('connection', function (socket) { console.log('User connected'); socket.on('disconnect', function(){ console.log('User disconnected'); }); socket.on('joinToRoom', function(roomname) { console.log("User joined to " + roomname) socket.join(roomname); }) socket.on('leaveRoom', function(roomname){ socket.leave(roomname); console.log("leave room") }) socket.on('message', function (message) { console.log(message) var imageID = message.data.imageID console.log('message-from-others:' + message ) socket.broadcast.to(imageID).emit('message-from-others', message); }); socket.on('draw', function (obj) { console.log('draw:' + obj ) console.log("email: " + obj.email) var data = obj.data var roomID = data.imageID.toString(); var action = new Action({ imageID: mongoose.Types.ObjectId(data.imageID.toString()), userID: mongoose.Types.ObjectId(data.userID.toString()), objectID: data.objectID, mode: data.mode, x: data.x || null, y: data.y || null, width: data.width || null, height: data.height || null, color: data.color || null, content: data.content || null, type: data.type || null }) console.log(action) //console.log("object:" + JSON.stringify(obj.data)) action.save(function(err){ if (err) throw err; obj.data = action socket.broadcast.to(roomID).emit('draw', obj); }); }); //var data={"message":"Hello World!", options:options}; //socket.emit("testreply",data,id); }); }); /*app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { debug('Express server listening on port ' + server.address().port); }); */
33695fa3b0a114eb7159612bbc0bee353a4db462
[ "JavaScript" ]
12
JavaScript
pawelrychly/image-tele-consult
851a519d1352fbec84365d80bf52041c526f2b82
02b84fa0b094e2c95c8f9c9b066778693527af2c
refs/heads/master
<repo_name>c-johnson/mainst<file_sep>/README.md mainst ====== Main Street Carpentry home website <file_sep>/app/assets/javascripts/services.js (function () { var MainController = { init: function () { this.registerElements(); this.registerEventHandlers(); }, registerElements: function () { this.lbContent = $('#lightboxContent'); this.lbControls = $('#lightboxControls'); this.lbImage = $('#lightboxContent img'); this.lbCaption = $('#lightboxContent .lightbox-caption'); }, registerEventHandlers: function () { $(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) { event.preventDefault(); $(this).ekkoLightbox(); }); } }; $(function () { MainController.init(); }); })();<file_sep>/app/controllers/main_controller.rb class MainController < ApplicationController def send_message send_simple_message(params[:name], params[:email], params[:message]) end def send_simple_message(name, email, message) RestClient.post "https://api:key-3ax6xnjp29jd6fds4gc373sgvjxteol0"\ "@api.mailgun.net/v2/samples.mailgun.org/messages", :from => "#{name} <#{email}>", :to => "<EMAIL>", :subject => "Inquiry about website", :text => "#{message}" end end
a32a69f4b115b2e368435c81c734f1aff08f8d42
[ "Markdown", "JavaScript", "Ruby" ]
3
Markdown
c-johnson/mainst
e57879d40ba1693c509f58eada3f52c8cae98a5f
467b245e21ae208e1271ecb151c3fa2c2c1ee1fd
refs/heads/master
<file_sep>import unittest import numpy as np from src.agents.AgentMLPTF import AgentMLPTF import tensorflow as tf # agent.visualise_model() # print(agent.summary()) class MyTestCase(unittest.TestCase): def test_single_input(self): # reset seeds np.random.seed(1) tf.random.set_seed(1) # instantiate agent agent = AgentMLPTF() action = agent(np.array([2]))["Action"] self.assertEqual(action, np.array([0.57267284],dtype=np.float32)) def test_batch_input(self): # reset seeds np.random.seed(1) tf.random.set_seed(1) # instantiate agent agent = AgentMLPTF() action = agent(np.array([[2]]))["Action"] self.assertEqual(action, np.array([0.57267284],dtype=np.float32)) if __name__ == '__main__': unittest.main() <file_sep>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D class LinearEnv: """ A univariate environment on a horizontal line that has regions of highly negative reward. """ def __init__(self, s_goal=6, randomize=False, s_max=10, visualize=False): """ s_goal - goal state randomize - bool flag for whether state should be fixed or randomized at each reset() call s_max - hard boundary to the right of the environment """ # initialise env self.random_s0 = randomize self.visualize = visualize self.goal_tol = 0.5 self.max_steps = 20 self.s_goal = np.expand_dims(s_goal, axis=0) self.s_max = np.expand_dims(s_max, axis=0) self.s = self.reset() # rendering self.ax = None def reset(self): self.steps = 0 if self.random_s0: self.s = np.random.choice(np.array([0.5, 1, self.s_max-0.5, self.s_max-1])) + np.random.normal(loc=0, scale=0.2, size=(1,)) return self.s else: self.s = np.expand_dims(1.0, axis=0) return self.s def step(self, a): assert np.ndim(a) == 1, "incorrect action dim " + str(np.ndim(a)) # clip the action a = np.clip(a, -1, 1) r = 0.0 wall_penalty = -100 done = False self.s = np.array(self.s) + np.array(a) # enforce boundaries if self.s < 0: self.s = np.array([0.0]) r = wall_penalty elif self.s > self.s_max: self.s = self.s_max r = wall_penalty # check if goal reached or max steps reached if np.abs(self.s - self.s_goal) < self.goal_tol or self.steps == self.max_steps - 1: done = True r = 0.0 else: # compute reward r += self.reward(self.s) self.steps += 1 if self.visualize: self.render(a) return self.s, r, done, {} def reward(self, s): # insert code for checking if the agent is # within circle boundaries (highly penalising states) return -(s - self.s_goal)**2 def render(self, a, azimuth=60, elevation=20): if self.ax is None: fig = plt.figure() self.ax = fig.add_subplot(111, projection='3d') self.ax.scatter(self.s, self.steps*5, a, c='r', marker='o') self.ax.azim = azimuth self.ax.elev = elevation self.ax.set_xlabel('state') self.ax.set_ylabel('timestep') self.ax.set_zlabel('action') # draw starting and goal lines <file_sep>import unittest from src.envs import LinearEnv import numpy as np class EnvTestCases(unittest.TestCase): def test_init_state_not_random(self): env = LinearEnv.LinearEnv(randomize=False) self.assertEqual(env.s,np.array([1])) if __name__ == '__main__': unittest.main() <file_sep>from src.envs import LinearEnv<file_sep>from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='A codebase for the continuous control action priors framework', author='<NAME>', license='MIT', ) <file_sep>from tensorflow.keras.layers import Dense, Flatten, Conv2D from tensorflow.keras import Model import tensorflow as tf import numpy as np import tensorflow_probability as tfp tfd = tfp.distributions # make all layer data types consistent tf.keras.backend.set_floatx('float64') # Set random seeds #tf.random.set_seed(0) #np.random.seed(0) class AgentMLPTF(Model): """ Uses subclassing and functional API in keras to define a Gaussian MLP policy. """ def __init__(self): super(AgentMLPTF, self).__init__() # declare action distribution self.action_dist = None normalizer = tf.keras.layers.LayerNormalization(axis=1) # model inputs inputs = tf.keras.Input(shape=(1,), dtype='float64') # normalize inputs # norm_inputs = normalizer(inputs) # norm_inputs = inputs/10.0 # model layers (output = activation(dot(input, kernel) + bias) ) d1 = Dense(15, activation='relu', name="d1")(inputs) d2_mu = Dense(1, activation='tanh', name="d2_mu")(d1) d2_sigma = Dense(1, activation='sigmoid', name="d2_sigma")(d1) # consider using sigmoid/exponential here # model outputs outputs = {"Loc": d2_mu, "Scale": d2_sigma} self.model = tf.keras.Model(inputs, outputs) # model returns TFP Gaussian dist params as output def call(self, x): batch = True if np.ndim(x) == 1: batch = False x = np.expand_dims(x, axis=1) # 1. Define Policy GaussianParams = self.model(x) # at this point, x is the output of d1 min_stddev = 0 #1e-3 # define minimum for sigma value 1e-4 # 2. Define Gaussian tf probability distribution layer self.action_dist = tfd.Normal(GaussianParams["Loc"], GaussianParams["Scale"]+min_stddev, validate_args=True) # 3. Sample policy to get action action = self.action_dist.sample() # 4. Get log probability from tfp layer action_log_prob = self.action_dist.log_prob(action) # add minimum log prob for actions if not batch: action = action.numpy().flatten() action_log_prob = action_log_prob.numpy().flatten() return dict({"Action": action, "LogProbability": action_log_prob}, **GaussianParams) def visualise_model(self): tf.keras.utils.plot_model( self.model, to_file='model.png', show_shapes=True, show_layer_names=True, rankdir='TB', expand_nested=True, dpi=96 ) <file_sep># local package -e . # external requirements click~=7.1.2 Sphinx coverage awscli flake8 python-dotenv>=0.5.1 numpy~=1.19.1 matplotlib~=3.3.2 tensorflow~=2.0.0 setuptools~=50.3.0
d8bfceaa95f38f2e3908189e63f99a9a76480804
[ "Python", "Text" ]
7
Python
Sicelukwanda/action_priors
c066aa2e050fe899e1b954d40a9da208d782328a
79d52a32686b23c7bdc84badd0e99164f0b52942
refs/heads/master
<repo_name>DaybitGure/backEnd<file_sep>/server.js const Express = require("express"); const BodyParser = require("body-parser"); const MongoClient = require("mongodb").MongoClient; const ObjectID = require('mongodb').ObjectID; var app = Express(); const url = "mongodb+srv://keke:<EMAIL>/test?retryWrites=true"; //const client = new MongoClient(uri, { useNewUrlParser: true }); app.use(BodyParser.json()); app.use(BodyParser.urlencoded({ extended: true })); app.use(function (req, res, next) { res.header('Access-Control-Allow-Origin', ' *'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', '"Origin, X-Requested-With, Content-Type, Accept'); next(); }); var database, collection; var port = (process.env.PORT || 3000); var db MongoClient.connect('mongodb+srv://keke:n.51263978@cluster0-gpv98.gcp.mongodb.net/test?retryWrites=true', (err, client) => { if (err) return console.log(err) db = client.db('data') db.createCollection("user", function (err, res) { if (err) throw err; db.collection('user').createIndex({ name: 1 }, { sparse: true, unique: true }); console.log("User collection created!"); }); db.createCollection("Album", function (err, res) { if (err) throw err; console.log("Album collection created!"); }); db.createCollection("Ly", function (err, res) { if (err) throw err; console.log("Ly collection created!"); }); app.listen(port) }) //user function app.post('/reg', (req, res) => { db.collection('user').findOne({ "email": req.body.email },function(err, result){ if (err) return console.log(err) if (result!=null) { result.status = false; res.send(result) } else { db.collection('user').save(req.body, (err, rs) => { if (err) return console.log(err) console.log('saved to database') db.collection('user').findOne({ "email": req.body.email },function(err, drs) { if (err) return console.log("err="+err) console.log("drs="+JSON.stringify(drs)) if (drs!=null) { drs.status = true; res.send(drs) } else { drs.status = false; res.send(drs) } }) }); } }) }) app.get('/AuthUser/:email/:pw', (req, res) => { console.log(req.params.email) db.collection('user').findOne({ "email": req.params.email, "pw": req.params.pw },function(err, result){ if (err) return console.log(err) if (result) { result.status = true; res.send(result) } else { var result={} result.status = false; res.send(result) } }) }) //post function app.get('/getAlbum/:id', (req, res) => {//ok console.log(req.params.id) const obj = { _id: ObjectID(req.params.id) }; db.collection('Album').findOne(obj, function (err, result) { if (err) return res.send(false); console.log(result) res.send(result) }) }) app.get('/getLy/:id', (req, res) => {//ok console.log(req.params.id) const obj = { _id: ObjectID(req.params.id) }; db.collection('Ly').findOne(obj, function (err, result) { if (err) return res.send(false); console.log(result) res.send(result) }) }) app.get('/SearchAllAlbum/:id', (req, res) => {//ok var str=req.params.id db.collection('Album').find({ $or: [{"name":{$regex:str}},{"singer":{$regex:str}}]}).sort({date:-1}).toArray((err, result) => { if (err) return res.send(false); console.log(result) res.send(result) }) }) app.get('/SearchAllLy/:id', (req, res) => {//ok var str=req.params.id db.collection('Ly').find({ $or: [{"song":{$regex:str}},{"singer":{$regex:str}}]}).sort({date:-1}).toArray((err, result) => { if (err) return res.send(false); console.log(result) res.send(result) }) }) app.get('/getAllAlbum/:id', (req, res) => {//ok db.collection('Album').find({ "userid": req.params.id }).sort({date:-1}).toArray((err, result) => { if (err) return res.send(false); console.log(result) res.send(result) }) }) app.get('/getAllLy/:id', (req, res) => {//ok db.collection('Ly').find({ "userid": req.params.id }).toArray((err, result) => { if (err) return res.send(false); console.log(result) res.send(result) }) }) app.post('/addAlbum', (req, res) => {//ok db.collection('Album').save(req.body, (err, result) => { if (err) return res.send(false); console.log('Album saved!') res.send(true); }); }) app.post('/addLy', (req, res) => {//ok db.collection('Ly').save(req.body, (err, result) => { if (err) return res.send(false); console.log('Lyrics saved!') res.send(true); }); }) app.put('/editAlbum/:id', (req, res) => {//ok console.log(req.params.id, req.body); const newvalues = { $set: req.body }; const obj = { _id: ObjectID(req.params.id) }; db.collection("Album").updateOne(obj, newvalues, function (err, obj) { if (err) throw res.send(false); console.log("Album updated"); res.send(true); }); }) app.put('/editLy/:id', (req, res) => {//ok console.log(req.params.id, req.body); const newvalues = { $set: req.body }; const obj = { _id: ObjectID(req.params.id) }; db.collection("Ly").updateOne(obj, newvalues, function (err, obj) { if (err) throw res.send(false); console.log("Lyrics updated"); res.send(true); }); }) app.delete('/delRecord/:id', (req, res) => {//ok // use _id need use ObjectID(value) const obj = { _id: ObjectID(req.params.id) }; db.collection("Album").remove(obj, function (err, obj) { if (err) res.send(false); console.log("Album deleted"); res.send(true); }); }) app.delete('/delLy/:id', (req, res) => {//ok // use _id need use ObjectID(value) const obj = { _id: ObjectID(req.params.id) }; db.collection("Ly").remove(obj, function (err, obj) { if (err) res.send(false); console.log("Lyrics deleted"); res.send(true); }); })
bc220bbf36e4873ea10410b3e1b4fb1cb8fe268b
[ "JavaScript" ]
1
JavaScript
DaybitGure/backEnd
274ad870feb579a0aa1a7718a1aa7e6ddf09043a
68bcfd15536d17bd0a77bb4d1ddc578e5704c86c
refs/heads/master
<file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ /* * Portions of this software include software developed by the OpenSSL Project for * use in the OpenSSL Toolkit (http://www.openssl.org/), and those portions * are governed by the OpenSSL Toolkit License. */ #include <string.h> #include <openssl/x509.h> #include <openssl/objects.h> #include <openssl/ts.h> #include <openssl/err.h> #include <openssl/pkcs7.h> /* This function is copied from openssl x509_vfy.c. It checks certificates chain. We customized this function and eliminated check of certificates date */ int verify_certificates_chain(X509_STORE_CTX *ctx) { int ok=0,n; X509 *xs,*xi; EVP_PKEY *pkey=NULL; int (*cb)(int xok,X509_STORE_CTX *xctx); cb=ctx->verify_cb; n=sk_X509_num(ctx->chain); ctx->error_depth=n-1; n--; xi=sk_X509_value(ctx->chain,n); if (ctx->check_issued(ctx, xi, xi)) xs=xi; else { if (n <= 0) { ctx->error=X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE; ctx->current_cert=xi; ok=cb(0,ctx); goto end; } else { n--; ctx->error_depth=n; xs=sk_X509_value(ctx->chain,n); } } /* ctx->error=0; not needed */ while (n >= 0) { ctx->error_depth=n; /* Skip signature check for self signed certificates unless * explicitly asked for. It doesn't add any security and * just wastes time. */ if (!xs->valid && (xs != xi || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) { if ((pkey=X509_get_pubkey(xi)) == NULL) { ctx->error=X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY; ctx->current_cert=xi; ok=(*cb)(0,ctx); if (!ok) goto end; } else if (X509_verify(xs,pkey) <= 0) { ctx->error=X509_V_ERR_CERT_SIGNATURE_FAILURE; ctx->current_cert=xs; ok=(*cb)(0,ctx); if (!ok) { EVP_PKEY_free(pkey); goto end; } } EVP_PKEY_free(pkey); pkey=NULL; } xs->valid = 1; /* Do not check the time ok = check_cert_time(ctx, xs); if (!ok) goto end; */ /* The last error (if any) is still in the error value */ ctx->current_issuer=xi; ctx->current_cert=xs; ok=(*cb)(1,ctx); if (!ok) goto end; n--; if (n >= 0) { xi=xs; xs=sk_X509_value(ctx->chain,n); } } ok=1; end: return ok; } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include "global.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "callbacks.h" #include "winpe.h" #include "miscellaneous.h" #include "endianness.h" UNSIGNED64 winpe2_object_end(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PE_ALL_HEADERS* peh) { long filepos; int i; TAG_IMAGE_SECTION_HEADER fs; UNSIGNED64 res = 0; /* If there are no sections, then the size of pe object is a size of headers */ if (winpe_is_pe64(peh)) { res = peh->oh.pe64.SizeOfHeaders; } else { res = peh->oh.pe32.SizeOfHeaders; } if (peh->fh.NumberOfSections != 0) { filepos = peh->dh.e_lfanew + sizeof(UNSIGNED32) + sizeof(TAG_IMAGE_FILE_HEADER) + peh->fh.SizeOfOptionalHeader; /* shift file pointer to the sections array */ if (file_seek(pCtx, fp, filepos, SEEK_SET)) { /* reading all sections and find rva address */ for (i = 0; i < peh->fh.NumberOfSections; i++) { /* read section from the file */ if (winpe_read_section_header(pCtx, fp, &fs)) { if (fs.PointerToRawData != 0) { res = fs.PointerToRawData + winpe_raw_section_size(peh, &fs); } filepos += sizeof(TAG_IMAGE_SECTION_HEADER); if (!file_seek(pCtx, fp, filepos, SEEK_SET)) { break; } } else { break; } } } } return res; } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include <iostream> #include <fstream> #include <istream> #include <string> #include <sys/types.h> #include <sys/stat.h> #if defined(_MSC_VER) && (_MSC_VER > 1300) #include <direct.h> #include <windows.h> #include <strsafe.h> #else #include <unistd.h> #include <dirent.h> #endif #include <time.h> #include "fileio.h" #include "winpe.h" #include "taggantlib.h" #include "taggant_types.h" #include "miscellaneous.h" using namespace std; void print_tag_info(__in PTAGGANTOBJ tag_obj, ENUMTAGINFO eKey); void check_file(PTAGGANTCONTEXT pCtx, char* cacert, char* tscert, string fileName); int dir_exists(const char* dirName); void seek_dir(PTAGGANTCONTEXT pCtx, char* cacert, char* tscert, string path); #define MAX_PATH_LENGTH 4096 int main(int argc, char *argv[]) { cout << "Taggant Test Application\n\n"; const char* usage = "Usage: test.exe ca_root_certificate_file ca_ts_certificate_file [optional] directory_to_scan\n\n"; // Check if number of arguments is not less than 2 if (argc < 3) { cout << "Invalid Arguments, no CA and/or TS root certificates!\n\n" << usage; return 1; } // Check if second arguments points to the CA root certificate file ifstream fca(argv[1], ios::binary); if (!fca.is_open()) { cout << "CA certificate file does not exist\n\n" << usage; return 1; } fca.close(); // Check if third arguments points to the TS root certificate file ifstream fts(argv[2], ios::binary); if (!fts.is_open()) { cout << "TS certificate file does not exist\n\n" << usage; return 1; } fts.close(); // Check if the 4th argument exists and if it is a directory // Otherwise, scan current directory char* cwd = NULL; if (argc >= 4) { if (dir_exists(argv[3])) { cwd = argv[3]; } } char* tmp = NULL; if (cwd == NULL) { tmp = new char [MAX_PATH_LENGTH]; memset(tmp, 0, MAX_PATH_LENGTH); if (getcwd(tmp, MAX_PATH_LENGTH)) { cwd = tmp; } } int err = 0; if (cwd != NULL) { // Initialize taggant library TAGGANTFUNCTIONS funcs; memset(&funcs, 0, sizeof(TAGGANTFUNCTIONS)); UNSIGNED64 uVersion = TAGGANT_LIBRARY_VERSION2; // Set structure size funcs.size = sizeof(TAGGANTFUNCTIONS); TaggantInitializeLibrary(&funcs, &uVersion); cout << "Taggant Library version " << uVersion << "\n"; // Make sure the taggant library supports version 2 if (uVersion < TAGGANT_LIBRARY_VERSION2) { cout << "Current taggant library does not support version 2\n\n"; err = 1; } if (!err) { // Create taggant context PTAGGANTCONTEXT pCtx; UNSIGNED32 ctxres = TaggantContextNewEx(&pCtx); if (ctxres == TNOERR) { // Vendor should check version flow here! pCtx->FileReadCallBack = (size_t (__DECLARATION *)(void*, void*, size_t))fileio_fread; pCtx->FileSeekCallBack = (int (__DECLARATION *)(void*, UNSIGNED64, int))fileio_fseek; pCtx->FileTellCallBack = (UNSIGNED64 (__DECLARATION *)(void*))fileio_ftell; // Load CA certificate to the memory ifstream fca(argv[1], ios::binary); fca.seekg(0, ios::end); long fsize = fca.tellg(); char* cacert = new char[fsize + 1]; cacert[fsize] = '\0'; fca.seekg(0, ios::beg); fca.read(cacert, fsize); fca.clear(); // Load TS certificate to the memory ifstream fts(argv[2], ios::binary); fts.seekg(0, ios::end); long ftssize = fts.tellg(); char* tscert = new char[ftssize + 1]; tscert[ftssize] = '\0'; fts.seekg(0, ios::beg); fts.read(tscert, ftssize); fts.clear(); if (TaggantCheckCertificate(cacert) == TNOERR) { if (TaggantCheckCertificate(tscert) == TNOERR) { // scan the directory and search files with the taggant seek_dir(pCtx, cacert, tscert, string(cwd)); } else { cout << "TS certificate is invalid\n\n" << usage; err = 1; } } else { cout << "CA certificate is invalid\n\n" << usage; err = 1; } delete[] cacert; delete[] tscert; TaggantContextFree(pCtx); } else { cout << "TaggantContextNewEx failed with result: " << ctxres << "\n\n"; err = 1; } TaggantFinalizeLibrary(); } } if (tmp != NULL) { delete[] tmp; } return err; } void print_tag_info(PTAGGANTOBJ tag_obj, ENUMTAGINFO eKey) { unsigned int tag_info_size = 0; // Get the length of the eKey taggant information if (TaggantGetInfo(tag_obj, eKey, &tag_info_size, NULL) == TINSUFFICIENTBUFFER) { // Allocate enough buffer char* taginfo = new char[tag_info_size]; // Get the eKey taggant information if ( TaggantGetInfo(tag_obj, eKey, &tag_info_size, taginfo) == TNOERR) { // Print taggant information if (tag_info_size > 0) { for (int i = 0; i <= (int)tag_info_size / 16; i++) { int k = tag_info_size - i * 16; if (k > 0) { k = (k < 16) ? k : 16; cout << " "; for (int j = 0; j < k; j++) { printf("%02x ", (unsigned char)taginfo[i * 16 + j]); } cout << "\n"; } } } else { cout << " no data" << endl; } } // Free buffer delete[] taginfo; } // return; } #if defined(_MSC_VER) && (_MSC_VER > 1300) int dir_exists(const char* dirName) { DWORD attr = GetFileAttributes(dirName); if (attr == INVALID_FILE_ATTRIBUTES) { return 0; } if (attr & FILE_ATTRIBUTE_DIRECTORY) { // this is a directory! return 1; } return 0; } void seek_dir(PTAGGANTCONTEXT pCtx, char* cacert, char* tscert, string path) { WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; size_t length_of_arg; TCHAR szDir[MAX_PATH]; StringCchLength(path.c_str(), MAX_PATH, &length_of_arg); // Prepare string for use with FindFile functions. First, copy the // string to a buffer, then append '\*' to the directory name. StringCchCopy(szDir, MAX_PATH, path.c_str()); StringCchCat(szDir, MAX_PATH, TEXT("\\*")); hFind = FindFirstFile(szDir, &ffd); if (hFind != INVALID_HANDLE_VALUE) { do { string fileName = path + "/" + ffd.cFileName; if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { check_file(pCtx, cacert, tscert, fileName); } else { if(strcmp(ffd.cFileName,".") != 0 && strcmp(ffd.cFileName,"..") != 0) { // Scan new directory recursively seek_dir(pCtx, cacert, tscert, fileName); } } } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); } } #else int dir_exists(const char* dirName) { DIR* dir = opendir(dirName); if (dir != 0) { closedir(dir); return 1; } return 0; } void seek_dir(PTAGGANTCONTEXT pCtx, char* cacert, char* tscert, string path) { // Try to open the directory DIR* dir = opendir(path.c_str()); if (dir != 0) { struct dirent *d; while( (d = readdir(dir)) != 0) { if(strcmp(d->d_name,".") != 0 && strcmp(d->d_name,"..") != 0) { string fileName = path + "/" + d->d_name; check_file(pCtx, cacert, tscert, fileName); // Scan new directory recursively seekdir(pCtx, cacert, tscert, p); } } } } #endif void process_taggant(PTAGGANTCONTEXT pCtx, ifstream *pfin, PPE_ALL_HEADERS ppeh, PTAGGANT pTaggant, char* cacert, char* tscert) { cout << " - taggant is found\n"; // Initialize taggant object before it will be validated PTAGGANTOBJ tag_obj; UNSIGNED32 objres = TaggantObjectNewEx(pTaggant, 0, TAGGANT_PEFILE, &tag_obj); if (objres == TNOERR) { cout << " - taggant object created\n"; // Validate the taggant UNSIGNED32 res = TNOERR; if ((res = TaggantValidateSignature(tag_obj, pTaggant, (PVOID)cacert)) == TNOERR) { cout << " - taggant is correct\n"; // Check if the TS exists unsigned long long timest = 0; if ((res = TaggantGetTimestamp(tag_obj, &timest, (PVOID)tscert)) == TNOERR) { cout << " - taggant timestamp " << asctime(gmtime((time_t*)&timest)); } else { cout << " - taggant does not contain timestamp, or it is invalid, error code " << res << "\n"; } // print packer information PACKERINFO pinfo; UNSIGNED32 psize = sizeof(PACKERINFO); if ((res = TaggantGetInfo(tag_obj, EPACKERINFO, &psize, (char*)&pinfo)) == TNOERR) { cout << " - file protected by packer with " << pinfo.PackerId << " id, version " << pinfo.VersionMajor << "." << pinfo.VersionMinor << "." << pinfo.VersionBuild << "\n"; } else { cout << " - cannot get packer info, error code " << res << "\n"; } // print contributors info UNSIGNED32 csize; if ((res = TaggantGetInfo(tag_obj, ECONTRIBUTORLIST, &csize, NULL)) == TINSUFFICIENTBUFFER) { cout << " - found contributors information of " << csize << " bytes length\n"; char *cinfo = new char[csize]; if (TaggantGetInfo(tag_obj, ECONTRIBUTORLIST, &csize, cinfo) == TNOERR) { cout << " - contributors information: " << cinfo << "\n"; } delete[] cinfo; } else { cout << " - cannot get contributor info or it is empty, error code " << res << "\n"; } // get the ignore hash map value UNSIGNED8 ignorehmh = 0; UNSIGNED32 ihmhsize = sizeof(UNSIGNED8); if ((res = TaggantGetInfo(tag_obj, EIGNOREHMH, &ihmhsize, (char*)&ignorehmh)) == TNOERR) { if (ignorehmh) { cout << " - ignore hash map value is set for the taggant\n"; } } else { cout << " - cannot get ignore hash map value, error code " << res << "\n"; } // get the previous tag value UNSIGNED8 tagprev = 0; UNSIGNED32 tprevsize = sizeof(UNSIGNED8); if ((res = TaggantGetInfo(tag_obj, ETAGPREV, &tprevsize, (char*)&tagprev)) == TNOERR) { if (tagprev) { cout << " - previous tag value is set for the taggant\n"; } } else { cout << " - cannot get previous tag value, error code " << res << "\n"; } res = TNOERR; if (!ignorehmh) { // Get file hash type // Do a quick file check using hash map (in case it exists) PHASHBLOB_HASHMAP_DOUBLE dbl = NULL; int dbl_count = TaggantGetHashMapDoubles(tag_obj, &dbl); if (dbl_count) { cout << " - hashmap covers following regions:\n"; for (int i = 0; i < dbl_count; i++) { cout << i << ". from " << dbl[i].AbsoluteOffset << " to " << (dbl[i].AbsoluteOffset + dbl[i].Length) << "\n"; } // Compute hashmap of the current file res = TaggantValidateHashMap(pCtx, tag_obj, (void*)pfin); // Check if file hash is valid if (res == TNOERR) { cout << " - hashmap is valid\n"; } else { cout << " - hashmap is INVALID\n"; } } } // If hashmap does not exist, or if it exists and valid we do a full file hash check if (res == TNOERR) { // Check full file hash only if there is no previous tag if (!tagprev) { UNSIGNED64 file_end = 0; UNSIGNED32 size = sizeof(UNSIGNED64); // Get file end value from the taggant, used for taggant v1 only TaggantGetInfo(tag_obj, EFILEEND, &size, (char*)&file_end); if (!file_end) { file_end = fileio_fsize(pfin); } int object_end = winpe_object_size(pfin, ppeh); // Compute default hashes of the current file res = TaggantValidateDefaultHashes(pCtx, tag_obj, (void*)pfin, object_end, file_end); // Check if file hash is valid if (res == TNOERR) { cout << " - full file hash is valid\n"; } else { cout << " - full file hash is INVALID\n"; } } else { cout << " - skip check of full file hash as there is another taggant in the file\n"; } } // Check if file hash is valid if (res == TNOERR) { // Extract all information from the taggant // SPV certificate cout << " - SPV Certificate\n"; print_tag_info(tag_obj, ESPVCERT); // End User certificate cout << " - User Certificate\n"; print_tag_info(tag_obj, EUSERCERT); } } else { cout << " - taggant is invalid, error code: " << res << "\n"; } TaggantObjectFree(tag_obj); } else { cout << " - could not create taggant object, error code: " << objres << "\n"; } } void check_file(PTAGGANTCONTEXT pCtx, char* cacert, char* tscert, string fileName) { // Try to open the file ifstream fin(fileName.c_str(), ios::binary); if (fin.is_open()) { cout << "" + fileName + "\n"; PE_ALL_HEADERS peh; void *taggant = NULL; UNSIGNED32 res = TNOTAGGANTS; TAGGANTCONTAINER filetype = TAGGANT_PEFILE; // Make sure the file is correct PE file if (winpe_is_correct_pe_file(&fin, &peh)) { cout << " - check against PE file\n"; filetype = TAGGANT_PEFILE; res = TaggantGetTaggant(pCtx, (void*)&fin, filetype, &taggant); } else { cout << " - check against JS file\n"; filetype = TAGGANT_JSFILE; res = TaggantGetTaggant(pCtx, (void*)&fin, filetype, &taggant); if (res != TNOERR) { TaggantFreeTaggant(taggant); taggant = NULL; cout << " - check against TXT file\n"; filetype = TAGGANT_TXTFILE; res = TaggantGetTaggant(pCtx, (void*)&fin, filetype, &taggant); if (res != TNOERR) { TaggantFreeTaggant(taggant); taggant = NULL; cout << " - check against BIN file\n"; filetype = TAGGANT_BINFILE; res = TaggantGetTaggant(pCtx, (void*)&fin, filetype, &taggant); } } } if (res == TNOERR) { process_taggant(pCtx, &fin, &peh, taggant, cacert, tscert); // Enumerate taggants while ((res = TaggantGetTaggant(pCtx, (void*)&fin, filetype, &taggant)) == TNOERR) { process_taggant(pCtx, &fin, &peh, taggant, cacert, tscert); } } else if (res == TNOTAGGANTS) { cout << " - taggant is not found\n"; } else { cout << " - TaggantGetTaggant failed, error code: " << res << "\n"; } TaggantFreeTaggant(taggant); fin.close(); } } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "callbacks.h" #include "winpe.h" #include "miscellaneous.h" #include "endianness.h" int winpe_read_optional_header64(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, TAG_IMAGE_OPTIONAL_HEADER64 *oheader) { UNSIGNED32 dirsize, ohsize; int i; /* PE32+ file, read optional header */ memset(oheader, 0, sizeof(TAG_IMAGE_OPTIONAL_HEADER64)); /* Read optional header without directories */ ohsize = sizeof(TAG_IMAGE_OPTIONAL_HEADER64) - IMAGE_NUMBEROF_DIRECTORY_ENTRIES * sizeof(TAG_IMAGE_DATA_DIRECTORY); if (pCtx->FileReadCallBack(fp, oheader, ohsize) == ohsize) { if (IS_BIG_ENDIAN) { oheader->Magic = UNSIGNED16_to_big_endian((char*)&oheader->Magic); oheader->AddressOfEntryPoint = UNSIGNED32_to_big_endian((char*)&oheader->AddressOfEntryPoint); oheader->SectionAlignment = UNSIGNED32_to_big_endian((char*)&oheader->SectionAlignment); oheader->FileAlignment = UNSIGNED32_to_big_endian((char*)&oheader->FileAlignment); oheader->NumberOfRvaAndSizes = UNSIGNED32_to_big_endian((char*)&oheader->NumberOfRvaAndSizes); } if (oheader->Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) { /* Read directories */ if (oheader->NumberOfRvaAndSizes > 0) { dirsize = get_min(oheader->NumberOfRvaAndSizes, IMAGE_NUMBEROF_DIRECTORY_ENTRIES) * sizeof(TAG_IMAGE_DATA_DIRECTORY); if (pCtx->FileReadCallBack(fp, &oheader->DataDirectory, dirsize) == dirsize) { if (IS_BIG_ENDIAN) { for (i = 0; i < get_min(oheader->NumberOfRvaAndSizes, IMAGE_NUMBEROF_DIRECTORY_ENTRIES); i++) { oheader->DataDirectory[i].VirtualAddress = UNSIGNED32_to_big_endian((char*)&oheader->DataDirectory[i].VirtualAddress); oheader->DataDirectory[i].Size = UNSIGNED32_to_big_endian((char*)&oheader->DataDirectory[i].Size); } } return 1; } } else { return 1; } } } return 0; } int winpe_read_optional_header32(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, TAG_IMAGE_OPTIONAL_HEADER32 *oheader) { UNSIGNED32 dirsize, ohsize; int i; /* PE32 file, read optional header */ memset(oheader, 0, sizeof(TAG_IMAGE_OPTIONAL_HEADER32)); /* Read optional header without directories */ ohsize = sizeof(TAG_IMAGE_OPTIONAL_HEADER32) - IMAGE_NUMBEROF_DIRECTORY_ENTRIES * sizeof(TAG_IMAGE_DATA_DIRECTORY); if (pCtx->FileReadCallBack(fp, oheader, ohsize) == ohsize) { if (IS_BIG_ENDIAN) { oheader->Magic = UNSIGNED16_to_big_endian((char*)&oheader->Magic); oheader->AddressOfEntryPoint = UNSIGNED32_to_big_endian((char*)&oheader->AddressOfEntryPoint); oheader->SectionAlignment = UNSIGNED32_to_big_endian((char*)&oheader->SectionAlignment); oheader->FileAlignment = UNSIGNED32_to_big_endian((char*)&oheader->FileAlignment); oheader->NumberOfRvaAndSizes = UNSIGNED32_to_big_endian((char*)&oheader->NumberOfRvaAndSizes); } if (oheader->Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) { /* Read directories */ if (oheader->NumberOfRvaAndSizes > 0) { dirsize = get_min(oheader->NumberOfRvaAndSizes, IMAGE_NUMBEROF_DIRECTORY_ENTRIES) * sizeof(TAG_IMAGE_DATA_DIRECTORY); if (pCtx->FileReadCallBack(fp, &oheader->DataDirectory, dirsize) == dirsize) { if (IS_BIG_ENDIAN) { for (i = 0; i < get_min(oheader->NumberOfRvaAndSizes, IMAGE_NUMBEROF_DIRECTORY_ENTRIES); i++) { oheader->DataDirectory[i].VirtualAddress = UNSIGNED32_to_big_endian((char*)&oheader->DataDirectory[i].VirtualAddress); oheader->DataDirectory[i].Size = UNSIGNED32_to_big_endian((char*)&oheader->DataDirectory[i].Size); } } return 1; } } else { return 1; } } } return 0; } int winpe_read_file_header(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, TAG_IMAGE_FILE_HEADER *fheader) { if (pCtx->FileReadCallBack(fp, fheader, sizeof(TAG_IMAGE_FILE_HEADER)) == sizeof(TAG_IMAGE_FILE_HEADER)) { if (IS_BIG_ENDIAN) { fheader->Machine = UNSIGNED16_to_big_endian((char*)&fheader->Machine); fheader->NumberOfSections = UNSIGNED16_to_big_endian((char*)&fheader->NumberOfSections); fheader->SizeOfOptionalHeader = UNSIGNED16_to_big_endian((char*)&fheader->SizeOfOptionalHeader); } return 1; } return 0; } int winpe_read_dos_header(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, TAG_IMAGE_DOS_HEADER *dheader) { if (pCtx->FileReadCallBack(fp, dheader, sizeof(TAG_IMAGE_DOS_HEADER)) == sizeof(TAG_IMAGE_DOS_HEADER)) { if (IS_BIG_ENDIAN) { dheader->e_magic = UNSIGNED16_to_big_endian((char*)&dheader->e_magic); dheader->e_lfanew = (SIGNED32)UNSIGNED32_to_big_endian((char*)&dheader->e_lfanew); } return 1; } return 0; } int winpe_read_section_header(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, TAG_IMAGE_SECTION_HEADER *section) { if (pCtx->FileReadCallBack(fp, section, sizeof(TAG_IMAGE_SECTION_HEADER)) == sizeof(TAG_IMAGE_SECTION_HEADER)) { if (IS_BIG_ENDIAN) { section->Misc.VirtualSize = UNSIGNED32_to_big_endian((char*)&section->Misc.VirtualSize); section->VirtualAddress = UNSIGNED32_to_big_endian((char*)&section->VirtualAddress); section->SizeOfRawData = UNSIGNED32_to_big_endian((char*)&section->SizeOfRawData); section->PointerToRawData = UNSIGNED32_to_big_endian((char*)&section->PointerToRawData); } return 1; } return 0; } UNSIGNED32 winpe_header_size(PE_ALL_HEADERS* peh) { UNSIGNED32 ohdefsize, ohsize; ohdefsize = winpe_is_pe64(peh) ? sizeof(TAG_IMAGE_OPTIONAL_HEADER64) : sizeof(TAG_IMAGE_OPTIONAL_HEADER32); ohsize = get_max(peh->fh.SizeOfOptionalHeader, ohdefsize); return peh->dh.e_lfanew + sizeof(peh->signature) + sizeof(peh->fh) + ohsize + peh->fh.NumberOfSections * sizeof(TAG_IMAGE_SECTION_HEADER); } int winpe_taggant_physical_offset(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PE_ALL_HEADERS* peh, UNSIGNED64 ep_physical_offset, UNSIGNED64 *tag_offset) { UNSIGNED16 jmpcode = 0; UNSIGNED64 offset = 0; /* read 2 bytes from file entry point */ if (file_seek(pCtx, fp, ep_physical_offset, SEEK_SET)) { if (file_read_UNSIGNED16(pCtx, fp, &jmpcode)) { if (jmpcode == TAGGANT_ADDRESS_JMP) { if (file_seek(pCtx, fp, ep_physical_offset + sizeof(UNSIGNED16), SEEK_SET)) { if (file_read_UNSIGNED64(pCtx, fp, &offset)) { /* Check if the taggant offset points to the area after headers */ if (offset >= winpe_header_size(peh)) { *tag_offset = offset; return 1; } } } } } } return 0; } UNSIGNED32 winpe_raw_section_size(PE_ALL_HEADERS* peh, TAG_IMAGE_SECTION_HEADER* sec) { long file_alignment = winpe_is_pe64(peh) ? peh->oh.pe64.FileAlignment : peh->oh.pe32.FileAlignment; /* Note, sec->Misc.VirtualSize is being rounded up to the multiple page size value for i386 and AMD64 we assume it is 0x1000 */ return (sec->Misc.VirtualSize ? get_min(round_up(0x1000, sec->Misc.VirtualSize), round_up(file_alignment, sec->SizeOfRawData)) : round_up(file_alignment, sec->SizeOfRawData)); } UNSIGNED32 winpe_raw_section_offset(PE_ALL_HEADERS* peh, TAG_IMAGE_SECTION_HEADER* sec) { long section_alignment; section_alignment = winpe_is_pe64(peh) ? peh->oh.pe64.SectionAlignment : peh->oh.pe32.SectionAlignment; if (section_alignment >= 0x1000) { return round_down(0x200, sec->PointerToRawData); } return sec->PointerToRawData; } int winpe_va_to_rwa(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PE_ALL_HEADERS* peh, UNSIGNED32 va, UNSIGNED64 *offset) { long filepos; int i; TAG_IMAGE_SECTION_HEADER fs; if (peh->fh.NumberOfSections == 0) { *offset = (UNSIGNED64)va; return 1; } /* check is number of sections greater zero */ if (peh->fh.NumberOfSections > 0) { filepos = peh->dh.e_lfanew + sizeof(UNSIGNED32) + sizeof(TAG_IMAGE_FILE_HEADER) + peh->fh.SizeOfOptionalHeader; /* shift file pointer to the sections array */ if (file_seek(pCtx, fp, filepos, SEEK_SET)) { /* reading all sections and find rwa address */ for (i = 0; i < peh->fh.NumberOfSections; i++) { /* read section from the file */ if (winpe_read_section_header(pCtx, fp, &fs)) { if (va < fs.VirtualAddress) { /* If va is less than virtual address of the first section, then we assume the va is located in file header, and so va = rwa */ if (i == 0) { *offset = (UNSIGNED64)va; return 1; } break; } else if (fs.PointerToRawData != 0) { if (va >= fs.VirtualAddress && va < (fs.VirtualAddress + winpe_raw_section_size(peh, &fs))) { *offset = (UNSIGNED64)va - (UNSIGNED64)fs.VirtualAddress + (UNSIGNED64)winpe_raw_section_offset(peh, &fs); return 1; } } filepos += sizeof(TAG_IMAGE_SECTION_HEADER); if (!file_seek(pCtx, fp, filepos, SEEK_SET)) { break; } } else { break; } } } } return 0; } int winpe_is_pe64(PE_ALL_HEADERS* peh) { return (peh->fh.Machine == IMAGE_FILE_MACHINE_AMD64) ? 1 : 0; } int winpe_entry_point_physical_offset(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PE_ALL_HEADERS* peh, UNSIGNED64 *ep_offset) { if (winpe_is_pe64(peh)) { if (peh->oh.pe64.AddressOfEntryPoint != 0) { return winpe_va_to_rwa(pCtx, fp, peh, peh->oh.pe64.AddressOfEntryPoint, ep_offset); } } else { if (peh->oh.pe32.AddressOfEntryPoint != 0) { return winpe_va_to_rwa(pCtx, fp, peh, peh->oh.pe32.AddressOfEntryPoint, ep_offset); } } return 0; } int winpe_is_correct_pe_file(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PE_ALL_HEADERS* peh) { /* remember the size of the file */ UNSIGNED64 filesize = get_file_size(pCtx, fp); /* make sure filesize is greater than size of DOS header */ if (filesize >= sizeof(TAG_IMAGE_DOS_HEADER)) { /* seek file to the file beginning */ if (file_seek(pCtx, fp, 0L, SEEK_SET)) { /* make sure dos header is read fully */ if (winpe_read_dos_header(pCtx, fp, &peh->dh)) { /* check dos header e_magic */ if (peh->dh.e_magic == IMAGE_DOS_SIGNATURE) { if (filesize >= peh->dh.e_lfanew) { /* seek file to the dh.e_magic from beginning */ if (file_seek(pCtx, fp, peh->dh.e_lfanew, SEEK_SET)) { /* read file signature */ if (file_read_UNSIGNED32(pCtx, fp, &peh->signature)) { if (peh->signature == IMAGE_NT_SIGNATURE) { /* read file header */ if (winpe_read_file_header(pCtx, fp, &peh->fh)) { /* As MSDN says, only these types of files can be run in Windows */ if (peh->fh.Machine == IMAGE_FILE_MACHINE_I386) { return winpe_read_optional_header32(pCtx, fp, &peh->oh.pe32); } else if (peh->fh.Machine == IMAGE_FILE_MACHINE_AMD64) { return winpe_read_optional_header64(pCtx, fp, &peh->oh.pe64); } } } } } } } } } } return 0; } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #ifndef WINPE_HEADER #define WINPE_HEADER #include "types.h" #include "taggant_types.h" #define TAGGANT_ADDRESS_JMP 0x08EB #define TAGGANT_ADDRESS_JMP_SIZE 2 /* Minimum sizes of PE files */ #define MINIMUM_PE32_FILE_SIZE 97 #define MINIMUM_PE64_FILE_SIZE 268 #define IMAGE_DOS_SIGNATURE 0x5A4D #define IMAGE_NT_SIGNATURE 0x00004550 #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 #define IMAGE_FILE_MACHINE_I386 0x014c /* Intel 386 or later processors */ #define IMAGE_FILE_MACHINE_AMD64 0x8664 /* x64 */ #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b #define IMAGE_SIZEOF_SHORT_NAME 8 #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 #pragma pack(push,1) typedef struct _TAG_IMAGE_DOS_HEADER { UNSIGNED16 e_magic; UNSIGNED8 Reserved[58]; /* Uncomment necessary values UNSIGNED16 e_cblp; UNSIGNED16 e_cp; UNSIGNED16 e_crlc; UNSIGNED16 e_cparhdr; UNSIGNED16 e_minalloc; UNSIGNED16 e_maxalloc; UNSIGNED16 e_ss; UNSIGNED16 e_sp; UNSIGNED16 e_csum; UNSIGNED16 e_ip; UNSIGNED16 e_cs; UNSIGNED16 e_lfarlc; UNSIGNED16 e_ovno; UNSIGNED16 e_res[4]; UNSIGNED16 e_oemid; UNSIGNED16 e_oeminfo; UNSIGNED16 e_res2[10]; */ SIGNED32 e_lfanew; } TAG_IMAGE_DOS_HEADER,*PTAG_IMAGE_DOS_HEADER; typedef struct _TAG_IMAGE_FILE_HEADER { UNSIGNED16 Machine; UNSIGNED16 NumberOfSections; UNSIGNED8 Reserved1[12]; /* Uncomment necessary values UNSIGNED32 TimeDateStamp; UNSIGNED32 PointerToSymbolTable; UNSIGNED32 NumberOfSymbols; */ UNSIGNED16 SizeOfOptionalHeader; UNSIGNED8 Reserved2[2]; /* Uncomment necessary values UNSIGNED16 Characteristics; */ } TAG_IMAGE_FILE_HEADER, *PTAG_IMAGE_FILE_HEADER; typedef struct _TAG_IMAGE_DATA_DIRECTORY { UNSIGNED32 VirtualAddress; UNSIGNED32 Size; } TAG_IMAGE_DATA_DIRECTORY,*PTAG_IMAGE_DATA_DIRECTORY; typedef struct _TAG_IMAGE_OPTIONAL_HEADER32 { UNSIGNED16 Magic; UNSIGNED8 Reserved1[14]; /* Uncomment necessary values UNSIGNED8 MajorLinkerVersion; UNSIGNED8 MinorLinkerVersion; UNSIGNED32 SizeOfCode; UNSIGNED32 SizeOfInitializedData; UNSIGNED32 SizeOfUninitializedData; */ UNSIGNED32 AddressOfEntryPoint; UNSIGNED8 Reserved2[12]; /* Uncomment necessary values UNSIGNED32 BaseOfCode; UNSIGNED32 BaseOfData; UNSIGNED32 ImageBase; */ UNSIGNED32 SectionAlignment; UNSIGNED32 FileAlignment; UNSIGNED8 Reserved3[20]; /* Uncomment necessary values UNSIGNED16 MajorOperatingSystemVersion; UNSIGNED16 MinorOperatingSystemVersion; UNSIGNED16 MajorImageVersion; UNSIGNED16 MinorImageVersion; UNSIGNED16 MajorSubsystemVersion; UNSIGNED16 MinorSubsystemVersion; UNSIGNED32 Win32VersionValue; UNSIGNED32 SizeOfImage; */ UNSIGNED32 SizeOfHeaders; UNSIGNED8 Reserved4[28]; /* Uncomment necessary values UNSIGNED32 CheckSum; UNSIGNED16 Subsystem; UNSIGNED16 DllCharacteristics; UNSIGNED32 SizeOfStackReserve; UNSIGNED32 SizeOfStackCommit; UNSIGNED32 SizeOfHeapReserve; UNSIGNED32 SizeOfHeapCommit; UNSIGNED32 LoaderFlags; */ UNSIGNED32 NumberOfRvaAndSizes; TAG_IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } TAG_IMAGE_OPTIONAL_HEADER32,*PTAG_IMAGE_OPTIONAL_HEADER32; typedef struct _TAG_IMAGE_OPTIONAL_HEADER64 { UNSIGNED16 Magic; UNSIGNED8 Reserved1[14]; /* Uncomment necessary values UNSIGNED8 MajorLinkerVersion; UNSIGNED8 MinorLinkerVersion; UNSIGNED32 SizeOfCode; UNSIGNED32 SizeOfInitializedData; UNSIGNED32 SizeOfUninitializedData; */ UNSIGNED32 AddressOfEntryPoint; UNSIGNED8 Reserved2[12]; /* Uncomment necessary values UNSIGNED32 BaseOfCode; UNSIGNED64 ImageBase; */ UNSIGNED32 SectionAlignment; UNSIGNED32 FileAlignment; UNSIGNED8 Reserved3[20]; /* Uncomment necessary values UNSIGNED16 MajorOperatingSystemVersion; UNSIGNED16 MinorOperatingSystemVersion; UNSIGNED16 MajorImageVersion; UNSIGNED16 MinorImageVersion; UNSIGNED16 MajorSubsystemVersion; UNSIGNED16 MinorSubsystemVersion; UNSIGNED32 Win32VersionValue; UNSIGNED32 SizeOfImage; */ UNSIGNED32 SizeOfHeaders; UNSIGNED8 Reserved4[44]; /* Uncomment necessary values UNSIGNED32 CheckSum; UNSIGNED16 Subsystem; UNSIGNED16 DllCharacteristics; UNSIGNED64 SizeOfStackReserve; UNSIGNED64 SizeOfStackCommit; UNSIGNED64 SizeOfHeapReserve; UNSIGNED64 SizeOfHeapCommit; UNSIGNED32 LoaderFlags; */ UNSIGNED32 NumberOfRvaAndSizes; TAG_IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } TAG_IMAGE_OPTIONAL_HEADER64,*PTAG_IMAGE_OPTIONAL_HEADER64; typedef struct _TAG_IMAGE_SECTION_HEADER { UNSIGNED8 Name[IMAGE_SIZEOF_SHORT_NAME]; union { UNSIGNED32 PhysicalAddress; UNSIGNED32 VirtualSize; } Misc; UNSIGNED32 VirtualAddress; UNSIGNED32 SizeOfRawData; UNSIGNED32 PointerToRawData; UNSIGNED8 Reserved[16]; /* Uncomment necessary values UNSIGNED32 PointerToRelocations; UNSIGNED32 PointerToLinenumbers; UNSIGNED16 NumberOfRelocations; UNSIGNED16 NumberOfLinenumbers; UNSIGNED32 Characteristics; */ } TAG_IMAGE_SECTION_HEADER,*PTAG_IMAGE_SECTION_HEADER; #pragma pack(pop) typedef struct _PE_ALL_HEADERS { TAG_IMAGE_DOS_HEADER dh; UNSIGNED32 signature; TAG_IMAGE_FILE_HEADER fh; union { TAG_IMAGE_OPTIONAL_HEADER32 pe32; TAG_IMAGE_OPTIONAL_HEADER64 pe64; } oh; } PE_ALL_HEADERS,*PPE_ALL_HEADERS; /* checks file header if the file is correct PE file returns 1 is PE file is valid */ int winpe_is_correct_pe_file(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PE_ALL_HEADERS* peh); /* returns a physical file offset of file entry point PE file has to be valid function returns 0 if entry point is not found */ int winpe_entry_point_physical_offset(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PE_ALL_HEADERS* peh, UNSIGNED64 *ep_offset); /* function returns the taggant physical offset inside the file it returns 0 if taggant is not found */ int winpe_taggant_physical_offset(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PE_ALL_HEADERS* peh, UNSIGNED64 ep_physical_offset, UNSIGNED64 *tag_offset); int winpe_is_pe64(PE_ALL_HEADERS* peh); int winpe_read_section_header(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, TAG_IMAGE_SECTION_HEADER *section); UNSIGNED32 winpe_raw_section_size(PE_ALL_HEADERS* peh, TAG_IMAGE_SECTION_HEADER* sec); #endif /* WINPE_HEADER */ <file_sep>/* * fileio.cpp * * Created on: Nov 7, 2011 * Author: <NAME> */ #include <iostream> #include <fstream> #include <istream> #include "taggant_types.h" using namespace std; __DECLARATION size_t fileio_fread(ifstream* fin, void* buffer, size_t size) { fin->read((char*)buffer, size); return fin->gcount(); } __DECLARATION int fileio_fseek(ifstream* fin, UNSIGNED64 offset, int type) { switch (type) { case SEEK_SET: fin->seekg(offset, ios::beg); break; case SEEK_CUR: fin->seekg(offset, ios::cur); break; case SEEK_END: fin->seekg(offset, ios::end); break; default: return 0; } return ((fin->rdstate() & fin->failbit) || (fin->rdstate() & fin->badbit) || (fin->rdstate() & fin->eofbit)) ? 1 : 0; } __DECLARATION UNSIGNED64 fileio_ftell(ifstream* fin) { return fin->tellg(); } UNSIGNED64 fileio_fsize (ifstream* fin) { UNSIGNED64 pos = fileio_ftell(fin); fileio_fseek(fin, 0L, SEEK_END); UNSIGNED64 size = fileio_ftell(fin); fileio_fseek(fin, pos, SEEK_SET); return size; } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include <windows.h> #include <string.h> #include <time.h> #include "fileio.h" #include "taggant_types.h" #include "taggantlib.h" #include "winpe.h" using namespace std; #define SIGNTOOL_VERSION 0x010000 #define SSV_LIB_NAME "libssv.dll" #define SPV_LIB_NAME "libspv.dll" #ifdef _MSC_VER #define strcasecmp _stricmp #endif static UNSIGNED32(STDCALL *pSSVTaggantInitializeLibrary) (__in_opt TAGGANTFUNCTIONS *pFuncs, __out UNSIGNED64 *puVersion); static void(STDCALL *pSSVTaggantFinalizeLibrary) (); static PTAGGANTOBJ(STDCALL *pSSVTaggantObjectNew) (__in_opt PTAGGANT pTaggant); static UNSIGNED32(STDCALL *pSSVTaggantObjectNewEx) (__in_opt PTAGGANT pTaggant, UNSIGNED64 uVersion, TAGGANTCONTAINER eTaggantType, __out PTAGGANTOBJ *pTaggantObj); static void(STDCALL *pSSVTaggantObjectFree) (__deref PTAGGANTOBJ pTaggantObj); static PTAGGANTCONTEXT(STDCALL *pSSVTaggantContextNew) (); static UNSIGNED32(STDCALL *pSSVTaggantContextNewEx) (__out PTAGGANTCONTEXT *pCtx); static void(STDCALL *pSSVTaggantContextFree) (__deref PTAGGANTCONTEXT pTaggantCtx); /* Deprecated function, use TaggantGetInfo/TaggantPutInfo with EPACKERINFO parameter instead */ static DEPRECATED PPACKERINFO(STDCALL *pSSVTaggantPackerInfo) (__in PTAGGANTOBJ pTaggantObj); static UNSIGNED16(STDCALL *pSSVTaggantGetHashMapDoubles) (__in PTAGGANTOBJ pTaggantObj, __out PHASHBLOB_HASHMAP_DOUBLE *pDoubles); static UNSIGNED32(STDCALL *pSSVTaggantValidateDefaultHashes) (__in PTAGGANTCONTEXT pCtx, __in PTAGGANTOBJ pTaggantObj, __in PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd); static UNSIGNED32(STDCALL *pSSVTaggantValidateHashMap) (__in PTAGGANTCONTEXT pCtx, __in PTAGGANTOBJ pTaggantObj, __in PFILEOBJECT hFile); static UNSIGNED32(STDCALL *pSSVTaggantGetTaggant) (__in PTAGGANTCONTEXT pCtx, __in PFILEOBJECT hFile, TAGGANTCONTAINER eContainer, __inout PTAGGANT *pTaggant); static void(STDCALL *pSSVTaggantFreeTaggant) (__deref PTAGGANT pTaggant); static UNSIGNED32(STDCALL *pSSVTaggantValidateSignature) (__in PTAGGANTOBJ pTaggantObj, __in PTAGGANT pTaggant, __in PVOID pRootCert); static UNSIGNED32(STDCALL *pSSVTaggantGetInfo) (__in PTAGGANTOBJ pTaggantObj, ENUMTAGINFO eKey, __inout UNSIGNED32 *pSize, __out_bcount_full_opt(*pSize) PINFO pInfo); static UNSIGNED32(STDCALL *pSSVTaggantGetTimestamp) (__in PTAGGANTOBJ pTaggantObj, __out UNSIGNED64 *pTime, __in PVOID pTSRootCert); static UNSIGNED32(STDCALL *pSSVTaggantCheckCertificate) (__in PVOID pCert); static UNSIGNED32(STDCALL *pSPVTaggantInitializeLibrary) (__in_opt TAGGANTFUNCTIONS *pFuncs, __out UNSIGNED64 *puVersion); static void(STDCALL *pSPVTaggantFinalizeLibrary) (); static PTAGGANTOBJ(STDCALL *pSPVTaggantObjectNew) (__in_opt PTAGGANT pTaggant); static UNSIGNED32(STDCALL *pSPVTaggantObjectNewEx) (__in_opt PTAGGANT pTaggant, UNSIGNED64 uVersion, TAGGANTCONTAINER eTaggantType, __out PTAGGANTOBJ *pTaggantObj); static void(STDCALL *pSPVTaggantObjectFree) (__deref PTAGGANTOBJ pTaggantObj); static PTAGGANTCONTEXT(STDCALL *pSPVTaggantContextNew) (); static UNSIGNED32(STDCALL *pSPVTaggantContextNewEx) (__out PTAGGANTCONTEXT *pCtx); static void(STDCALL *pSPVTaggantContextFree) (__deref PTAGGANTCONTEXT pTaggantCtx); /* Deprecated function, use TaggantGetInfo/TaggantPutInfo with EPACKERINFO parameter instead */ static DEPRECATED PPACKERINFO(STDCALL *pSPVTaggantPackerInfo) (__in PTAGGANTOBJ pTaggantObj); static UNSIGNED32(STDCALL *pSPVTaggantPutInfo) (__inout PTAGGANTOBJ pTaggantObj, ENUMTAGINFO eKey, UNSIGNED32 pSize, __in_bcount(Size) PINFO pInfo); static UNSIGNED32(STDCALL *pSPVTaggantComputeHashes) (__in PTAGGANTCONTEXT pCtx, __inout PTAGGANTOBJ pTaggantObj, __in PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd, UNSIGNED32 uTaggantSize); static UNSIGNED32(STDCALL *pSPVTaggantGetLicenseExpirationDate) (__in const PVOID pLicense, __out UNSIGNED64 *pTime); static UNSIGNED32(STDCALL *pSPVTaggantAddHashRegion) (__inout PTAGGANTOBJ pTaggantObj, UNSIGNED64 uOffset, UNSIGNED64 uLength); static UNSIGNED32(STDCALL *pSPVTaggantPrepare) (__inout PTAGGANTOBJ pTaggantObj, __in const PVOID pLicense, __out_bcount_part(*uTaggantReservedSize, *uTaggantReservedSize) PVOID pTaggantOut, __inout UNSIGNED32 *uTaggantReservedSize); static UNSIGNED32(STDCALL *pSPVTaggantPutTimestamp) (__inout PTAGGANTOBJ pTaggantObj, __in const char* pTSUrl, UNSIGNED32 uTimeout); int init_functions() { HMODULE libssv = LoadLibrary(SSV_LIB_NAME); if (libssv == NULL) { cout << "Error: Cannot load SSV library!\n\n"; return 0; } if ( (pSSVTaggantInitializeLibrary = (UNSIGNED32(STDCALL *) (TAGGANTFUNCTIONS*, UNSIGNED64*)) GetProcAddress(libssv, "TaggantInitializeLibrary")) == NULL || (pSSVTaggantFinalizeLibrary = (void(STDCALL *) ()) GetProcAddress(libssv, "TaggantFinalizeLibrary")) == NULL || (pSSVTaggantObjectNew = (PTAGGANTOBJ(STDCALL *) (PTAGGANT)) GetProcAddress(libssv, "TaggantObjectNew")) == NULL || (pSSVTaggantObjectNewEx = (UNSIGNED32(STDCALL *) (PTAGGANT, UNSIGNED64, TAGGANTCONTAINER, PTAGGANTOBJ*)) GetProcAddress(libssv, "TaggantObjectNewEx")) == NULL || (pSSVTaggantObjectFree = (void(STDCALL *) (PTAGGANTOBJ)) GetProcAddress(libssv, "TaggantObjectFree")) == NULL || (pSSVTaggantContextNew = (PTAGGANTCONTEXT(STDCALL *) ()) GetProcAddress(libssv, "TaggantContextNew")) == NULL || (pSSVTaggantContextNewEx = (UNSIGNED32(STDCALL *) (PTAGGANTCONTEXT*)) GetProcAddress(libssv, "TaggantContextNewEx")) == NULL || (pSSVTaggantContextFree = (void(STDCALL *) (PTAGGANTCONTEXT)) GetProcAddress(libssv, "TaggantContextFree")) == NULL || (pSSVTaggantPackerInfo = (PPACKERINFO(STDCALL *) (PTAGGANTOBJ)) GetProcAddress(libssv, "TaggantPackerInfo")) == NULL || (pSSVTaggantGetHashMapDoubles = (UNSIGNED16(STDCALL *) (PTAGGANTOBJ, PHASHBLOB_HASHMAP_DOUBLE *)) GetProcAddress(libssv, "TaggantGetHashMapDoubles")) == NULL || (pSSVTaggantValidateDefaultHashes = (UNSIGNED32(STDCALL *) (PTAGGANTCONTEXT, PTAGGANTOBJ, PFILEOBJECT, UNSIGNED64, UNSIGNED64)) GetProcAddress(libssv, "TaggantValidateDefaultHashes")) == NULL || (pSSVTaggantValidateHashMap = (UNSIGNED32(STDCALL *) (PTAGGANTCONTEXT, PTAGGANTOBJ, PFILEOBJECT)) GetProcAddress(libssv, "TaggantValidateHashMap")) == NULL || (pSSVTaggantGetTaggant = (UNSIGNED32(STDCALL *) (PTAGGANTCONTEXT, PFILEOBJECT, TAGGANTCONTAINER, PTAGGANT*)) GetProcAddress(libssv, "TaggantGetTaggant")) == NULL || (pSSVTaggantFreeTaggant = (void(STDCALL *) (PTAGGANT)) GetProcAddress(libssv, "TaggantFreeTaggant")) == NULL || (pSSVTaggantValidateSignature = (UNSIGNED32(STDCALL *) (PTAGGANTOBJ, PTAGGANT, PVOID)) GetProcAddress(libssv, "TaggantValidateSignature")) == NULL || (pSSVTaggantGetInfo = (UNSIGNED32(STDCALL *) (PTAGGANTOBJ, ENUMTAGINFO, UNSIGNED32*, PINFO)) GetProcAddress(libssv, "TaggantGetInfo")) == NULL || (pSSVTaggantGetTimestamp = (UNSIGNED32(STDCALL *) (PTAGGANTOBJ, UNSIGNED64*, PVOID)) GetProcAddress(libssv, "TaggantGetTimestamp")) == NULL || (pSSVTaggantCheckCertificate = (UNSIGNED32(STDCALL *) (PVOID)) GetProcAddress(libssv, "TaggantCheckCertificate")) == NULL ) { cout << "Error: Cannot initialize functions of SSV library!\n\n"; return 0; } HMODULE libspv = LoadLibrary(SPV_LIB_NAME); if (libspv == NULL) { cout << "Error: Cannot load SPV library!\n\n"; return 0; } if ( (pSPVTaggantInitializeLibrary = (UNSIGNED32(STDCALL *) (TAGGANTFUNCTIONS*, UNSIGNED64*)) GetProcAddress(libspv, "TaggantInitializeLibrary")) == NULL || (pSPVTaggantFinalizeLibrary = (void(STDCALL *) ()) GetProcAddress(libspv, "TaggantFinalizeLibrary")) == NULL || (pSPVTaggantObjectNew = (PTAGGANTOBJ(STDCALL *) (PTAGGANT)) GetProcAddress(libspv, "TaggantObjectNew")) == NULL || (pSPVTaggantObjectNewEx = (UNSIGNED32(STDCALL *) (PTAGGANT, UNSIGNED64, TAGGANTCONTAINER, PTAGGANTOBJ*)) GetProcAddress(libspv, "TaggantObjectNewEx")) == NULL || (pSPVTaggantObjectFree = (void(STDCALL *) (PTAGGANTOBJ)) GetProcAddress(libspv, "TaggantObjectFree")) == NULL || (pSPVTaggantContextNew = (PTAGGANTCONTEXT(STDCALL *) ()) GetProcAddress(libspv, "TaggantContextNew")) == NULL || (pSPVTaggantContextNewEx = (UNSIGNED32(STDCALL *) (PTAGGANTCONTEXT*)) GetProcAddress(libspv, "TaggantContextNewEx")) == NULL || (pSPVTaggantContextFree = (void(STDCALL *) (PTAGGANTCONTEXT)) GetProcAddress(libspv, "TaggantContextFree")) == NULL || (pSPVTaggantPackerInfo = (PPACKERINFO(STDCALL *) (PTAGGANTOBJ)) GetProcAddress(libspv, "TaggantPackerInfo")) == NULL || (pSPVTaggantPutInfo = (UNSIGNED32(STDCALL *) (PTAGGANTOBJ, ENUMTAGINFO, UNSIGNED32, PINFO)) GetProcAddress(libspv, "TaggantPutInfo")) == NULL || (pSPVTaggantComputeHashes = (UNSIGNED32(STDCALL *) (PTAGGANTCONTEXT, PTAGGANTOBJ, PFILEOBJECT, UNSIGNED64, UNSIGNED64, UNSIGNED32)) GetProcAddress(libspv, "TaggantComputeHashes")) == NULL || (pSPVTaggantGetLicenseExpirationDate = (UNSIGNED32(STDCALL *) (const PVOID, UNSIGNED64*)) GetProcAddress(libspv, "TaggantGetLicenseExpirationDate")) == NULL || (pSPVTaggantAddHashRegion = (UNSIGNED32(STDCALL *) (PTAGGANTOBJ, UNSIGNED64, UNSIGNED64)) GetProcAddress(libspv, "TaggantAddHashRegion")) == NULL || (pSPVTaggantPrepare = (UNSIGNED32(STDCALL *) (PTAGGANTOBJ, const PVOID, PVOID, UNSIGNED32*)) GetProcAddress(libspv, "TaggantPrepare")) == NULL || (pSPVTaggantPutTimestamp = (UNSIGNED32(STDCALL *) (PTAGGANTOBJ, const char*, UNSIGNED32)) GetProcAddress(libspv, "TaggantPutTimestamp")) == NULL ) { cout << "Error: Cannot initialize functions of SPV library!\n\n"; return 0; } return 1; } int main(int argc, char *argv[], char *envp[]) { int silent = 0; int filearg = 1; if ((argc > 1) && !stricmp(argv[1], "-silent")) { silent = 1; filearg = 2; } if (!silent) cout << "SignTool Application (adds Taggant v2 to files)\n\n"; const char* usage = "Usage: signtool.exe [-silent] <file_to_sign> <license.pem> [optional] -t:<type> -csa -r:<root.crt> -s:<timestamp server url>\n\n-t:<type> - type of the file to sign (pe/js/txt/bin)\n-csa - enables CSA Mode\n-r:<root.crt> - root certificate for CSA Mode\n-s:<timestamp server url> - url to the timestamp server (default: http://taggant-tsa.ieee.org/)\n\n"; // Check if number of arguments is not less than 2 if (argc < 2) { cout << "Error: Invalid Arguments, no file_to_sign and/or license.pem is specified!\n\n" << usage; return 1; } if (!init_functions()) { return 1; } // Get the type of the file to sign (pe/js) TAGGANTCONTAINER filetype = TAGGANT_PEFILE; int csamode = 0; char *rootfile = NULL; char *root = NULL; char *tsurl = NULL; if (argc >= 3) { for (int i = 3; i < argc; i++) { if (stricmp(argv[i], "-csa") == 0) { csamode = 1; } else if (strnicmp(argv[i], "-r:", 3) == 0) { int len = strlen(argv[i]) - 3 + 1; rootfile = new char[len]; memset(rootfile, 0, len); strcpy(rootfile, argv[i] + 3); } else if (strnicmp(argv[i], "-t:", 3) == 0) { char type[4]; memset(&type, 0, sizeof(type)); strncpy((char*)&type, argv[i] + 3, strlen(argv[i]) > 6 ? 3 : strlen(argv[i]) - 3); // Determine the type if (stricmp((char*)&type, "js") == 0) { filetype = TAGGANT_JSFILE; } else if (stricmp((char*)&type, "txt") == 0) { filetype = TAGGANT_TXTFILE; } else if (stricmp((char*)&type, "bin") == 0) { filetype = TAGGANT_BINFILE; } } else if (strnicmp(argv[i], "-s:", 3) == 0) { int len = strlen(argv[i]) - 3 + 1; tsurl = new char[len]; memset(tsurl, 0, len); strcpy(tsurl, argv[i] + 3); } } } int err = 0; UNSIGNED32 ffhres = TNOTIMPLEMENTED; UNSIGNED32 hmhres = TNOERR; // If CSA mode is used, load and check root and tsroot certificates if (csamode) { // Initialize SSV taggant library TAGGANTFUNCTIONS funcs; memset(&funcs, 0, sizeof(TAGGANTFUNCTIONS)); UNSIGNED64 uVersion; // Set structure size funcs.size = sizeof(TAGGANTFUNCTIONS); pSSVTaggantInitializeLibrary(&funcs, &uVersion); if (!silent) cout << "SSV Taggant Library version " << uVersion << "\n"; if (uVersion < TAGGANT_LIBRARY_VERSION2) { if (!silent) cout << "Current SSV taggant library does not support version 2\n\n"; err = 1; } if (!err) { ifstream tmps(rootfile, ios::binary); if (tmps.is_open()) { tmps.seekg(0, ios::end); long tmpsize = tmps.tellg(); root = new char[tmpsize]; tmps.seekg(0, ios::beg); tmps.read(root, tmpsize); tmps.close(); // Check certificate if (pSSVTaggantCheckCertificate(root) != TNOERR) { if (!silent) cout << "Error: root certificate is invalid\n\n" << usage; err = 1; } } else { if (!silent) cout << "Error: root certificate file does not exist\n\n" << usage; err = 1; } // Check the previous taggant before adding a new one if (!err) { UNSIGNED32 res = TNOERR; // Create taggant context PTAGGANTCONTEXT pCtx; if ((res = pSSVTaggantContextNewEx(&pCtx)) == TNOERR) { // Vendor should check version flow here! pCtx->FileReadCallBack = (size_t(__DECLARATION *)(void*, void*, size_t))fileio_fread; pCtx->FileSeekCallBack = (int (__DECLARATION *)(void*, UNSIGNED64, int))fileio_fseek; pCtx->FileTellCallBack = (UNSIGNED64(__DECLARATION *)(void*))fileio_ftell; // Try to open the file ifstream fin(argv[filearg], ios::binary); if (fin.is_open()) { void *taggant = NULL; // Get the taggant from the file if ((res = pSSVTaggantGetTaggant(pCtx, (void*)&fin, filetype, &taggant)) == TNOERR) { // Initialize taggant object before it will be validated PTAGGANTOBJ tag_obj; if ((res = pSSVTaggantObjectNewEx(taggant, 0, TAGGANT_PEFILE, &tag_obj)) == TNOERR) { // Validate the taggant if ((res = pSSVTaggantValidateSignature(tag_obj, taggant, (PVOID)root)) == TNOERR) { // get the ignore hash map value UNSIGNED8 ignorehmh = 0; UNSIGNED32 ihmhsize = sizeof(UNSIGNED8); res = pSSVTaggantGetInfo(tag_obj, EIGNOREHMH, &ihmhsize, (char*)&ignorehmh); if (res == TNOERR || res == TNOTFOUND || res == TERRORKEY) { res = TNOERR; if (!ignorehmh) { // Get file hash type // Do a quick file check using hash map (in case it exists) PHASHBLOB_HASHMAP_DOUBLE dbl = NULL; int dbl_count = pSSVTaggantGetHashMapDoubles(tag_obj, &dbl); if (dbl_count) { // Compute hashmap of the current file, remember result for later hmhres = pSSVTaggantValidateHashMap(pCtx, tag_obj, (void*)&fin); } } // get the previous tag value UNSIGNED8 tagprev = 0; UNSIGNED32 tprevsize = sizeof(UNSIGNED8); res = pSSVTaggantGetInfo(tag_obj, ETAGPREV, &tprevsize, (char*)&tagprev); if (res == TNOERR || res == TNOTFOUND || res == TERRORKEY) { res = TNOERR; // Check full file hash only if there is no previous tag if (!tagprev) { UNSIGNED64 file_end = 0; UNSIGNED32 size = sizeof(UNSIGNED64); // Get file end value from the taggant, used for taggant v1 only if (pSSVTaggantGetInfo(tag_obj, EFILEEND, &size, (char*)&file_end) == TNOERR) { if (!file_end) { file_end = fileio_fsize(&fin); } int object_end = 0; if (filetype == TAGGANT_PEFILE) { PE_ALL_HEADERS peh; if (winpe_is_correct_pe_file(&fin, &peh)) { object_end = winpe_object_size(&fin, &peh); } } // Compute default hashes of the current file ffhres = pSSVTaggantValidateDefaultHashes(pCtx, tag_obj, (void*)&fin, object_end, file_end); if (ffhres != TNOERR) { res = ffhres; } } } else if (hmhres != TNOERR) { res = hmhres; } } } } pSSVTaggantObjectFree(tag_obj); } } pSSVTaggantFreeTaggant(taggant); fin.close(); } else { if (!silent) cout << "Error: Cannot open file to validate for CSA mode\n\n"; err = 1; } pSSVTaggantContextFree(pCtx); } if (res != TNOTAGGANTS && res != TNOERR) { if (!silent) cout << "Error: Validation of the file for CSA mode failed with error " << res <<" \n\n"; err = res; } } } pSSVTaggantFinalizeLibrary(); } delete[] rootfile; delete[] root; if (!err) { // Check if the first argument refers to existing file ifstream ffs(argv[filearg], ios::binary); if (ffs.is_open()) { // Initialize taggant library TAGGANTFUNCTIONS funcs; memset(&funcs, 0, sizeof(TAGGANTFUNCTIONS)); UNSIGNED64 uVersion; // Set structure size funcs.size = sizeof(TAGGANTFUNCTIONS); //spv_namespace::Tagga pSPVTaggantInitializeLibrary(&funcs, &uVersion); if (!silent) cout << "SPV Taggant Library version " << uVersion << "\n"; // Make sure the taggant library supports version 2 if (uVersion < TAGGANT_LIBRARY_VERSION2) { if (!silent) cout << "Error: Current taggant library does not support version 2\n\n"; err = 1; } if (!err) { // Check if the license.pem file exist char* lic; ifstream flc(argv[filearg + 1], ios::binary); if (!flc.is_open()) { if (!silent) cout << "Error: license.pem does not exist\n\n" << usage; err = 1; } else { // Read license from file flc.seekg(0, ios::end); long fsize = flc.tellg(); lic = new char[fsize]; flc.seekg(0, ios::beg); flc.read(lic, fsize); // Make sure the license is valid UNSIGNED64 ltime; if (pSPVTaggantGetLicenseExpirationDate(lic, &ltime) == TNOERR) { if (!silent) cout << "License file is valid, expiration date is " << asctime(gmtime((time_t*)&ltime)); // Create taggant context PTAGGANTCONTEXT pCtx; UNSIGNED32 ctxres = pSPVTaggantContextNewEx(&pCtx); if (ctxres == TNOERR) { // Vendor should check version flow here! pCtx->FileReadCallBack = (size_t(__DECLARATION *)(void*, void*, size_t))fileio_fread; pCtx->FileSeekCallBack = (int (__DECLARATION *)(void*, UNSIGNED64, int))fileio_fseek; pCtx->FileTellCallBack = (UNSIGNED64(__DECLARATION *)(void*))fileio_ftell; PTAGGANTOBJ tagobj; UNSIGNED32 objres = pSPVTaggantObjectNewEx(NULL, TAGGANT_LIBRARY_VERSION2, filetype, &tagobj); if (objres == TNOERR) { UNSIGNED32 hashres = pSPVTaggantComputeHashes(pCtx, tagobj, &ffs, 0, 0, 0); if (hashres == TNOERR) { if (!silent) cout << "File hashes computed successfully\n"; // set packer information PACKERINFO packer_info; memset(&packer_info, 0, sizeof(PACKERINFO)); packer_info.PackerId = 1; packer_info.VersionMajor = SIGNTOOL_VERSION >> 16 & 0xFF; packer_info.VersionMinor = SIGNTOOL_VERSION >> 8 & 0xFF; packer_info.VersionBuild = SIGNTOOL_VERSION & 0xFF; UNSIGNED32 packerres = pSPVTaggantPutInfo(tagobj, EPACKERINFO, sizeof(PACKERINFO), (char*)&packer_info); if (packerres == TNOERR) { UNSIGNED32 ihmhres = TNOERR; if ((ffhres == TNOERR) && (hmhres != TNOERR)) { UNSIGNED8 ignorehmh = 1; ihmhres = pSPVTaggantPutInfo(tagobj, EIGNOREHMH, sizeof(UNSIGNED8), (char*)&ignorehmh); } if (ihmhres == TNOERR) { // Set contributor list information char *clist = "CONTRIBUTORS LIST HERE"; UNSIGNED32 clistres = pSPVTaggantPutInfo(tagobj, ECONTRIBUTORLIST, strlen(clist) + 1, clist); if (clistres == TNOERR) { // try to put timestamp if (!silent) cout << "Put timestamp\n"; UNSIGNED32 timestampres = pSPVTaggantPutTimestamp(tagobj, tsurl ? tsurl : "http://taggant-tsa.ieee.org/", 50); if (!silent) { switch (timestampres) { case TNOERR: { cout << "Timestamp successfully placed\n"; break; } case TNONET: { cout << "Warning: Can't put timestamp, no connection to the internet\n"; break; } case TTIMEOUT: { cout << "Warning: Can't put timestamp, the timestamp authority server response time has expired\n"; break; } default: { cout << "Warning: Can't put timestamp, error: " << timestampres << "\n"; break; } } cout << "Prepare the taggant\n"; } // allocate the approximate buffer for CMS UNSIGNED32 taggantsize = 0x10000; char* taggant = new char[taggantsize]; UNSIGNED32 prepareres = pSPVTaggantPrepare(tagobj, (PVOID)lic, taggant, &taggantsize); // if the allocated buffer is not sufficient then allocate bigger buffer if (prepareres == TINSUFFICIENTBUFFER) { delete[] taggant; taggantsize = taggantsize * 2; taggant = new char[taggantsize]; prepareres = pSPVTaggantPrepare(tagobj, (PVOID)lic, taggant, &taggantsize); } if (prepareres == TNOERR) { if (!silent) cout << "Taggant successfully created\n"; // append the file with the taggant ofstream ofs(argv[filearg], ios::binary | ios::app | ios::out); if (ofs.is_open()) { ofs.write(taggant, taggantsize); if (!silent) cout << "Taggant is written to file\n"; } ofs.close(); } else { if (!silent) cout << "Error: TaggantPrepare failed with result: " << prepareres << "\n\n"; } delete[] taggant; } else { if (!silent) cout << "Error: TaggantSetInfo failed to set contributor list information with result: " << clistres << "\n\n"; err = 1; } } else { if (!silent) cout << "Error: TaggantSetInfo failed to set EIGNOREHMH with result: " << ihmhres << "\n\n"; err = 1; } } else { if (!silent) cout << "Error: TaggantSetInfo failed to set packer information with result: " << packerres << "\n\n"; err = 1; } } else { if (!silent) cout << "Error: TaggantComputeHashes failed with result: " << hashres << "\n\n"; err = 1; } pSPVTaggantObjectFree(tagobj); } else { if (!silent) cout << "Error: TaggantObjectNewEx failed with result: " << objres << "\n\n"; err = 1; } pSPVTaggantContextFree(pCtx); } else { if (!silent) cout << "Error: TaggantContextNewEx failed with result: " << ctxres << "\n\n"; err = 1; } } else { if (!silent) cout << "Error: License file is not valid\n\n"; err = 1; } } flc.close(); delete[] lic; } pSPVTaggantFinalizeLibrary(); } else { if (!silent) cout << "Error: file_to_sign does not exist\n\n" << usage; err = 1; } ffs.close(); } delete[] tsurl; return err; } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include "global.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "types.h" #include "taggant.h" #include "endianness.h" #include "taggant_types.h" #include "callbacks.h" #include "miscellaneous.h" UNSIGNED32 txt_taggant_header2_size(void) { return sizeof(UNSIGNED16) * 2 /* Version */ + sizeof(UNSIGNED32) * 2 /* CMSLength */ + sizeof(UNSIGNED32) * 2 /* TaggantLength */ + sizeof(UNSIGNED32) /* MarkerBegin */; } UNSIGNED32 txt_read_taggant_header2(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED64 offset, TAGGANT_HEADER2* pTagHeader, UNSIGNED32 *uSize) { UNSIGNED32 res = TFILEACCESSDENIED, size = txt_taggant_header2_size(); /* offset is pointing to the end of the taggant header */ /* seek to the beginning of the taggant header */ memset(pTagHeader, 0, sizeof(TAGGANT_HEADER2)); if (file_seek(pCtx, fp, offset - size, SEEK_SET)) { /* read Version */ if (file_read_textual_UNSIGNED16(pCtx, fp, &pTagHeader->Version)) { /* read CMSLength */ if (file_read_textual_UNSIGNED32(pCtx, fp, &pTagHeader->CMSLength)) { /* read TaggantLength */ if (file_read_textual_UNSIGNED32(pCtx, fp, &pTagHeader->TaggantLength)) { if (file_read_UNSIGNED32(pCtx, fp, &pTagHeader->MarkerBegin)) { *uSize = size; res = TNOERR; } } } } } return res; } UNSIGNED32 txt_bio_base64_decode(BIO *inbio, BIO *outbio) { BIO *bio64, *tbio; char inbuf[512]; int inlen; UNSIGNED32 res = 0; bio64 = BIO_new(BIO_f_base64()); if (bio64) { BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL); tbio = BIO_push(bio64, inbio); while ((inlen = BIO_read(tbio, inbuf, 512)) > 0) { BIO_write(outbio, inbuf, inlen); res += inlen; } BIO_free(bio64); } return res; } UNSIGNED32 txt_read_taggant_cms(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED64 offset, UNSIGNED32 size, PVOID* pCms, UNSIGNED32 *uSize) { char *buf; BIO *biomem, *biomemout; int osize; UNSIGNED32 res = TFILEACCESSDENIED; if (file_seek(pCtx, fp, offset - size, SEEK_SET)) { buf = memory_alloc(size); if (buf) { if (file_read_buffer(pCtx, fp, buf, size)) { biomem = BIO_new(BIO_s_mem()); if (biomem) { BIO_write(biomem, buf, size); biomemout = BIO_new(BIO_s_mem()); if (biomemout) { osize = txt_bio_base64_decode(biomem, biomemout); if (osize) { *pCms = memory_alloc(osize); if (*pCms) { BIO_read(biomemout, *pCms, osize); *uSize = osize; res = TNOERR; } else { res = TMEMORY; } } BIO_free(biomemout); } else { res = TMEMORY; } BIO_free(biomem); } else { res = TMEMORY; } } else { res = TFILEACCESSDENIED; } memory_free(buf); } else { res = TMEMORY; } } else { res = TFILEACCESSDENIED; } return res; } UNSIGNED32 txt_read_taggant_footer2(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED64 offset, TAGGANT_FOOTER2* pTagFooter, UNSIGNED32 *uSize) { UNSIGNED32 res = TFILEACCESSDENIED; /* offset is pointing to the end of the taggant footer */ /* seek to the beginning of the taggant footer */ memset(pTagFooter, 0, sizeof(TAGGANT_FOOTER2)); /* Read end marker */ if (file_seek(pCtx, fp, offset - sizeof(UNSIGNED32), SEEK_SET)) { if (file_read_UNSIGNED32(pCtx, fp, &pTagFooter->MarkerEnd)) { /* Return the size of taggant_footer2 structure */ *uSize = sizeof(UNSIGNED32) /* size of end marker */; res = TNOERR; } else { res = TFILEACCESSDENIED; } } else { res = TFILEACCESSDENIED; } return res; } int txt_write_UNSIGNED16(BIO *outBio, UNSIGNED16 value) { char buf[5]; if (sprintf((char*)&buf, "%.4x", value) == sizeof(buf) - 1) { BIO_write(outBio, &buf, sizeof(buf) - 1); return 1; } return 0; } int txt_write_UNSIGNED32(BIO *outBio, UNSIGNED32 value) { char buf[9]; if (sprintf((char*)&buf, "%.8x", value) == sizeof(buf) - 1) { BIO_write(outBio, &buf, sizeof(buf) - 1); return 1; } return 0; } int txt_write_taggant_header2(PTAGGANT_HEADER2 pTagHeader, BIO *outBio) { UNSIGNED32 val; if (txt_write_UNSIGNED16(outBio, pTagHeader->Version)) { if (txt_write_UNSIGNED32(outBio, pTagHeader->CMSLength)) { if (txt_write_UNSIGNED32(outBio, pTagHeader->TaggantLength)) { val = pTagHeader->MarkerBegin; if (IS_BIG_ENDIAN) { UNSIGNED32_to_little_endian(val, (char*)&val); } BIO_write(outBio, (char*)&val, sizeof(val)); return 1; } } } return 0; } UNSIGNED32 txt_bio_base64_encode(BIO *inbio, BIO *outbio) { BIO *bio64, *tbio; char inbuf[512], *buf; int inlen, size; int maxlen = MAX_INTEGER; UNSIGNED32 res = 0; bio64 = BIO_new(BIO_f_base64()); if (bio64) { BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL); tbio = BIO_push(bio64, inbio); size = BIO_read(inbio, NULL, maxlen); buf = memory_alloc(size); if (buf) { BIO_read(inbio, buf, size); BIO_write(tbio, buf, size); BIO_flush(tbio); while ((inlen = BIO_read(inbio, inbuf, 512)) > 0) { BIO_write(outbio, inbuf, inlen); res += inlen; } memory_free(buf); } BIO_free(bio64); } return res; } int txt_write_buffer(BIO *outBio, char *buffer, UNSIGNED16 length) { int i, res = 1; char buf[3]; for (i = 0; i < length; i++) { if (sprintf((char*)&buf, "%.2x", *buffer) == sizeof(buf) - 1) { BIO_write(outBio, &buf, sizeof(buf) - 1); } else { res = 0; break; } buffer++; } return 0; } int txt_write_taggant_footer2(PTAGGANT_FOOTER2 pTagFooter, BIO *outBio, UNSIGNED32 *size) { UNSIGNED32 val = pTagFooter->MarkerEnd; /* write end marker */ if (IS_BIG_ENDIAN) { UNSIGNED32_to_little_endian(val, (char*)&val); } BIO_write(outBio, (char*)&val, sizeof(val)); /* return the size of written data */ *size = sizeof(val); return 1; }<file_sep>/* * miscellaneous.c * * Created on: Dec 19, 2011 * Author: Enigma */ #include <stdio.h> #include <stdlib.h> #include "taggant_types.h" long round_up(long alignment, long size) { return (size % alignment != 0 && size != 0) ? size + alignment - size % alignment : size; } long round_down(long alignment, long size) { return (size % alignment != 0 && size != 0) ? size - size % alignment : size; } long get_min(long v1, long v2) { return (v1 < v2) ? v1 : v2; } long get_file_size (PTAGGANTCONTEXT pCtx, PFILEOBJECT fp) { long size; long pos = pCtx->FileTellCallBack(fp); pCtx->FileSeekCallBack(fp, 0, SEEK_END); size = pCtx->FileTellCallBack(fp); pCtx->FileSeekCallBack(fp, pos, SEEK_SET); return size; } <file_sep>/* * winpe.h * * Created on: Oct 16, 2011 * Author: Enigma */ #ifndef WINPE_H_ #define WINPE_H_ #include <iostream> #include <fstream> #include <istream> #include <string> #include <string.h> #include "winpe_types.h" using namespace std; #define TAGGANT_ADDRESS_JMP 0x08EB #define TAGGANT_ADDRESS_JMP_SIZE 2 typedef struct _PE_ALL_HEADERS { IMAGE_DOS_HEADER dh; DWORD signature; IMAGE_FILE_HEADER fh; union { IMAGE_OPTIONAL_HEADER32 pe32; IMAGE_OPTIONAL_HEADER64 pe64; } oh; } PE_ALL_HEADERS,*PPE_ALL_HEADERS; // checks file header if the file is correct PE file // returns TRUE is PE file is valid int winpe_is_correct_pe_file(ifstream* fp, PE_ALL_HEADERS* peh); // returns a physical file offset of file entry point // PE file has to be valid // function returns -1 if entry point is not found long winpe_entry_point_physical_offset(ifstream* fp, PE_ALL_HEADERS* peh); int winpe_is_pe64(PE_ALL_HEADERS* peh); int winpe_va_to_rwa(ifstream* fp, PE_ALL_HEADERS* peh, unsigned long va); int winpe_object_size(ifstream* fp, PE_ALL_HEADERS* peh); #endif /* WINPE_H_ */ <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #ifndef FILEIO_H_ #define FILEIO_H_ #include <iostream> #include <fstream> #include <istream> #include "taggant_types.h" using namespace std; size_t __DECLARATION fileio_fread(ifstream* fin, void* buffer, size_t size); int __DECLARATION fileio_fseek(ifstream* fin, UNSIGNED64 offset, int type); UNSIGNED64 __DECLARATION fileio_ftell(ifstream* fin); UNSIGNED64 fileio_fsize (ifstream* fin); #endif /* FILEIO_H_ */ <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include "global.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "callbacks.h" #include "taggantlib.h" #include "endianness.h" unsigned long round_up(unsigned long alignment, unsigned long size) { return (size + alignment - 1) & (0 - alignment); } unsigned long round_down(unsigned long alignment, unsigned long size) { return size & (0 - alignment); } unsigned long get_min(unsigned long v1, unsigned long v2) { return (v1 < v2) ? v1 : v2; } unsigned long get_max(unsigned long v1, unsigned long v2) { return (v1 > v2) ? v1 : v2; } UNSIGNED64 get_file_size (PTAGGANTCONTEXT pCtx, PFILEOBJECT fp) { UNSIGNED64 size; UNSIGNED64 pos = pCtx->FileTellCallBack(fp); pCtx->FileSeekCallBack(fp, 0, SEEK_END); size = pCtx->FileTellCallBack(fp); pCtx->FileSeekCallBack(fp, pos, SEEK_SET); return size; } int file_seek(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED64 offset, int type) { return pCtx->FileSeekCallBack(fp, offset, type) == 0 ? 1 : 0; } int file_read_buffer(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, void* buffer, size_t length) { return (pCtx->FileReadCallBack(fp, buffer, length) == length) ? 1 : 0; } int file_read_UNSIGNED16(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED16 *value) { if (pCtx->FileReadCallBack(fp, value, sizeof(UNSIGNED16)) == sizeof(UNSIGNED16)) { if (IS_BIG_ENDIAN) { *value = UNSIGNED16_to_big_endian((char*)value); } return 1; } return 0; } int file_read_UNSIGNED32(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED32 *value) { if (pCtx->FileReadCallBack(fp, value, sizeof(UNSIGNED32)) == sizeof(UNSIGNED32)) { if (IS_BIG_ENDIAN) { *value = UNSIGNED32_to_big_endian((char*)value); } return 1; } return 0; } int file_read_UNSIGNED64(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED64 *value) { if (pCtx->FileReadCallBack(fp, value, sizeof(UNSIGNED64)) == sizeof(UNSIGNED64)) { if (IS_BIG_ENDIAN) { *value = UNSIGNED64_to_big_endian((char*)value); } return 1; } return 0; } int file_read_textual_UNSIGNED16(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED16 *value) { char buf[5]; memset(&buf, 0, sizeof(buf)); if (pCtx->FileReadCallBack(fp, &buf, sizeof(buf) - 1) == sizeof(buf) - 1) { *value = (UNSIGNED16)strtol((char*)&buf, NULL, 16); return 1; } return 0; } int file_read_textual_UNSIGNED32(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED32 *value) { char buf[9]; memset(&buf, 0, sizeof(buf)); if (pCtx->FileReadCallBack(fp, &buf, sizeof(buf) - 1) == sizeof(buf) - 1) { *value = (UNSIGNED32)strtol((char*)&buf, NULL, 16); return 1; } return 0; } int file_read_textual_buffer(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PVOID buffer, UNSIGNED16 length) { PVOID tmpbuf; int i, res = 0, len; char buf[3], *intmpbuf, *outtmpbuf; len = length * 2; tmpbuf = memory_alloc(len); if (tmpbuf) { memset(tmpbuf, 0, len); if ((int)pCtx->FileReadCallBack(fp, tmpbuf, len) == len) { memset(buf, 0, sizeof(buf)); intmpbuf = (char*)tmpbuf; outtmpbuf = (char*)buffer; for (i = 0; i < len; i += 2) { buf[0] = *intmpbuf; intmpbuf++; buf[1] = *intmpbuf; intmpbuf++; *outtmpbuf = (UNSIGNED8)strtol((char*)&buf, NULL, 16); outtmpbuf++; } res = 1; } memory_free(tmpbuf); } return res; }<file_sep>/* * winpe_types.h * * Created on: Oct 16, 2011 * Author: Enigma */ #ifndef WINPE_TYPES_H_ #define WINPE_TYPES_H_ typedef long LONG; typedef unsigned char BYTE,*PBYTE; typedef unsigned short WORD,*PWORD; typedef unsigned long DWORD,*PDWORD; typedef unsigned long long ULONGLONG; #define IMAGE_DOS_SIGNATURE 0x5A4D #define IMAGE_NT_SIGNATURE 0x00004550 #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 #define IMAGE_FILE_MACHINE_I386 0x014c /* Intel 386 or later processors */ #define IMAGE_FILE_MACHINE_IA64 0x0200 /* Intel Itanium processor family */ #define IMAGE_FILE_MACHINE_AMD64 0x8664 /* x64 */ #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b #define IMAGE_SIZEOF_SHORT_NAME 8 #pragma pack(push,1) typedef struct _IMAGE_DOS_HEADER { WORD e_magic; WORD e_cblp; WORD e_cp; WORD e_crlc; WORD e_cparhdr; WORD e_minalloc; WORD e_maxalloc; WORD e_ss; WORD e_sp; WORD e_csum; WORD e_ip; WORD e_cs; WORD e_lfarlc; WORD e_ovno; WORD e_res[4]; WORD e_oemid; WORD e_oeminfo; WORD e_res2[10]; LONG e_lfanew; } IMAGE_DOS_HEADER,*PIMAGE_DOS_HEADER; typedef struct _IMAGE_FILE_HEADER { WORD Machine; WORD NumberOfSections; DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; WORD Characteristics; } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; typedef struct _IMAGE_DATA_DIRECTORY { DWORD VirtualAddress; DWORD Size; } IMAGE_DATA_DIRECTORY,*PIMAGE_DATA_DIRECTORY; typedef struct _IMAGE_OPTIONAL_HEADER { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; DWORD BaseOfData; DWORD ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; DWORD SizeOfStackReserve; DWORD SizeOfStackCommit; DWORD SizeOfHeapReserve; DWORD SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER32,*PIMAGE_OPTIONAL_HEADER32; typedef struct _IMAGE_OPTIONAL_HEADER64 { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; ULONGLONG ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; ULONGLONG SizeOfStackReserve; ULONGLONG SizeOfStackCommit; ULONGLONG SizeOfHeapReserve; ULONGLONG SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER64,*PIMAGE_OPTIONAL_HEADER64; typedef struct _IMAGE_SECTION_HEADER { BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; union { DWORD PhysicalAddress; DWORD VirtualSize; } Misc; DWORD VirtualAddress; DWORD SizeOfRawData; DWORD PointerToRawData; DWORD PointerToRelocations; DWORD PointerToLinenumbers; WORD NumberOfRelocations; WORD NumberOfLinenumbers; DWORD Characteristics; } IMAGE_SECTION_HEADER,*PIMAGE_SECTION_HEADER; #pragma pack(pop) #endif /* WINPE_TYPES_H_ */ <file_sep>Link: ../crypto/constant_time_test.c<file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #ifndef COMMON_TYPES_HEADER #define COMMON_TYPES_HEADER /* Do not remove this include because it is necessary for size_t type definition for MinGW compiler */ #include <stdio.h> /* TAGGANT_MINIMUM_SIZE should be greater than sum of sizeof(TAGGANT_HEADER) and sizeof(TAGGANT_FOOTER) */ #define TAGGANT_MINIMUM_SIZE 0x00002000 #define TAGGANT_MAXIMUM_SIZE 0x0000FFFF #define PFILEOBJECT void* #define UNSIGNED8 unsigned char #define UNSIGNED16 unsigned short #define SIGNED32 int #define UNSIGNED32 unsigned long #if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__) typedef unsigned __int64 UNSIGNED64; typedef __int64 SIGNED64; #elif defined(__arch64__) typedef unsigned long UNSIGNED64; typedef long SIGNED64; #else typedef unsigned long long UNSIGNED64; typedef long long SIGNED64; #endif #define PVOID void* #define PINFO char* typedef enum { TAGGANT_PEFILE = 0 } TAGGANTCONTAINER; typedef enum { ETAGGANTBLOB = 0, ESPVCERT = 1, EUSERCERT = 2, EFILEEND = 3 } ENUMTAGINFO; #ifdef WIN32 # define __DECLARATION __stdcall #else # define __DECLARATION #endif #pragma pack(push,2) typedef struct { UNSIGNED64 AbsoluteOffset; UNSIGNED64 Length; } HASHBLOB_HASHMAP_DOUBLE, *PHASHBLOB_HASHMAP_DOUBLE; typedef struct { UNSIGNED32 PackerId; UNSIGNED16 VersionMajor; UNSIGNED16 VersionMinor; UNSIGNED16 VersionBuild; UNSIGNED16 Reserved; } PACKERINFO, *PPACKERINFO; typedef struct { size_t size; /* File IO callbacks */ size_t (__DECLARATION *FileReadCallBack)(PFILEOBJECT, void*, size_t); int (__DECLARATION *FileSeekCallBack)(PFILEOBJECT, UNSIGNED64, int); UNSIGNED64 (__DECLARATION *FileTellCallBack)(PFILEOBJECT); } TAGGANTCONTEXT, *PTAGGANTCONTEXT; typedef struct { size_t size; /* Memory callbacks */ void* (__DECLARATION *MemoryAllocCallBack)(size_t); void* (__DECLARATION *MemoryReallocCallBack)(void*, size_t); void (__DECLARATION *MemoryFreeCallBack)(void*); } TAGGANTFUNCTIONS, *PTAGGANTFUNCTIONS; #pragma pack(pop) #ifndef TAGGANT_LIBRARY #define PTAGGANT PVOID #define PTAGGANTOBJ PVOID #endif #define TNOERR 0 #define TTYPE 1 #define TNOTAGGANTS 2 #define TMEMORY 3 #define TFILEERROR 4 #define TBADKEY 5 #define TMISMATCH 6 #define TERRORKEY 7 #define TNONET 8 #define TTIMEOUT 9 #define TINTERNALERROR 10 #define TSERVERERROR 11 #define TERROR 12 #define TNOTIME 13 #define TINVALID 14 #define TLIBNOTINIT 15 #define TINVALIDPEFILE 16 #define TINVALIDPEENTRYPOINT 17 #define TINVALIDTAGGANTOFFSET 18 #define TINVALIDTAGGANT 19 #define TFILEACCESSDENIED 20 #define TENTRIESEXCEED 21 #define TINSUFFICIENTBUFFER 22 #endif /* COMMON_TYPES_HEADER */ <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ /* * Portions of this software include software developed by the OpenSSL Project for * use in the OpenSSL Toolkit (http://www.openssl.org/), and those portions * are governed by the OpenSSL Toolkit License. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/ts.h> #include "http.h" #include "callbacks.h" #include "url.h" #include "types.h" #include "timestamp.h" #include "timestamp_nonce.h" #include "ossl_ts_rsp_verify.h" #define NONCE_LENGTH 64 TS_REQ* get_timestamp_request(char* hash, int hash_size, ASN1_INTEGER *nonce_asn1) { int ret = 0; TS_REQ *ts_req = NULL; TS_MSG_IMPRINT *msg_imprint = NULL; X509_ALGOR *algo = NULL; unsigned char *data = NULL; ASN1_OBJECT *policy_obj = NULL; const EVP_MD* md = NULL; /* Setting default message digest. */ if ((md = EVP_get_digestbyname("sha256")) == NULL) { goto err; } /* Creating request object. */ if ((ts_req = TS_REQ_new()) == NULL) { goto err; } /* Setting version. */ if (!TS_REQ_set_version(ts_req, 1)) goto err; /* Creating and adding MSG_IMPRINT object. */ if ((msg_imprint = TS_MSG_IMPRINT_new()) == NULL) { goto err; } /* Adding algorithm. */ if ((algo = X509_ALGOR_new()) == NULL) { goto err; } if ((algo->algorithm = OBJ_nid2obj(EVP_MD_type(md))) == NULL) { goto err; } if ((algo->parameter = ASN1_TYPE_new()) == NULL) { goto err; } algo->parameter->type = V_ASN1_NULL; if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo)) goto err; /* Adding message digest. */ if (!TS_MSG_IMPRINT_set_msg(msg_imprint, (unsigned char*)hash, hash_size)) goto err; if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint)) goto err; /* Setting policy if requested. */ if ((policy_obj = OBJ_txt2obj("1.1.3", 0)) == NULL) { goto err; } if (policy_obj && !TS_REQ_set_policy_id(ts_req, policy_obj)) goto err; /* Setting nonce if requested. */ if (nonce_asn1 && !TS_REQ_set_nonce(ts_req, nonce_asn1)) goto err; /* Setting certificate request flag if requested. */ if (!TS_REQ_set_cert_req(ts_req, 1)) goto err; ret = 1; err: if (!ret) { TS_REQ_free(ts_req); ts_req = NULL; } TS_MSG_IMPRINT_free(msg_imprint); X509_ALGOR_free(algo); OPENSSL_free(data); ASN1_OBJECT_free(policy_obj); return ts_req; } #ifdef SPV_LIBRARY UNSIGNED32 get_timestamp_response(const char* urlStr, char* hash, UNSIGNED32 hash_size, UNSIGNED32 httpTimeOut, TS_RESP** tsResponse) { UNSIGNED32 result = TINTERNALERROR; BIO* responseBio = NULL; Url* url = NULL; TS_REQ* tsRequest = NULL; BIO* requestBio = NULL; int requestHeaderLength; int requestLength; int requestContentLength; char requestHeader[2048 + 256]; char* request = NULL; void* contentBuffer = NULL; void* resultBuffer = NULL; int resultLength; TS_MSG_IMPRINT* msgImprint = NULL; ASN1_OCTET_STRING* hashedMessage = NULL; int hashedMessageLength; int httpResult; char *urlBuffer = NULL; int redirection = 0; /* Check if TS url is specified */ if (!urlStr) { goto end; } /* Get Request for timestamp */ tsRequest = get_timestamp_request(hash, hash_size, create_nonce(NONCE_LENGTH)); msgImprint = TS_REQ_get_msg_imprint(tsRequest); hashedMessage = TS_MSG_IMPRINT_get_msg(msgImprint); hashedMessageLength = ASN1_STRING_length((ASN1_STRING*)hashedMessage); if ((int)hash_size != hashedMessageLength) { goto end; } requestBio = BIO_new(BIO_s_mem()); if (requestBio == NULL) { goto end; } if (!i2d_TS_REQ_bio(requestBio, tsRequest)) { goto end; } contentBuffer = memory_alloc(BIO_number_written(requestBio)); if (contentBuffer == NULL) { goto end; } requestContentLength = BIO_read(requestBio, contentBuffer, BIO_number_written(requestBio)); /* Allocate memory buffer for timestamp server url */ urlBuffer = memory_alloc(strlen(urlStr) + 1); if (!urlBuffer) { goto end; } /* Copy TS url to allocated buffer */ strcpy(urlBuffer, urlStr); http_redirect: /* Parse and check URL */ url = parse_url(urlBuffer); if (url == NULL) { goto end; } if (strcmp(url->Scheme, "http") != 0) { goto end; } requestHeaderLength = sprintf(requestHeader, "POST %s HTTP/1.0\r\nHOST: %s\r\nPragma: no-cache\r\nContent-Type: application/timestamp-query\r\nAccept: application/timestamp-reply\r\nContent-Length: %d\r\n\r\n", urlBuffer, url->Host, requestContentLength); requestLength = requestHeaderLength + requestContentLength; request = (char*)memory_alloc(requestLength); if (request == NULL) { goto end; } memcpy(request, requestHeader, requestHeaderLength); memcpy(request + requestHeaderLength, contentBuffer, requestContentLength); httpResult = http_read(url->Host, request, requestLength, url->Port, httpTimeOut, 1, &resultBuffer, &resultLength); if (httpResult == HTTP_REDIRECTION && (resultBuffer) && !redirection) { free_url(url); url = NULL; memory_free(request); request = NULL; /* Allocated buffer for redirected url */ urlBuffer = memory_realloc(urlBuffer, resultLength); if (!urlBuffer) { goto end; } memcpy(urlBuffer, resultBuffer, resultLength); memory_free(resultBuffer); resultBuffer = NULL; redirection++; goto http_redirect; } else if ((httpResult == HTTP_NOERROR) && (resultBuffer)) { responseBio = BIO_new(BIO_s_mem()); if (responseBio == NULL) { goto end; } BIO_write(responseBio, resultBuffer, resultLength); *tsResponse = d2i_TS_RESP_bio(responseBio, NULL); if (*tsResponse == NULL) { goto end; } result = TNOERR; } else { switch (httpResult) { case HTTP_NOLIVEINTERNET_ERROR: result = TNONET; break; case HTTP_TIMEOUT_ERROR: result = TTIMEOUT; break; case HTTP_RESPONSESTATUS_ERROR: result = TSERVERERROR; break; default: result = TINTERNALERROR; break; } } end: free_url(url); if (tsRequest != NULL) { TS_REQ_free(tsRequest); } if (requestBio != NULL) { BIO_free_all(requestBio); } if (responseBio != NULL) { BIO_free_all(responseBio); } if (request != NULL) { memory_free(request); } if (contentBuffer != NULL) { memory_free(contentBuffer); } if (resultBuffer != NULL) { memory_free(resultBuffer); } if (urlBuffer != NULL) { memory_free(urlBuffer); } return result; } #endif int check_time_stamp(TS_RESP* tsResponse, X509* caCert, char* hash, UNSIGNED32 hash_size) { int result = 0; TS_REQ* tsRequest = NULL; TS_VERIFY_CTX* ctx = NULL; TS_MSG_IMPRINT* msgImprint = NULL; ASN1_OCTET_STRING* hashedMessage = NULL; int hashedMessageLength; tsRequest = get_timestamp_request(hash, hash_size, tsResponse->tst_info->nonce); msgImprint = TS_REQ_get_msg_imprint(tsRequest); hashedMessage = TS_MSG_IMPRINT_get_msg(msgImprint); hashedMessageLength = ASN1_STRING_length((ASN1_STRING*)hashedMessage); if (hashedMessageLength != (int)hash_size) { goto end; } if (!(ctx = TS_REQ_to_TS_VERIFY_CTX(tsRequest, NULL))) { goto end; } ctx->flags |= TS_VFY_SIGNATURE; ctx->store = X509_STORE_new(); X509_STORE_add_cert(ctx->store, caCert); if (ossl_TS_RESP_verify_response(ctx, tsResponse)) { result = 1; } end: if (tsRequest != NULL) { TS_REQ_free(tsRequest); } if (ctx != NULL) { TS_VERIFY_CTX_free(ctx); } return result; } UNSIGNED64 time_as_unsigned64(int year, int month, int day, int hour, int minute, int second) { UNSIGNED64 days = ((year - 1970) * (365 + 365 + 366 + 365) + 1) / 4 + day - 1; switch (month) { case 2: days += 31; break; case 3: days += 31 + 28; break; case 4: days += 31 + 28 + 31; break; case 5: days += 31 + 28 + 31 + 30; break; case 6: days += 31 + 28 + 31 + 30 + 31; break; case 7: days += 31 + 28 + 31 + 30 + 31 + 30; break; case 8: days += 31 + 28 + 31 + 30 + 31 + 30 + 31; break; case 9: days += 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31; break; case 10: days += 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30; break; case 11: days += 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31; break; case 12: days += 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30; break; } if ((month >= 3) && (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))) { days++; } return (days * 24 * 3600) + (hour * 3600) + (minute * 60) + second; } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include "global.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "js.h" #include "txt.h" #include "types.h" #include "winpe.h" #include "winpe2.h" #include "taggant.h" #include "taggant2.h" #include "callbacks.h" #include "endianness.h" #include "miscellaneous.h" #include "taggant_types.h" #include "verify_helper.h" #include "timestamp.h" #include <openssl/pem.h> #define umaxof(t) (((0x1ULL << ((sizeof(t) * 8ULL) - 1ULL)) - 1ULL) | \ (0xFULL << ((sizeof(t) * 8ULL) - 4ULL))) UNSIGNED32 taggant2_get_extrainfo(PEXTRABLOB2 pExtrablob, ENUMTAGINFO eKey, UNSIGNED32 *pSize, PINFO pInfo) { UNSIGNED32 res = TNOTFOUND; UNSIGNED16 vsize, vtype; char *buf; UNSIGNED16 size; int found; if ((UNSIGNED16)eKey >= 0x8000) { found = 0; /* find this key in existing structure */ if (pExtrablob->Data && pExtrablob->Length) { buf = pExtrablob->Data; size = pExtrablob->Length; while (size) { /* get type */ vtype = *(UNSIGNED16*)buf; if (IS_BIG_ENDIAN) { vtype = UNSIGNED16_to_big_endian((char*)&vtype); } buf += sizeof(UNSIGNED16); /* get size */ vsize = *(UNSIGNED16*)buf; if (IS_BIG_ENDIAN) { vsize = UNSIGNED16_to_big_endian((char*)&vsize); } buf += sizeof(UNSIGNED16); if (vtype == eKey) { found = 1; /* get the content */ if (*pSize >= vsize && pInfo != NULL) { memcpy(pInfo, buf, vsize); /* succeeded */ res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = vsize; break; } buf += vsize; /* decrease the size */ size -= sizeof(UNSIGNED16) + sizeof(UNSIGNED16) + vsize; } } if (!found) { *pSize = 0; } } else { res = TERRORKEY; } return res; } UNSIGNED32 taggant2_put_extrainfo(PEXTRABLOB2 pExtrablob, ENUMTAGINFO eKey, UNSIGNED32 uSize, PINFO pInfo) { UNSIGNED32 res = TNOERR; char *buf, *bufsrc, *bufdest; UNSIGNED16 sizesrc, tmpu16; UNSIGNED16 vsize = 0, vtype; UNSIGNED32 size; int found; if ((UNSIGNED16)eKey >= 0x8000) { size = (UNSIGNED32)pExtrablob->Length; found = 0; /* find this key in existing structure */ if (pExtrablob->Data && pExtrablob->Length) { bufsrc = pExtrablob->Data; sizesrc = pExtrablob->Length; while (sizesrc) { /* get type */ vtype = *(UNSIGNED16*)bufsrc; if (IS_BIG_ENDIAN) { vtype = UNSIGNED16_to_big_endian((char*)&vtype); } bufsrc += sizeof(UNSIGNED16); /* get size */ vsize = *(UNSIGNED16*)bufsrc; if (IS_BIG_ENDIAN) { vsize = UNSIGNED16_to_big_endian((char*)&vsize); } if (vtype == eKey) { found = 1; break; } bufsrc += sizeof(UNSIGNED16) + vsize; /* decrease the size */ sizesrc -= sizeof(UNSIGNED16) + sizeof(UNSIGNED16) + vsize; } } if (found) { if (uSize) { /* set the new item size and buffer */ size += uSize - vsize; if (size <= umaxof(UNSIGNED16)) { buf = memory_alloc(size); if (buf) { bufsrc = pExtrablob->Data; bufdest = buf; sizesrc = pExtrablob->Length; while (sizesrc) { /* copy type */ vtype = *(UNSIGNED16*)bufsrc; if (IS_BIG_ENDIAN) { vtype = UNSIGNED16_to_big_endian((char*)&vtype); } memcpy(bufdest, bufsrc, sizeof(UNSIGNED16)); bufsrc += sizeof(UNSIGNED16); bufdest += sizeof(UNSIGNED16); /* set size */ vsize = *(UNSIGNED16*)bufsrc; if (IS_BIG_ENDIAN) { vsize = UNSIGNED16_to_big_endian((char*)&vsize); } if (vtype == eKey) { tmpu16 = (UNSIGNED16)uSize; if (IS_BIG_ENDIAN) { UNSIGNED16_to_little_endian(tmpu16, (char*)&tmpu16); } memcpy(bufdest, &tmpu16, sizeof(UNSIGNED16)); } else { memcpy(bufdest, bufsrc, sizeof(UNSIGNED16)); } bufsrc += sizeof(UNSIGNED16); bufdest += sizeof(UNSIGNED16); /* copy the buffer */ if (vtype == eKey) { memcpy(bufdest, pInfo, uSize); bufdest += uSize; } else { memcpy(bufdest, bufsrc, vsize); bufdest += vsize; } bufsrc += vsize; /* decrease the size */ sizesrc -= sizeof(UNSIGNED16) + sizeof(UNSIGNED16) + vsize; } /* deallocate old buffer */ if (pExtrablob->Data) { memory_free(pExtrablob->Data); } pExtrablob->Data = buf; pExtrablob->Length = (UNSIGNED16)size; } else { res = TMEMORY; } } else { res = TINSUFFICIENTBUFFER; } } else { /* eliminate the item */ size -= sizeof(UNSIGNED16) + sizeof(UNSIGNED16) + vsize; if (size <= umaxof(UNSIGNED16)) { buf = memory_alloc(size); if (buf) { bufsrc = pExtrablob->Data; bufdest = buf; sizesrc = pExtrablob->Length; while (sizesrc) { /* copy type */ vtype = *(UNSIGNED16*)bufsrc; if (IS_BIG_ENDIAN) { vtype = UNSIGNED16_to_big_endian((char*)&vtype); } if (vtype == eKey) { bufsrc += sizeof(UNSIGNED16); /* get size */ vsize = *(UNSIGNED16*)bufsrc; if (IS_BIG_ENDIAN) { vsize = UNSIGNED16_to_big_endian((char*)&vsize); } bufsrc += sizeof(UNSIGNED16); /* get content */ bufsrc += vsize; } else { memcpy(bufdest, bufsrc, sizeof(UNSIGNED16)); bufsrc += sizeof(UNSIGNED16); bufdest += sizeof(UNSIGNED16); /* get size */ vsize = *(UNSIGNED16*)bufsrc; if (IS_BIG_ENDIAN) { vsize = UNSIGNED16_to_big_endian((char*)&vsize); } memcpy(bufdest, bufsrc, sizeof(UNSIGNED16)); bufsrc += sizeof(UNSIGNED16); bufdest += sizeof(UNSIGNED16); /* copy the buffer */ memcpy(bufdest, bufsrc, vsize); bufsrc += vsize; bufdest += vsize; } /* decrease the size */ sizesrc -= sizeof(UNSIGNED16) + sizeof(UNSIGNED16) + vsize; } /* deallocate old buffer */ if (pExtrablob->Data) { memory_free(pExtrablob->Data); } pExtrablob->Data = buf; pExtrablob->Length = (UNSIGNED16)size; } else { res = TMEMORY; } } else { res = TINSUFFICIENTBUFFER; } } } else { if (uSize) { /* add the new item */ size += sizeof(UNSIGNED16) + sizeof(UNSIGNED16) + uSize; if (size <= umaxof(UNSIGNED16)) { buf = memory_alloc(size); if (buf) { bufdest = buf; if (pExtrablob->Data && pExtrablob->Length) { /* copy original buffer */ memcpy(bufdest, pExtrablob->Data, pExtrablob->Length); bufdest += pExtrablob->Length; } /* set type */ vtype = eKey; tmpu16 = vtype; if (IS_BIG_ENDIAN) { UNSIGNED16_to_little_endian(tmpu16, (char*)&tmpu16); } memcpy(bufdest, &tmpu16, sizeof(UNSIGNED16)); bufdest += sizeof(UNSIGNED16); /* set size */ vsize = (UNSIGNED16)uSize; tmpu16 = vsize; if (IS_BIG_ENDIAN) { UNSIGNED16_to_little_endian(tmpu16, (char*)&tmpu16); } memcpy(bufdest, &tmpu16, sizeof(UNSIGNED16)); bufdest += sizeof(UNSIGNED16); /* set buffer */ memcpy(bufdest, pInfo, vsize); /* deallocate old buffer */ if (pExtrablob->Data) { memory_free(pExtrablob->Data); } pExtrablob->Data = buf; pExtrablob->Length = (UNSIGNED16)size; } else { res = TMEMORY; } } else { res = TINSUFFICIENTBUFFER; } } } } else { res = TERRORKEY; } return res; } void taggant2_free_taggant(PTAGGANT2 pTaggant) { /* Make sure taggant object is not null */ if (pTaggant) { if (pTaggant->CMSBuffer) { memory_free(pTaggant->CMSBuffer); } memory_free(pTaggant); } } UNSIGNED16 taggant2_taggantblob2_size(PTAGGANTBLOB2 pTagBlob) { return sizeof(TAGGANTBLOB_HEADER) + sizeof(HASHBLOB) + sizeof(UNSIGNED16) + pTagBlob->Extrablob.Length + pTagBlob->Hash.Hashmap.Entries * sizeof(HASHBLOB_HASHMAP_DOUBLE); } UNSIGNED32 taggant2_read_textual(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED64 offset, PTAGGANT2* pTaggant, TAGGANTCONTAINER filetype, char *beginmarker, int beginmarkersize, char *endmarker, int endmarkersize) { UNSIGNED32 res = TNOERR; PTAGGANT2 tagbuf = NULL; UNSIGNED32 taghdrsize, cmssize, tagftrsize; char *bmarker = NULL; char *emarker = NULL; if (beginmarkersize) { bmarker = memory_alloc(beginmarkersize); if (!bmarker) { res = TMEMORY; } } if (res == TNOERR) { if (endmarkersize) { emarker = memory_alloc(endmarkersize); if (!emarker) { res = TMEMORY; } } } if (res == TNOERR) { /* allocate memory for taggant */ tagbuf = memory_alloc(sizeof(TAGGANT2)); if (tagbuf) { memset(tagbuf, 0, sizeof(TAGGANT2)); /* remember the taggant type */ tagbuf->tagganttype = filetype; /* read and check the end marker */ if (endmarkersize) { offset -= endmarkersize; if (file_seek(pCtx, fp, offset, SEEK_SET)) { /* read comment's end marker */ if (file_read_buffer(pCtx, fp, emarker, endmarkersize)) { if (strncmp(emarker, endmarker, endmarkersize) != 0) { res = TNOTAGGANTS; } } else { res = TFILEACCESSDENIED; } } else { res = TFILEACCESSDENIED; } } if (res == TNOERR) { /* read taggant header and return it's size in js file */ if ((res = txt_read_taggant_header2(pCtx, fp, offset, &tagbuf->Header, &taghdrsize)) == TNOERR) { if (tagbuf->Header.Version == TAGGANT_VERSION2 && tagbuf->Header.MarkerBegin == TAGGANT_MARKER_BEGIN && tagbuf->Header.CMSLength) { offset -= taghdrsize; if ((res = txt_read_taggant_cms(pCtx, fp, offset, tagbuf->Header.CMSLength, &tagbuf->CMSBuffer, &cmssize)) == TNOERR) { /* read taggant footer and return it's size in js file */ offset -= tagbuf->Header.CMSLength; if ((res = txt_read_taggant_footer2(pCtx, fp, offset, &tagbuf->Footer, &tagftrsize)) == TNOERR) { if (tagbuf->Footer.MarkerEnd == TAGGANT_MARKER_END) { tagbuf->CMSBufferSize = cmssize; offset -= tagftrsize; if (beginmarkersize) { offset -= beginmarkersize; if (file_seek(pCtx, fp, offset, SEEK_SET)) { /* read and check end marker */ if (file_read_buffer(pCtx, fp, bmarker, beginmarkersize)) { if (strncmp(bmarker, beginmarker, beginmarkersize) != 0) { res = TNOTAGGANTS; } } else { res = TFILEACCESSDENIED; } } else { res = TFILEACCESSDENIED; } } if (res == TNOERR) { if (tagbuf->Header.TaggantLength == taghdrsize + tagbuf->Header.CMSLength + tagftrsize) { *pTaggant = tagbuf; res = TNOERR; } else { res = TNOTAGGANTS; } } } else { res = TNOTAGGANTS; } } } } else { res = TNOTAGGANTS; } } } if (res != TNOERR) { taggant2_free_taggant(tagbuf); } } else { res = TMEMORY; } } if (bmarker) { memory_free(bmarker); } if (emarker) { memory_free(emarker); } return res; } UNSIGNED32 taggant2_read_binary(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED64 offset, PTAGGANT2* pTaggant, TAGGANTCONTAINER filetype) { UNSIGNED32 res = TNOTAGGANTS; PTAGGANT2 tagbuf = NULL; /* seek to the specified offset */ offset -= sizeof(TAGGANT_HEADER2); if (file_seek(pCtx, fp, offset, SEEK_SET)) { /* allocate memory for taggant */ tagbuf = memory_alloc(sizeof(TAGGANT2)); if (tagbuf) { memset(tagbuf, 0, sizeof(TAGGANT2)); /* remember the taggant type */ tagbuf->tagganttype = filetype; /* read taggant header */ if (file_read_buffer(pCtx, fp, &tagbuf->Header, sizeof(TAGGANT_HEADER2))) { if (IS_BIG_ENDIAN) { TAGGANT_HEADER2_to_big_endian(&tagbuf->Header, &tagbuf->Header); } if (tagbuf->Header.Version == TAGGANT_VERSION2 && tagbuf->Header.MarkerBegin == TAGGANT_MARKER_BEGIN && tagbuf->Header.CMSLength) { /* allocate buffer for CMS */ tagbuf->CMSBuffer = memory_alloc(tagbuf->Header.CMSLength); if (tagbuf->CMSBuffer) { memset(tagbuf->CMSBuffer, 0, tagbuf->Header.CMSLength); tagbuf->CMSBufferSize = tagbuf->Header.CMSLength; /* seek to the CMS offset */ offset -= tagbuf->Header.CMSLength; if (file_seek(pCtx, fp, offset, SEEK_SET)) { /* read CMS */ if (file_read_buffer(pCtx, fp, tagbuf->CMSBuffer, tagbuf->Header.CMSLength)) { offset -= sizeof(UNSIGNED32); if (file_seek(pCtx, fp, offset, SEEK_SET)) { /* read end marker */ if (file_read_UNSIGNED32(pCtx, fp, &tagbuf->Footer.MarkerEnd)) { if (IS_BIG_ENDIAN) { UNSIGNED32_to_big_endian((char*)&tagbuf->Footer.MarkerEnd); } /* check end marker */ if (tagbuf->Footer.MarkerEnd == TAGGANT_MARKER_END) { /* make sure there is no appended data in cms */ if (tagbuf->Header.TaggantLength == sizeof(TAGGANT_HEADER2) + tagbuf->Header.CMSLength + /* TAGGANT_FOOTER2 length */ sizeof(UNSIGNED32)) { *pTaggant = tagbuf; res = TNOERR; } else { res = TNOTAGGANTS; } } else { res = TNOTAGGANTS; } } else { res = TFILEACCESSDENIED; } } else { res = TFILEACCESSDENIED; } } else { res = TFILEACCESSDENIED; } } else { res = TFILEACCESSDENIED; } } else { res = TMEMORY; } } else { res = TNOTAGGANTS; } } else { res = TFILEACCESSDENIED; } if (res != TNOERR) { taggant2_free_taggant(tagbuf); } } else { res = TMEMORY; } } else { res = TFILEACCESSDENIED; } return res; } UNSIGNED32 taggant2_compute_default_hash_pe(EVP_MD_CTX *evp, PTAGGANTCONTEXT pCtx, PHASHBLOB_DEFAULT pDefaultHash, PFILEOBJECT hFile, PE_ALL_HEADERS *peh, UNSIGNED64 uObjectEnd) { UNSIGNED32 res = TINVALIDPEFILE; /* for the default hash there are HASHMAP2_MAX_LENGTH number of regions is needed * Full File Hash contains from a hash of two regions: * - from file start to end of PE file (default hash) * - from end of PE file to end of physical file (extended hash) * * For the first region we have to exclude from the hashing: * - Checksum from optinal header * - Digital Signature header from optinal header */ HASHBLOB_HASHMAP_DOUBLE regions[HASHMAP2_MAX_LENGTH]; EVP_MD_CTX evp_ext; char* buf = NULL; int i, len; /* Calculate default hash */ memset(&regions, 0, sizeof(regions)); /* set the entire file region from file start to file end by default */ regions[0].AbsoluteOffset = 0; regions[0].Length = uObjectEnd; /* exclude Checksum from region */ len = exclude_region_from_hashmap(&regions[0], peh->dh.e_lfanew + sizeof(peh->signature) + sizeof(peh->fh) + 64, sizeof(UNSIGNED32)); /* exclude PE Header Digital Signature */ if (winpe_is_pe64(peh)) { len = exclude_region_from_hashmap(&regions[0], peh->dh.e_lfanew + sizeof(peh->signature) + sizeof(peh->fh) + 144, sizeof(TAG_IMAGE_DATA_DIRECTORY)); } else { len = exclude_region_from_hashmap(&regions[0], peh->dh.e_lfanew + sizeof(peh->signature) + sizeof(peh->fh) + 128, sizeof(TAG_IMAGE_DATA_DIRECTORY)); } /* allocate buffer for file reading */ buf = (char*)memory_alloc(HASH_READ_BLOCK); if (!buf) { return TMEMORY; } for (i = 0; i < len; i++) { if ((res = compute_region_hash(pCtx, hFile, evp, &regions[i], buf)) != TNOERR) { break; } } if (res == TNOERR) { memset(pDefaultHash, 0, sizeof(HASHBLOB_DEFAULT)); pDefaultHash->Header.Type = TAGGANT_HASBLOB_DEFAULT; pDefaultHash->Header.Length = sizeof(HASHBLOB_DEFAULT); pDefaultHash->Header.Version = HASHBLOB_VERSION2; /* Copy context before destroying it by calling EVP_DigestFinal_ex */ EVP_MD_CTX_copy(&evp_ext, evp); /* Get default file hash */ EVP_DigestFinal_ex(&evp_ext, pDefaultHash->Header.Hash, NULL); /* Clean extended hashing context */ EVP_MD_CTX_cleanup(&evp_ext); } memory_free(buf); return res; } UNSIGNED32 taggant2_compute_extended_hash_pe(EVP_MD_CTX *evp, PTAGGANTCONTEXT pCtx, PHASHBLOB_EXTENDED pExtendedHash, PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd) { UNSIGNED32 res = TNOERR; HASHBLOB_HASHMAP_DOUBLE region; EVP_MD_CTX evp_ext; char* buf = NULL; /* Calculate extended hash */ memset(pExtendedHash, 0, sizeof(HASHBLOB_EXTENDED)); pExtendedHash->Header.Type = TAGGANT_HASBLOB_EXTENDED; pExtendedHash->Header.Length = sizeof(HASHBLOB_EXTENDED); pExtendedHash->Header.Version = HASHBLOB_VERSION2; /* remember the file end offset */ pExtendedHash->PhysicalEnd = uFileEnd; memset(&region, 0, sizeof(region)); /* set the initial region for extended file hash from end of PE file to end of physical file */ region.AbsoluteOffset = uObjectEnd; region.Length = uFileEnd - uObjectEnd; if (region.Length != 0) { /* allocate buffer for file reading */ buf = (char*)memory_alloc(HASH_READ_BLOCK); if (buf) { if ((res = compute_region_hash(pCtx, hFile, evp, &region, buf)) == TNOERR) { /* Copy context before destroying it by calling EVP_DigestFinal_ex */ EVP_MD_CTX_copy(&evp_ext, evp); /* Get default file hash */ EVP_DigestFinal_ex(&evp_ext, pExtendedHash->Header.Hash, NULL); /* Clean extended hashing context */ EVP_MD_CTX_cleanup(&evp_ext); } memory_free(buf); } else { res = TMEMORY; } } return res; } UNSIGNED32 taggant2_to_binary(BIO* cmsBio, BIO* outBio) { int inlen; UNSIGNED32 cmslength = 0; TAGGANT_FOOTER2 tagftr, tmptagftr; TAGGANT_HEADER2 taghdr; char inbuf[512]; /* fill out taggant footer */ memset(&tagftr, 0, sizeof(tagftr)); tagftr.MarkerEnd = TAGGANT_MARKER_END; /* copy data to temporary buffer to convert it to little endian if necessary */ tmptagftr = tagftr; if (IS_BIG_ENDIAN) { TAGGANT_FOOTER2_to_little_endian(&tmptagftr, &tmptagftr); } BIO_write(outBio, &tmptagftr.MarkerEnd, sizeof(UNSIGNED32)); /* Fill out taggant CMS */ while ((inlen = BIO_read(cmsBio, inbuf, 512)) > 0) { BIO_write(outBio, inbuf, inlen); cmslength += inlen; } /* Fill out taggant header */ taghdr.Version = TAGGANT_VERSION2; taghdr.CMSLength = cmslength; taghdr.TaggantLength = sizeof(TAGGANT_HEADER2) + cmslength + /* sizeof(TAGGANT_FOOTER2) */ sizeof(UNSIGNED32) /* sizeof(EndMarker) */; taghdr.MarkerBegin = TAGGANT_MARKER_BEGIN; if (IS_BIG_ENDIAN) { TAGGANT_HEADER2_to_little_endian(&taghdr, &taghdr); } BIO_write(outBio, &taghdr, sizeof(TAGGANT_HEADER2)); return TNOERR; } UNSIGNED32 taggant2_to_textual(BIO* cmsBio, BIO* outBio) { UNSIGNED32 cmslength, ftrlength; UNSIGNED32 res = TMEMORY; TAGGANT_FOOTER2 tagftr; TAGGANT_HEADER2 taghdr; /* fill out taggant footer */ memset(&tagftr, 0, sizeof(TAGGANT_FOOTER2)); tagftr.MarkerEnd = TAGGANT_MARKER_END; if (txt_write_taggant_footer2(&tagftr, outBio, &ftrlength)) { if ((cmslength = txt_bio_base64_encode(cmsBio, outBio)) > 0) { /* fill out taggant header */ memset(&taghdr, 0, sizeof(TAGGANT_HEADER2)); taghdr.Version = TAGGANT_VERSION2; taghdr.CMSLength = cmslength; taghdr.TaggantLength = ftrlength + cmslength + txt_taggant_header2_size(); taghdr.MarkerBegin = TAGGANT_MARKER_BEGIN; if (txt_write_taggant_header2(&taghdr, outBio)) { res = TNOERR; } } } return res; } int taggant2_write_taggantblob2(BIO *inbio, PTAGGANTBLOB2 tagblob) { TAGGANTBLOB_HEADER tmphdr; HASHBLOB tmpblob; UNSIGNED16 tmpu16; HASHBLOB_HASHMAP_DOUBLE tmpdbl; PHASHBLOB_HASHMAP_DOUBLE tmphm; int i; tagblob->Hash.Hashmap.DoublesOffset = sizeof(TAGGANTBLOB_HEADER) + sizeof(HASHBLOB) + sizeof(UNSIGNED16) + tagblob->Extrablob.Length; /* Write tagblob->Header */ tmphdr = tagblob->Header; if (IS_BIG_ENDIAN) { TAGGANTBLOB_HEADER_to_little_endian(&tmphdr, &tmphdr); } BIO_write(inbio, &tmphdr, sizeof(TAGGANTBLOB_HEADER)); /* Write tagblob->Hash */ tmpblob = tagblob->Hash; if (IS_BIG_ENDIAN) { HASHBLOB_to_little_endian(&tmpblob, &tmpblob); } BIO_write(inbio, &tmpblob, sizeof(HASHBLOB)); /* Write tagblob->Extrablob.Length */ tmpu16 = tagblob->Extrablob.Length; if (IS_BIG_ENDIAN) { UNSIGNED16_to_little_endian(tmpu16, (char*)&tmpu16); } BIO_write(inbio, &tmpu16, sizeof(UNSIGNED16)); if (tagblob->Extrablob.Length) { BIO_write(inbio, tagblob->Extrablob.Data, tagblob->Extrablob.Length); } /* Write tagblob->pHashMapDoubles */ tmphm = tagblob->pHashMapDoubles; for (i = 0; i < tagblob->Hash.Hashmap.Entries; i++) { tmpdbl = *tmphm; if (IS_BIG_ENDIAN) { HASHBLOB_HASHMAP_DOUBLE_to_little_endian(&tmpdbl, &tmpdbl); } BIO_write(inbio, &tmpdbl, sizeof(HASHBLOB_HASHMAP_DOUBLE)); tmphm++; } return 1; } #ifdef SPV_LIBRARY UNSIGNED32 taggant2_prepare(PTAGGANTOBJ2 pTaggantObj, const PVOID pLicense, TAGGANTCONTAINER TaggantType, PVOID pTaggantOut, UNSIGNED32 *uTaggantReservedSize) { UNSIGNED32 res = TBADKEY; BIO* licbio = NULL; X509* liccert = NULL, * licspv = NULL; EVP_PKEY* lickey = NULL; BIO* inbio = NULL, *outbio = NULL; BIO* cmsbio = NULL; STACK_OF(X509) *intermediate = NULL; int maxlen; UNSIGNED32 biolen; /* Load user license certificate and private key */ licbio = BIO_new(BIO_s_mem()); if (licbio) { BIO_write(licbio, pLicense, (int)strlen((const char*)pLicense)); licspv = PEM_read_bio_X509(licbio, NULL, 0, NULL); if (licspv) { liccert = PEM_read_bio_X509(licbio, NULL, 0, NULL); if (liccert) { lickey = PEM_read_bio_PrivateKey(licbio, NULL, 0, NULL); if (lickey) { inbio = BIO_new(BIO_s_mem()); if (inbio) { /* Set the length of the taggantblob2 */ pTaggantObj->tagBlob.Header.Length = taggant2_taggantblob2_size(&pTaggantObj->tagBlob); /* Write taggantblob2 */ if (taggant2_write_taggantblob2(inbio, &pTaggantObj->tagBlob)) { /* Push TSA response to the CMS signed data */ i2d_TS_RESP_bio(inbio, pTaggantObj->TSResponse); /* Create store with intermediate certificate(s) */ intermediate = sk_X509_new_null(); if (intermediate) { if (sk_X509_push(intermediate, licspv)) { /* Sign CMS */ pTaggantObj->CMS = CMS_sign(liccert, lickey, intermediate, inbio, CMS_BINARY); if (pTaggantObj->CMS) { cmsbio = BIO_new(BIO_s_mem()); if (cmsbio) { if (i2d_CMS_bio(cmsbio, pTaggantObj->CMS)) { outbio = BIO_new(BIO_s_mem()); if (outbio) { switch (TaggantType) { case TAGGANT_PEFILE: case TAGGANT_BINFILE: { res = taggant2_to_binary(cmsbio, outbio); break; } case TAGGANT_JSFILE: { /* write comment's begin marker */ BIO_write(outbio, JS_COMMENT_BEGIN, (int)strlen(JS_COMMENT_BEGIN)); res = taggant2_to_textual(cmsbio, outbio); /* write comment's end marker */ BIO_write(outbio, JS_COMMENT_END, (int)strlen(JS_COMMENT_END)); break; } case TAGGANT_TXTFILE: { res = taggant2_to_textual(cmsbio, outbio); break; } default: { res = TTYPE; break; } } if (res == TNOERR) { res = TERROR; /* Get bio size */ maxlen = MAX_INTEGER; biolen = (UNSIGNED32)BIO_read(outbio, NULL, maxlen); if (biolen) { if (*uTaggantReservedSize < biolen) { res = TINSUFFICIENTBUFFER; } else { /* read bio to buffer */ BIO_read(outbio, pTaggantOut, biolen); res = TNOERR; } *uTaggantReservedSize = biolen; } } BIO_free(outbio); } else { res = TMEMORY; } } BIO_free(cmsbio); } else { res = TMEMORY; } } } sk_X509_free(intermediate); } } BIO_free(inbio); } else { res = TMEMORY; } EVP_PKEY_free(lickey); } else { res = TBADKEY; } X509_free(liccert); } else { res = TBADKEY; } X509_free(licspv); } else { res = TBADKEY; } BIO_free(licbio); } else { res = TMEMORY; } if (res != TNOERR) { if (pTaggantObj->CMS) { CMS_ContentInfo_free(pTaggantObj->CMS); pTaggantObj->CMS = NULL; } } return res; } #endif UNSIGNED32 taggant2_compute_default_hash_raw(EVP_MD_CTX *pEvp, PTAGGANTCONTEXT pCtx, PHASHBLOB_DEFAULT pDefaultHash, PFILEOBJECT hFile, UNSIGNED64 uFileEnd) { UNSIGNED32 res = TFILEERROR; HASHBLOB_HASHMAP_DOUBLE region; EVP_MD_CTX evp_ext; char* buf = NULL; /* Calculate default hash */ region.AbsoluteOffset = 0; region.Length = uFileEnd; /* allocate buffer for file reading */ buf = (char*)memory_alloc(HASH_READ_BLOCK); if (!buf) { return TMEMORY; } res = compute_region_hash(pCtx, hFile, pEvp, &region, buf); if (res == TNOERR) { memset(pDefaultHash, 0, sizeof(HASHBLOB_DEFAULT)); pDefaultHash->Header.Type = TAGGANT_HASBLOB_DEFAULT; pDefaultHash->Header.Length = sizeof(HASHBLOB_DEFAULT); pDefaultHash->Header.Version = HASHBLOB_VERSION2; /* Copy context before destroying it by calling EVP_DigestFinal_ex */ EVP_MD_CTX_copy(&evp_ext, pEvp); /* Get default file hash */ EVP_DigestFinal_ex(&evp_ext, pDefaultHash->Header.Hash, NULL); /* Clean extended hashing context */ EVP_MD_CTX_cleanup (&evp_ext); } memory_free(buf); return res; } UNSIGNED32 taggant2_compute_extended_hash_raw(PHASHBLOB_EXTENDED pExtendedHash, UNSIGNED64 uFileEnd) { /* Calculate extended hash */ pExtendedHash->Header.Type = TAGGANT_HASBLOB_EXTENDED; pExtendedHash->Header.Length = sizeof(HASHBLOB_EXTENDED); pExtendedHash->Header.Version = HASHBLOB_VERSION2; /* remember the file end offset */ pExtendedHash->PhysicalEnd = uFileEnd; return TNOERR; } UNSIGNED32 taggant2_compute_hash_map(PTAGGANTCONTEXT pCtx, PFILEOBJECT hFile, PHASHBLOB_HASHMAP pHm, PHASHBLOB_HASHMAP_DOUBLE pHmDoubles) { UNSIGNED32 res = TFILEACCESSDENIED; EVP_MD_CTX evp; char* buf = NULL; int i; PHASHBLOB_HASHMAP_DOUBLE hmd; /* Compute hashes */ EVP_MD_CTX_init (&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* allocate buffer for file reading */ buf = (char*)memory_alloc(HASH_READ_BLOCK); if (buf) { /* compute hashmaps */ hmd = pHmDoubles; for (i = 0; i < pHm->Entries; i++) { if ((res = compute_region_hash(pCtx, hFile, &evp, hmd, buf)) != TNOERR) { break; } hmd++; } memory_free(buf); } else { res = TMEMORY; } if (res == TNOERR) { pHm->DoublesOffset = sizeof(TAGGANTBLOB); pHm->Header.Type = TAGGANT_HASBLOB_HASHMAP; pHm->Header.Length = sizeof(HASHBLOB_HASHMAP); pHm->Header.Version = HASHBLOB_VERSION2; EVP_DigestFinal_ex(&evp, pHm->Header.Hash, NULL); } EVP_MD_CTX_cleanup (&evp); return res; } UNSIGNED32 taggant2_compute_hash_raw(PTAGGANTCONTEXT pCtx, PHASHBLOB pHash, PFILEOBJECT hFile, UNSIGNED64 uFileEnd, PHASHBLOB_HASHMAP_DOUBLE pHmDoubles) { EVP_MD_CTX evp; UNSIGNED32 res = TNOERR; /* Compute hash */ EVP_MD_CTX_init(&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* Compute default hash */ if ((res = taggant2_compute_default_hash_raw(&evp, pCtx, &pHash->FullFile.DefaultHash, hFile, uFileEnd)) == TNOERR) { /* Compute extended hash */ if ((res = taggant2_compute_extended_hash_raw(&pHash->FullFile.ExtendedHash, uFileEnd)) == TNOERR) { if (pHash->Hashmap.Entries > 0) { /* Compute hashmap */ res = taggant2_compute_hash_map(pCtx, hFile, &pHash->Hashmap, pHmDoubles); } } } /* Clean hash context */ EVP_MD_CTX_cleanup(&evp); return res; } #ifdef SSV_LIBRARY int check_binary_cms(CMS_ContentInfo *cms, UNSIGNED32 size) { int res = 0; BIO *bio = NULL; int maxlen = MAX_INTEGER; bio = BIO_new(BIO_s_mem()); if (bio) { if (i2d_CMS_bio(bio, cms)) { /* Get bio size */ if ((UNSIGNED32)BIO_read(bio, NULL, maxlen) == size) { res = 1; } } BIO_free(bio); } return res; } int check_textual_cms(CMS_ContentInfo *cms, UNSIGNED32 size, UNSIGNED32 b64size) { int res = 0; BIO *bio = NULL, *bio64 = NULL; int maxlen = MAX_INTEGER; bio = BIO_new(BIO_s_mem()); if (bio) { if (i2d_CMS_bio(bio, cms)) { /* Get bio size */ if ((UNSIGNED32)BIO_read(bio, NULL, maxlen) == size) { bio64 = BIO_new(BIO_s_mem()); if (bio64) { if (txt_bio_base64_encode(bio, bio64) == b64size) { res = 1; } BIO_free(bio64); } } } BIO_free(bio); } return res; } UNSIGNED32 taggant2_read_taggantblob2(BIO *inbio, PTAGGANTBLOB2 tagblob) { UNSIGNED32 res = TERROR; PHASHBLOB_HASHMAP_DOUBLE tmphm; int i, err; memset(tagblob, 0, sizeof(TAGGANTBLOB2)); /* Read tagblob->Header */ if (BIO_read(inbio, &tagblob->Header, sizeof(TAGGANTBLOB_HEADER)) == sizeof(TAGGANTBLOB_HEADER)) { if (IS_BIG_ENDIAN) { TAGGANTBLOB_HEADER_to_big_endian(&tagblob->Header, &tagblob->Header); } /* Check if the taggantblob header version is correct */ if (tagblob->Header.Version == TAGGANTBLOB_VERSION2) { /* Read tagblob->Hash */ if (BIO_read(inbio, &tagblob->Hash, sizeof(HASHBLOB)) == sizeof(HASHBLOB)) { if (IS_BIG_ENDIAN) { HASHBLOB_to_big_endian(&tagblob->Hash, &tagblob->Hash); } /* Read tagblob->Extrablob.Length */ if (BIO_read(inbio, &tagblob->Extrablob.Length, sizeof(UNSIGNED16)) == sizeof(UNSIGNED16)) { if (IS_BIG_ENDIAN) { tagblob->Extrablob.Length = UNSIGNED16_to_big_endian((char*)&tagblob->Extrablob.Length); } /* Read tagblob->Extrablob */ err = 0; if (tagblob->Extrablob.Length) { err = 1; tagblob->Extrablob.Data = memory_alloc(tagblob->Extrablob.Length); if (tagblob->Extrablob.Data) { if (BIO_read(inbio, tagblob->Extrablob.Data, tagblob->Extrablob.Length) == tagblob->Extrablob.Length) { err = 0; } } else { res = TMEMORY; } } if (!err) { /* Read tagblob->pHashMapDoubles */ if (tagblob->Hash.Hashmap.Entries) { tagblob->pHashMapDoubles = memory_alloc(tagblob->Hash.Hashmap.Entries * sizeof(HASHBLOB_HASHMAP_DOUBLE)); if (tagblob->pHashMapDoubles) { tmphm = tagblob->pHashMapDoubles; for (i = 0; i < tagblob->Hash.Hashmap.Entries; i++) { if (BIO_read(inbio, tmphm, sizeof(HASHBLOB_HASHMAP_DOUBLE)) != sizeof(HASHBLOB_HASHMAP_DOUBLE)) { err = 1; break; } tmphm++; } } else { res = TMEMORY; err = 1; } } } if (!err) { /* Make sure taggant blob length is correct */ if (tagblob->Header.Length == taggant2_taggantblob2_size(tagblob)) { res = TNOERR; } } } } } } /* free memory that we allocated here in case of error */ if (res != TNOERR) { if (tagblob->Extrablob.Data) { memory_free(tagblob->Extrablob.Data); tagblob->Extrablob.Data = NULL; } tagblob->Extrablob.Length = 0; if (tagblob->pHashMapDoubles) { memory_free(tagblob->pHashMapDoubles); tagblob->pHashMapDoubles = NULL; } } return res; } UNSIGNED32 taggant2_validate_signature(PTAGGANTOBJ2 pTaggantObj, PTAGGANT2 pTaggant, PVOID pRootCert) { UNSIGNED32 res = TBADKEY; BIO *cmsbio = NULL; BIO *signedbio = NULL; BIO *tsbio = NULL; X509_STORE *trusted_store = NULL; X509_VERIFY_PARAM *vpm = NULL; int biolength = 0; int maxlen = MAX_INTEGER; char inbuf[512]; int inlen; X509* tmpcer; STACK_OF(X509) *cms_certs = NULL; EVP_PKEY *pkey; /* Load root certificate */ pTaggantObj->root = buffer_to_X509(pRootCert); if (pTaggantObj->root) { /* Compare taggant version */ if (pTaggant->Header.Version == TAGGANT_VERSION2 && pTaggant->Header.CMSLength > 0) { cmsbio = BIO_new(BIO_s_mem()); if (cmsbio) { BIO_write(cmsbio, pTaggant->CMSBuffer, pTaggant->CMSBufferSize); pTaggantObj->CMS = d2i_CMS_bio(cmsbio, NULL); if (pTaggantObj->CMS) { /* Check the CMS size, convert CMS to base64 and compare the length from the header for textual taggant */ if (((pTaggant->tagganttype == TAGGANT_PEFILE || pTaggant->tagganttype == TAGGANT_BINFILE) && check_binary_cms(pTaggantObj->CMS, pTaggant->Header.CMSLength)) || ((pTaggant->tagganttype == TAGGANT_JSFILE || pTaggant->tagganttype == TAGGANT_TXTFILE) && check_textual_cms(pTaggantObj->CMS, pTaggant->CMSBufferSize, pTaggant->Header.CMSLength))) { signedbio = BIO_new(BIO_s_mem()); if (signedbio) { /* Create a store with trusted certificates */ trusted_store = X509_STORE_new(); if (trusted_store) { /* Add root certificate to the trusted store */ if (X509_STORE_add_cert(trusted_store, pTaggantObj->root)) { vpm = X509_VERIFY_PARAM_new(); if (vpm) { /* We have to set the purpose to "any" to be used for signing certificate CMS_Verify expects that signer certificate has the purpose "smimeencrypt" but it does not. */ X509_VERIFY_PARAM_set_purpose(vpm, X509_PURPOSE_ANY); X509_STORE_set1_param(trusted_store, vpm); /* Set the custom cb function to suppress certificate time errors */ X509_STORE_set_verify_cb(trusted_store, verify_cms_cb); if (CMS_verify(pTaggantObj->CMS, NULL, trusted_store, NULL, signedbio, CMS_BINARY)) { /* Make sure there are 2 certificate in CMS */ cms_certs = CMS_get1_certs(pTaggantObj->CMS); if (cms_certs) { if (sk_X509_num(cms_certs) == CERTIFICATES_IN_TAGGANT_CHAIN) { /* Set the spv and user certificates, check first certificate against second one */ pTaggantObj->spv = X509_dup(sk_X509_value(cms_certs, 0)); pTaggantObj->user = X509_dup(sk_X509_value(cms_certs, 1)); pkey = X509_get_pubkey(pTaggantObj->spv); if (pkey) { if (!X509_verify(pTaggantObj->user, pkey)) { tmpcer = pTaggantObj->user; pTaggantObj->user = pTaggantObj->spv; pTaggantObj->spv = tmpcer; } EVP_PKEY_free(pkey); } /* CMS is OK, next try to read a timestamp */ if ((res = taggant2_read_taggantblob2(signedbio, &pTaggantObj->tagBlob)) == TNOERR) { /* get size of the signed data */ biolength = BIO_read(signedbio, NULL, maxlen); /* check if the timestamp response exists in the taggant */ if ((biolength - (int)pTaggantObj->tagBlob.Header.Length) > 0) { /* seek the pointer of the bio to tsresponse */ if (BIO_read(signedbio, NULL, pTaggantObj->tagBlob.Header.Length) == pTaggantObj->tagBlob.Header.Length) { /* load TS response, better to use d2i_TS_RESP instead of d2i_TS_RESP_bio */ tsbio = BIO_new(BIO_s_mem()); if (tsbio) { while ((inlen = BIO_read(signedbio, inbuf, 512)) > 0) { BIO_write(tsbio, inbuf, inlen); } pTaggantObj->TSResponse = d2i_TS_RESP_bio(tsbio, NULL); BIO_free(tsbio); } } } } } sk_X509_pop_free(cms_certs, X509_free); } } X509_VERIFY_PARAM_free(vpm); } } X509_STORE_free(trusted_store); } BIO_free(signedbio); } else { res = TMEMORY; } } } BIO_free(cmsbio); } else { res = TMEMORY; } } } else { res = TBADKEY; } if (res != TNOERR) { taggant2_free_taggantobj_content(pTaggantObj); } return res; } UNSIGNED32 taggant2_compare_default_hash(PHASHBLOB_DEFAULT pHash1, PHASHBLOB_DEFAULT pHash2) { UNSIGNED32 res = TMISMATCH; /* Check if hashblob of default hashes matches */ if (pHash1->Header.Version == pHash2->Header.Version && pHash1->Header.Version == HASHBLOB_VERSION2 && pHash1->Header.Type == pHash2->Header.Type && pHash1->Header.Type == TAGGANT_HASBLOB_DEFAULT && (memcmp(&pHash1->Header.Hash, &pHash2->Header.Hash, sizeof(pHash1->Header.Hash)) == 0) ) { res = TNOERR; } return res; } UNSIGNED32 taggant2_compare_extended_hash(PHASHBLOB_EXTENDED pHash1, PHASHBLOB_EXTENDED pHash2) { UNSIGNED32 res = TMISMATCH; /* Check if extended hash matches */ if (pHash1->Header.Version == pHash2->Header.Version && pHash1->Header.Version == HASHBLOB_VERSION2 && pHash1->Header.Type == pHash2->Header.Type && pHash1->Header.Type == TAGGANT_HASBLOB_EXTENDED && (memcmp(&pHash1->Header.Hash, &pHash2->Header.Hash, sizeof(pHash1->Header.Hash)) == 0) && (!pHash1->PhysicalEnd || (pHash1->PhysicalEnd == pHash2->PhysicalEnd)) ) { res = TNOERR; } return res; } UNSIGNED32 taggant2_validate_default_hashes_pe(PTAGGANTCONTEXT pCtx, PTAGGANTOBJ2 pTaggantObj, PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd) { PE_ALL_HEADERS peh; UNSIGNED32 res = TMEMORY; HASHBLOB_FULLFILE tmphb; UNSIGNED32 ds_offset, ds_size; UNSIGNED64 fileend = uFileEnd; EVP_MD_CTX evp; int valid_ds = 1; int valid_file = 0; if (winpe_is_correct_pe_file(pCtx, hFile, &peh)) { if (pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd == 0) { /* if the fileend value is not specified, take the file size */ if (!fileend) { fileend = get_file_size(pCtx, hFile); } /* Check if the file contains digital signature and if it is placed at the end of the file * If it is, then reduce fileend value to exclude digital signature, otherwise * mark file as there is no taggant */ if (winpe_is_pe64(&peh)) { ds_offset = (UNSIGNED32)peh.oh.pe64.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; ds_size = (UNSIGNED32)peh.oh.pe64.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; } else { ds_offset = (UNSIGNED32)peh.oh.pe32.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; ds_size = (UNSIGNED32)peh.oh.pe32.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; } if (ds_offset != 0 && ds_size != 0) { if ((ds_offset + ds_size) != fileend) { valid_ds = 0; } else { fileend -= ds_size; } } valid_file = valid_ds; } else { fileend = pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd; valid_file = 1; } if (valid_file && (!uFileEnd || (uFileEnd && fileend <= uFileEnd)) && fileend >= uObjectEnd) { if (fileend >= uObjectEnd) { /* Allocate a copy of taggant blob, without hashmap and extrablob buffers */ tmphb = pTaggantObj->tagBlob.Hash.FullFile; /* Compute hash */ EVP_MD_CTX_init(&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* Compute default hash */ if ((res = taggant2_compute_default_hash_pe(&evp, pCtx, &tmphb.DefaultHash, hFile, &peh, uObjectEnd)) == TNOERR) { if ((res = taggant2_compare_default_hash(&pTaggantObj->tagBlob.Hash.FullFile.DefaultHash, &tmphb.DefaultHash)) == TNOERR) { /* Compute extended hash */ if ((res = taggant2_compute_extended_hash_pe(&evp, pCtx, &tmphb.ExtendedHash, hFile, uObjectEnd, fileend)) == TNOERR) { res = taggant2_compare_extended_hash(&pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash, &tmphb.ExtendedHash); } } } /* Clean hash context */ EVP_MD_CTX_cleanup(&evp); } else { res = TFILEERROR; } } else { res = TERROR; } } else { res = TINVALIDPEFILE; } return res; } UNSIGNED32 taggant2_validate_default_hashes_bin(PTAGGANTCONTEXT pCtx, PTAGGANTOBJ2 pTaggantObj, PFILEOBJECT hFile, UNSIGNED64 uFileEnd) { UNSIGNED32 res = TMEMORY; HASHBLOB_FULLFILE tmphb; UNSIGNED64 fileend = uFileEnd; EVP_MD_CTX evp; if (pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd == 0) { /* if the fileend value is not specified, take the file size */ if (!fileend) { fileend = get_file_size(pCtx, hFile); } } else { fileend = pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd; } if (!uFileEnd || (uFileEnd && fileend <= uFileEnd)) { /* Allocate a copy of taggant blob, without hashmap and extrablob buffers */ tmphb = pTaggantObj->tagBlob.Hash.FullFile; /* Compute hash */ EVP_MD_CTX_init(&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* Compute default hash */ if ((res = taggant2_compute_default_hash_raw(&evp, pCtx, &tmphb.DefaultHash, hFile, fileend)) == TNOERR) { if ((res = taggant2_compare_default_hash(&pTaggantObj->tagBlob.Hash.FullFile.DefaultHash, &tmphb.DefaultHash)) == TNOERR) { /* Compute extended hash */ if ((res = taggant2_compute_extended_hash_raw(&tmphb.ExtendedHash, uFileEnd)) == TNOERR) { res = taggant2_compare_extended_hash(&pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash, &tmphb.ExtendedHash); } } } /* Clean hash context */ EVP_MD_CTX_cleanup(&evp); } else { res = TERROR; } return res; } UNSIGNED32 taggant2_validate_default_hashes_js(PTAGGANTCONTEXT pCtx, PTAGGANTOBJ2 pTaggantObj, PFILEOBJECT hFile, UNSIGNED64 uFileEnd) { UNSIGNED32 res = TMEMORY; HASHBLOB_FULLFILE tmphb; UNSIGNED64 fileend = uFileEnd, dsoffset; EVP_MD_CTX evp; if (pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd == 0) { /* if the fileend value is not specified, take the file size */ if (!fileend) { fileend = get_file_size(pCtx, hFile); } /* Check if the file contains digital signature */ if (js_get_ds_offset(pCtx, hFile, &dsoffset)) { fileend = dsoffset; } } else { fileend = pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd; } if (!uFileEnd || (uFileEnd && fileend <= uFileEnd)) { /* Allocate a copy of taggant blob, without hashmap and extrablob buffers */ tmphb = pTaggantObj->tagBlob.Hash.FullFile; /* Compute hash */ EVP_MD_CTX_init(&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* Compute default hash */ if ((res = taggant2_compute_default_hash_raw(&evp, pCtx, &tmphb.DefaultHash, hFile, fileend)) == TNOERR) { if ((res = taggant2_compare_default_hash(&pTaggantObj->tagBlob.Hash.FullFile.DefaultHash, &tmphb.DefaultHash)) == TNOERR) { /* Compute extended hash */ if ((res = taggant2_compute_extended_hash_raw(&tmphb.ExtendedHash, uFileEnd)) == TNOERR) { res = taggant2_compare_extended_hash(&pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash, &tmphb.ExtendedHash); } } } /* Clean hash context */ EVP_MD_CTX_cleanup(&evp); } else { res = TERROR; } return res; } UNSIGNED32 taggant2_validate_default_hashes_txt(PTAGGANTCONTEXT pCtx, PTAGGANTOBJ2 pTaggantObj, PFILEOBJECT hFile, UNSIGNED64 uFileEnd) { UNSIGNED32 res = TMEMORY; HASHBLOB_FULLFILE tmphb; UNSIGNED64 fileend = uFileEnd; EVP_MD_CTX evp; if (pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd == 0) { /* if the fileend value is not specified, take the file size */ if (!fileend) { fileend = get_file_size(pCtx, hFile); } } else { fileend = pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd; } if (!uFileEnd || (uFileEnd && fileend <= uFileEnd)) { /* Allocate a copy of taggant blob, without hashmap and extrablob buffers */ tmphb = pTaggantObj->tagBlob.Hash.FullFile; /* Compute hash */ EVP_MD_CTX_init(&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* Compute default hash */ if ((res = taggant2_compute_default_hash_raw(&evp, pCtx, &tmphb.DefaultHash, hFile, fileend)) == TNOERR) { if ((res = taggant2_compare_default_hash(&pTaggantObj->tagBlob.Hash.FullFile.DefaultHash, &tmphb.DefaultHash)) == TNOERR) { /* Compute extended hash */ if ((res = taggant2_compute_extended_hash_raw(&tmphb.ExtendedHash, uFileEnd)) == TNOERR) { res = taggant2_compare_extended_hash(&pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash, &tmphb.ExtendedHash); } } } /* Clean hash context */ EVP_MD_CTX_cleanup(&evp); } else { res = TERROR; } return res; } UNSIGNED32 taggant2_compare_hash_map(PHASHBLOB_HASHMAP pHm1, PHASHBLOB_HASHMAP pHm2) { UNSIGNED32 res = TMISMATCH; if (pHm1->Header.Version == HASHBLOB_VERSION2 && pHm1->Header.Type == TAGGANT_HASBLOB_HASHMAP && pHm1->Entries == pHm2->Entries && (memcmp(&pHm1->Header, &pHm2->Header, sizeof(HASHBLOB_HEADER)) == 0)) { res = TNOERR; } return res; } UNSIGNED32 taggant2_validate_hashmap(PTAGGANTCONTEXT pCtx, PTAGGANTOBJ2 pTaggantObj, PFILEOBJECT hFile) { UNSIGNED32 res = TNOERR; HASHBLOB_HASHMAP tmphm; int i; if ((pTaggantObj->tagBlob.Hash.Hashmap.DoublesOffset + (pTaggantObj->tagBlob.Hash.Hashmap.Entries * sizeof(HASHBLOB_HASHMAP_DOUBLE))) > pTaggantObj->tagBlob.Header.Length) { return TMEMORY; } /* Make sure the regions in hashmap are ordered correctly (from lowest offset to highest) */ for (i = 1; i < pTaggantObj->tagBlob.Hash.Hashmap.Entries; i++) { if (pTaggantObj->tagBlob.pHashMapDoubles[i - 1].AbsoluteOffset >= pTaggantObj->tagBlob.pHashMapDoubles[i].AbsoluteOffset) { res = TERROR; break; } } if (res == TNOERR) { /* Check if hashmap contains regions with zero size */ for (i = 0; i < pTaggantObj->tagBlob.Hash.Hashmap.Entries; i++) { if (pTaggantObj->tagBlob.pHashMapDoubles[i].Length == 0) { res = TERROR; break; } } } if (res == TNOERR) { /* Compute hash map */ tmphm = pTaggantObj->tagBlob.Hash.Hashmap; if ((res = taggant2_compute_hash_map(pCtx, hFile, &tmphm, pTaggantObj->tagBlob.pHashMapDoubles)) == TNOERR) { res = taggant2_compare_hash_map(&pTaggantObj->tagBlob.Hash.Hashmap, &tmphm); } } return res; } UNSIGNED32 taggant2_get_timestamp(PTAGGANTOBJ2 pTaggantObj, UNSIGNED64 *pTime, PVOID pTSRootCert) { UNSIGNED32 res = TERROR; char hash[HASH_SHA256_DIGEST_SIZE]; char* ptmp = NULL; BIO *tmpbio; EVP_MD_CTX evp; int year = 0; int month = 0; int day = 0; int hour = 0; int minute = 0; int second = 0; int temp; int maxlen = MAX_INTEGER, len; X509 *cert = NULL; X509_STORE *store; TS_TST_INFO* tstInfo = NULL; const ASN1_GENERALIZEDTIME* asn1Time = NULL; if (pTaggantObj->TSResponse == NULL) { return TNOTIME; } /* Calculate the hash of the taggant blob structure */ EVP_MD_CTX_init (&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* save taggant blob to bio and then to buffer */ tmpbio = BIO_new(BIO_s_mem()); if (tmpbio) { if (taggant2_write_taggantblob2(tmpbio, &pTaggantObj->tagBlob)) { len = BIO_read(tmpbio, NULL, maxlen); ptmp = memory_alloc(len); if (ptmp) { BIO_read(tmpbio, ptmp, len); EVP_DigestUpdate(&evp, ptmp, len); res = TNOERR; memory_free(ptmp); } else { res = TMEMORY; } } BIO_free(tmpbio); } else { res = TMEMORY; } EVP_DigestFinal_ex(&evp, (unsigned char *)&hash, NULL); EVP_MD_CTX_cleanup (&evp); /* Load all provided certificates */ if (res == TNOERR) { tmpbio = BIO_new(BIO_s_mem()); if (tmpbio) { BIO_write(tmpbio, pTSRootCert, (int)strlen((const char*)pTSRootCert)); if ((store = X509_STORE_new())) { while ((cert = PEM_read_bio_X509(tmpbio, NULL, 0, NULL))) { res = X509_STORE_add_cert(store, cert) ? res : TERROR; X509_free(cert); if (res != TNOERR) { X509_STORE_free(store); break; } } if (res == TNOERR) { if (check_time_stamp(pTaggantObj->TSResponse, store, (char*)&hash, sizeof(hash))) { tstInfo = TS_RESP_get_tst_info(pTaggantObj->TSResponse); asn1Time = TS_TST_INFO_get_time(tstInfo); temp = sscanf((const char*)ASN1_STRING_data((ASN1_STRING*)asn1Time), "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second); if (temp == 6) { *pTime = time_as_unsigned64(year, month, day, hour, minute, second); res = TNOERR; } else { res = TINVALID; } } else { res = TINVALID; } } } BIO_free(tmpbio); } } return res; } UNSIGNED32 taggant2_get_info(PTAGGANTOBJ2 pTaggantObj, ENUMTAGINFO eKey, UNSIGNED32 *pSize, PINFO pInfo) { UNSIGNED32 res = TERRORKEY; int biolength = 0; BIO *tmpbio = NULL; int maxlen = MAX_INTEGER; if (pTaggantObj->CMS == NULL) { return TNOTAGGANTS; } switch (eKey) { case ESPVCERT: res = TERROR; if (pTaggantObj->spv) { tmpbio = BIO_new(BIO_s_mem()); if (tmpbio) { if (i2d_X509_bio(tmpbio, pTaggantObj->spv)) { /* Get bio size */ maxlen = MAX_INTEGER; biolength = BIO_read(tmpbio, NULL, maxlen); if (biolength >= 0) { /* Make sure input buffer is enough to store BIO data */ if (*pSize >= (UNSIGNED32)biolength && pInfo != NULL) { BIO_read(tmpbio, pInfo, biolength); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = (UNSIGNED32)biolength; } } BIO_free(tmpbio); } else { res = TMEMORY; } } break; case EUSERCERT: res = TERROR; if (pTaggantObj->user) { tmpbio = BIO_new(BIO_s_mem()); if (tmpbio) { if (i2d_X509_bio(tmpbio, pTaggantObj->user)) { /* Get bio size */ maxlen = MAX_INTEGER; biolength = BIO_read(tmpbio, NULL, maxlen); if (biolength >= 0) { /* Make sure input buffer is enough to store BIO data */ if (*pSize >= (UNSIGNED32)biolength && pInfo != NULL) { BIO_read(tmpbio, pInfo, biolength); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = (UNSIGNED32)biolength; } } BIO_free(tmpbio); } else { res = TMEMORY; } } break; case EFILEEND: /* get the PhysicalEnd value from the taggant */ if (*pSize >= sizeof(pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd) && pInfo != NULL) { memcpy(pInfo, &pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd, sizeof(pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd)); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = sizeof(pTaggantObj->tagBlob.Hash.FullFile.ExtendedHash.PhysicalEnd); break; case EPACKERINFO: /* get the packer information from the taggant */ if (*pSize >= sizeof(PACKERINFO) && pInfo != NULL) { memcpy(pInfo, &pTaggantObj->tagBlob.Header.PackerInfo, sizeof(PACKERINFO)); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = sizeof(PACKERINFO); break; default: res = taggant2_get_extrainfo(&pTaggantObj->tagBlob.Extrablob, eKey, pSize, pInfo); break; } return res; } #endif #ifdef SPV_LIBRARY UNSIGNED32 taggant2_put_timestamp(PTAGGANTOBJ2 pTaggantObj, const char* pTSUrl, UNSIGNED32 uTimeout) { UNSIGNED32 res = TNONET; char hash[HASH_SHA256_DIGEST_SIZE]; EVP_MD_CTX evp; TS_RESP* tsResponse = NULL; char* ptmp = NULL; BIO *tbio; int maxlen = MAX_INTEGER, biolen; if (pTaggantObj->TSResponse != NULL) { TS_RESP_free(pTaggantObj->TSResponse); pTaggantObj->TSResponse = NULL; } /* Calculate the hash of the taggant blob structure */ EVP_MD_CTX_init (&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* Dump taggant blob */ tbio = BIO_new(BIO_s_mem()); if (tbio) { pTaggantObj->tagBlob.Header.Length = taggant2_taggantblob2_size(&pTaggantObj->tagBlob); if (taggant2_write_taggantblob2(tbio, &pTaggantObj->tagBlob)) { biolen = BIO_read(tbio, NULL, maxlen); ptmp = memory_alloc(biolen); if (ptmp) { BIO_read(tbio, ptmp, biolen); /* hash the taggant blob 2 */ EVP_DigestUpdate(&evp, ptmp, biolen); res = TNOERR; memory_free(ptmp); } else { res = TMEMORY; } } BIO_free(tbio); } else { res = TMEMORY; } if (res == TNOERR) { EVP_DigestFinal_ex(&evp, (unsigned char *)&hash, NULL); EVP_MD_CTX_cleanup(&evp); if ((res = get_timestamp_response(pTSUrl, (char*)&hash, sizeof(hash), uTimeout, &tsResponse)) == TNOERR) { pTaggantObj->TSResponse = tsResponse; } } return res; } UNSIGNED32 taggant2_add_hash_region(PTAGGANTOBJ2 pTaggantObj, UNSIGNED64 uOffset, UNSIGNED64 uLength) { PHASHBLOB_HASHMAP_DOUBLE hmd; HASHBLOB_HASHMAP_DOUBLE t; int i, j; UNSIGNED16 count; UNSIGNED64 a, b, c, d; char *tmpbuf; /* Check if the number of existing regions does not exceed allowed */ if (pTaggantObj->tagBlob.Hash.Hashmap.Entries >= HASHMAP_MAXIMUM_ENTRIES) { return TENTRIESEXCEED; } /* Realloc hashmap doubles to contain sufficient buffer for additional region */ tmpbuf = memory_realloc(pTaggantObj->tagBlob.pHashMapDoubles, pTaggantObj->tagBlob.Header.Length + sizeof(HASHBLOB_HASHMAP_DOUBLE)); if (!tmpbuf) { return TMEMORY; } pTaggantObj->tagBlob.pHashMapDoubles = (PHASHBLOB_HASHMAP_DOUBLE)tmpbuf; hmd = (PHASHBLOB_HASHMAP_DOUBLE)pTaggantObj->tagBlob.pHashMapDoubles; hmd[pTaggantObj->tagBlob.Hash.Hashmap.Entries].AbsoluteOffset = uOffset; hmd[pTaggantObj->tagBlob.Hash.Hashmap.Entries].Length = uLength; /* bubble sort hashmap array */ bubblesort_hashmap(hmd, pTaggantObj->tagBlob.Hash.Hashmap.Entries); pTaggantObj->tagBlob.Hash.Hashmap.Entries++; /* increase size of taggant blob */ pTaggantObj->tagBlob.Header.Length += sizeof(HASHBLOB_HASHMAP_DOUBLE); /* searching for overlapped regions */ count = 0; for (i = 0; i < pTaggantObj->tagBlob.Hash.Hashmap.Entries - 1; i++) { a = b = hmd[i].AbsoluteOffset; b += hmd[i].Length; c = d = hmd[i+1].AbsoluteOffset; d += hmd[i+1].Length; if (((a >= c) && (a <= d)) || ((b >= c) && (b <= d)) || ((c >= a) && (c <= b)) || ((d >= a) && (d <= b))) { /* overlapping here */ hmd[i+1].AbsoluteOffset = (a < c) ? a : c; hmd[i+1].Length = (b > d) ? b - hmd[i+1].AbsoluteOffset : d - hmd[i+1].AbsoluteOffset; hmd[i].AbsoluteOffset = 0; hmd[i].Length = 0; count++; } } /* if overlapped regions are found, then resize the array and remove zero size regions */ if (count > 0) { /* sort in descending order to move zero size regions at the end of array */ for (i = pTaggantObj->tagBlob.Hash.Hashmap.Entries - 1; i >= 0; i--) { for (j = 0; j <= pTaggantObj->tagBlob.Hash.Hashmap.Entries - 2; j++) { if (hmd[j].Length < hmd[j + 1].Length) { t = hmd[j]; hmd[j] = hmd[j + 1]; hmd[j + 1] = t; } } } /* decrease Entries on a number of intersections */ pTaggantObj->tagBlob.Hash.Hashmap.Entries = pTaggantObj->tagBlob.Hash.Hashmap.Entries - count; /* sort regions array */ bubblesort_hashmap(hmd, pTaggantObj->tagBlob.Hash.Hashmap.Entries - 1); /* realloc hashmap doubles */ tmpbuf = memory_realloc(pTaggantObj->tagBlob.pHashMapDoubles, pTaggantObj->tagBlob.Header.Length); if (!tmpbuf) { return TMEMORY; } pTaggantObj->tagBlob.pHashMapDoubles = (PHASHBLOB_HASHMAP_DOUBLE)tmpbuf; } return TNOERR; } UNSIGNED32 taggant2_put_info(PTAGGANTOBJ2 pTaggantObj, ENUMTAGINFO eKey, UNSIGNED32 uSize, PINFO pInfo) { UNSIGNED32 res = TERRORKEY; switch (eKey) { case EPACKERINFO: /* set the packer information to the taggant */ if (uSize >= sizeof(PACKERINFO) && pInfo != NULL) { memcpy(&pTaggantObj->tagBlob.Header.PackerInfo, pInfo, sizeof(PACKERINFO)); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } break; default: res = taggant2_put_extrainfo(&pTaggantObj->tagBlob.Extrablob, eKey, uSize, pInfo); break; } return res; } #endif void taggant2_free_taggantobj_content(PTAGGANTOBJ2 pTaggantObj) { /* Free extrablob */ if (pTaggantObj->tagBlob.Extrablob.Data) { memory_free(pTaggantObj->tagBlob.Extrablob.Data); pTaggantObj->tagBlob.Extrablob.Data = NULL; } pTaggantObj->tagBlob.Extrablob.Length = 0; /* Free hashmap */ if (pTaggantObj->tagBlob.pHashMapDoubles) { memory_free(pTaggantObj->tagBlob.pHashMapDoubles); pTaggantObj->tagBlob.pHashMapDoubles = NULL; } /* Free CMS */ if (pTaggantObj->CMS) { CMS_ContentInfo_free(pTaggantObj->CMS); pTaggantObj->CMS = NULL; } /* Free TSA response */ if (pTaggantObj->TSResponse) { TS_RESP_free(pTaggantObj->TSResponse); pTaggantObj->TSResponse = NULL; } /* Free user certificate*/ if (pTaggantObj->user) { X509_free(pTaggantObj->user); pTaggantObj->user = NULL; } /* Free spv certificate*/ if (pTaggantObj->spv) { X509_free(pTaggantObj->spv); pTaggantObj->spv = NULL; } /* Free root certificate*/ if (pTaggantObj->root) { X509_free(pTaggantObj->root); pTaggantObj->root = NULL; } }<file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #ifndef TYPES_HEADER #define TYPES_HEADER #include <openssl/bio.h> #include <openssl/cms.h> #include <openssl/ts.h> #include "taggant_types.h" #ifdef TAGGANT_LIBRARY /* Maximum buffer for conversion of X509 to binary */ #define MAX_INTEGER 0x7FFFFFFF #define HASH_SHA256_DIGEST_SIZE 32 #define HASHBLOB_VERSION 1 #define TAGGANTBLOB_VERSION 1 #define TAGGANT_VERSION 1 #define TAGGANT_MARKER_BEGIN 0x47474154 /* 'T'A'G'G' */ #define TAGGANT_MARKER_END 0x53544E41 /* 'A'N'T'S' */ #define HASHMAP_MAXIMUM_ENTRIES 100 /* TODO: Correct this value after testing with real certification system */ typedef enum { TAGGANT_HASBLOB_DEFAULT = 0, TAGGANT_HASBLOB_EXTENDED = 1, TAGGANT_HASBLOB_HASHMAP = 2 } TAGGANTHASHBLOBTYPE; #pragma pack(push,2) typedef struct { UNSIGNED16 Length; /* not implemented in the current specification char Data[0]; */ } EXTRABLOB, *PEXTRABLOB; typedef struct { UNSIGNED16 Length; UNSIGNED16 Type; UNSIGNED16 Version; unsigned char Hash[HASH_SHA256_DIGEST_SIZE]; } HASHBLOB_HEADER, *PHASHBLOB_HEADER; typedef struct { HASHBLOB_HEADER Header; } HASHBLOB_DEFAULT, *PHASHBLOB_DEFAULT; typedef struct { HASHBLOB_HEADER Header; UNSIGNED64 PhysicalEnd; } HASHBLOB_EXTENDED, *PHASHBLOB_EXTENDED; typedef struct { HASHBLOB_HEADER Header; UNSIGNED16 Entries; /* Offset to doubles array from begin of TAGGANTBLOB structure */ UNSIGNED16 DoublesOffset; } HASHBLOB_HASHMAP, *PHASHBLOB_HASHMAP; typedef struct { HASHBLOB_DEFAULT DefaultHash; HASHBLOB_EXTENDED ExtendedHash; } HASHBLOB_FULLFILE, *PHASHBLOB_FULLFILE; typedef struct { HASHBLOB_FULLFILE FullFile; HASHBLOB_HASHMAP Hashmap; } HASHBLOB, *PHASHBLOB; typedef struct { UNSIGNED16 Length; UNSIGNED16 Version; PACKERINFO PackerInfo; } TAGGANTBLOB_HEADER, *PTAGGANTBLOB_HEADER; typedef struct { TAGGANTBLOB_HEADER Header; HASHBLOB Hash; EXTRABLOB Extrablob; /* Array of hash map doubles HASHBLOB_HASHMAP_DOUBLE pHashMapDoubles[1]; */ } TAGGANTBLOB, *PTAGGANTBLOB; typedef struct { UNSIGNED32 MarkerBegin; UNSIGNED32 TaggantLength; UNSIGNED32 CMSLength; UNSIGNED16 Version; } TAGGANT_HEADER, *PTAGGANT_HEADER; typedef struct { EXTRABLOB Extrablob; UNSIGNED32 MarkerEnd; } TAGGANT_FOOTER, *PTAGGANT_FOOTER; typedef struct { TAGGANT_HEADER Header; PVOID CMSBuffer; TAGGANT_FOOTER Footer; } TAGGANT, *PTAGGANT; #pragma pack(pop) typedef struct { CMS_ContentInfo* CMS; TS_RESP* TSResponse; PTAGGANTBLOB pTagBlob; UNSIGNED32 uTaggantSize; } TAGGANTOBJ, *PTAGGANTOBJ; #endif /* TAGGANT_LIBRARY */ #endif /* TYPES_HEADER */ <file_sep>//============================================================================ // Name : ssv.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <fstream> #include <istream> #include <string> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <time.h> #include "fileio.h" #include "winpe.h" #include "taggantlib.h" #include "taggant_types.h" #include "miscellaneous.h" using namespace std; void print_tag_info(PTAGGANTOBJ tag_obj, ENUMTAGINFO eKey) { long unsigned int tag_info_size = 0; // Get the length of the eKey taggant information if (TaggantGetInfo(tag_obj, eKey, &tag_info_size, NULL) == TMEMORY) { // Allocate enough buffer char* taginfo = new char[tag_info_size]; // Get the eKey taggant information if (TaggantGetInfo(tag_obj, eKey, &tag_info_size, taginfo) == TNOERR) { // Print taggant information if (tag_info_size > 0) { for (int i = 0; i <= (int)tag_info_size / 16; i++) { int k = tag_info_size - i * 16; if (k > 0) { k = (k < 16) ? k : 16; cout << " "; for (int j = 0; j < k; j++) { printf("%02x ", (BYTE)taginfo[i * 16 + j]); } cout << "\n"; } } } } // Free buffer delete[] taginfo; } // return; } void seekdir(PTAGGANTCONTEXT pCtx, char* cacert, char* tscert, string path) { // Try to open the directory DIR* dir = opendir(path.c_str()); if (dir != 0) { struct dirent *d; while( (d = readdir(dir)) != 0) { if(strcmp(d->d_name,".") != 0 && strcmp(d->d_name,"..") != 0) { string p = path + "/" + d->d_name; // Try to open the file ifstream fin(p.c_str(), ios::binary); if (fin.is_open()) { cout << "" + p + "\n"; PE_ALL_HEADERS peh; // Make sure the file is correct PE file if (winpe_is_correct_pe_file(&fin, &peh)) { cout << " - correct PE file\n"; PTAGGANT taggant; // Get the taggant from the file if (TaggantGetTaggant(pCtx, (void*)&fin, TAGGANT_PEFILE, &taggant) == TNOERR) { cout << " - taggant is found\n"; // Initialize taggant object before it will be validated PTAGGANTOBJ tag_obj = TaggantObjectNew(taggant); if (tag_obj) { cout << " - taggant object created\n"; // Validate the taggant if (TaggantValidateSignature(tag_obj, (PTAGGANT)taggant, (PVOID)cacert) == TNOERR) { cout << " - taggant is correct\n"; // Check if the TS exists unsigned long long timest = 0; if (TaggantGetTimestamp(tag_obj, &timest, (PVOID)tscert) == TNOERR) { cout << " - taggant timestamp " << asctime(gmtime((time_t*)&timest)); } else { cout << " - taggant does not contain timestamp\n"; } // print packer information PPACKERINFO packer_info = TaggantPackerInfo(tag_obj); cout << " - file protected by packer with " << packer_info->PackerId << " id, version " << packer_info->VersionMajor << "."<< packer_info->VersionMinor << "." << packer_info->VersionBuild << "\n"; // Get file hash type int res = TNOERR; // Do a quick file check using hash map (in case it exists) PHASHBLOB_HASHMAP_DOUBLE dbl = NULL; int dbl_count = TaggantGetHashMapDoubles(tag_obj, &dbl); if (dbl_count) { cout << " - hashmap covers following regions:\n"; for (int i = 0; i < dbl_count; i++) { cout << i << ". from " << dbl[i].AbsoluteOffset << " to " << (dbl[i].AbsoluteOffset + dbl[i].Length) << "\n"; } // Compute hashmap of the current file res = TaggantValidateHashMap(pCtx, tag_obj, (void*)&fin); // Check if file hash is valid if (res == TNOERR) { cout << " - hashmap is valid\n"; } else { cout << " - hashmap is INVALID\n"; } } // If hashmap does not exist, or if it exists and valid we do a full file hash check if (res == TNOERR) { UNSIGNED64 file_end = 0; UNSIGNED32 size = sizeof(UNSIGNED64); // Get file end value from the taggant TaggantGetInfo(tag_obj, EFILEEND, &size, (char*)&file_end); if (!file_end) { file_end = fileio_fsize(&fin); } // int object_end = winpe_object_size(&fin, &peh); // Compute default hashes of the current file res = TaggantValidateDefaultHashes(pCtx, tag_obj, (void*)&fin, object_end, file_end); // Check if file hash is valid if (res == TNOERR) { cout << " - full file hash is valid\n"; cout << " - full file hash covers first " << file_end << " bytes\n"; } else { cout << " - full file hash is INVALID\n"; } } // Check if file hash is valid if (res == TNOERR) { // Extract all information from the taggant // SPV certificate cout << " - SPV Certificate\n"; print_tag_info(tag_obj, ESPVCERT); // End User certificate cout << " - User Certificate\n"; print_tag_info(tag_obj, EUSERCERT); } } else { cout << " - taggant is invalid\n"; } TaggantObjectFree(tag_obj); } TaggantFreeTaggant(taggant); } else { cout << " - taggant is not found\n"; } } fin.close(); } // Scan new directory recursively seekdir(pCtx, cacert, tscert, p); } } closedir(dir); } return; } #define MAX_PATH_LENGTH 0x8000 int main(int argc, char *argv[], char *envp[]) { cout << "Taggant Test Application\n\n"; const char* usage = "Usage: test.exe ca_root_certificate_file ca_ts_certificate_file [optional] directory_to_scan\n\n"; // Check if number of arguments is not less than 2 if (argc < 3) { cout << "Invalid Arguments, no CA and/or TS root certificates!\n\n" << usage; return 1; } // Check if second arguments points to the CA root certificate file ifstream fca(argv[1], ios::binary); if (!fca.is_open()) { cout << "CA certificate file does not exist\n\n" << usage; return 1; } fca.close(); // Check if third arguments points to the TS root certificate file ifstream fts(argv[2], ios::binary); if (!fts.is_open()) { cout << "TS certificate file does not exist\n\n" << usage; return 1; } fts.close(); // Check if the 4th argument exists and if it is a directory // Otherwise, scan current directory char* cwd = NULL; if (argc >= 4) { DIR* dir = opendir(argv[3]); if (dir != 0) { cwd = argv[3]; closedir(dir); } } char* tmp = NULL; if (cwd == NULL) { tmp = new char [MAX_PATH_LENGTH]; memset(tmp, 0, MAX_PATH_LENGTH); if (getcwd(tmp, MAX_PATH_LENGTH)) { cwd = tmp; } } int err = 0; if (cwd != NULL) { // Initialize taggant library TAGGANTFUNCTIONS funcs; memset(&funcs, 0, sizeof(TAGGANTFUNCTIONS)); UNSIGNED64 uVersion; // Set structure size funcs.size = sizeof(TAGGANTFUNCTIONS); TaggantInitializeLibrary(&funcs, &uVersion); cout << "Taggant Library version " << uVersion << "\n\n"; // Create taggant context PTAGGANTCONTEXT pCtx = TaggantContextNew(); // Vendor should check version flow here! pCtx->FileReadCallBack = (size_t (__DECLARATION *)(void*, void*, size_t))fileio_fread; pCtx->FileSeekCallBack = (int (__DECLARATION *)(void*, UNSIGNED64, int))fileio_fseek; pCtx->FileTellCallBack = (UNSIGNED64 (__DECLARATION *)(void*))fileio_ftell; // Load CA certificate to the memory ifstream fca(argv[1], ios::binary); fca.seekg(0, ios::end); long fsize = fca.tellg(); char* cacert = new char[fsize]; fca.seekg(0, ios::beg); fca.read(cacert, fsize); fca.clear(); // Load TS certificate to the memory ifstream fts(argv[2], ios::binary); fts.seekg(0, ios::end); long ftssize = fts.tellg(); char* tscert = new char[ftssize]; fts.seekg(0, ios::beg); fts.read(tscert, ftssize); fts.clear(); if (TaggantCheckCertificate(cacert) == TNOERR) { if (TaggantCheckCertificate(tscert) == TNOERR) { // scan the directory and search files with the taggant seekdir(pCtx, cacert, tscert, string(cwd)); } else { cout << "TS certificate is invalid\n\n" << usage; err = 1; } } else { cout << "CA certificate is invalid\n\n" << usage; err = 1; } delete[] cacert; TaggantContextFree(pCtx); TaggantFinalizeLibrary(); } if (tmp != NULL) { delete[] tmp; } return err; } <file_sep>IEEE_Taggant_System =================== The Taggant System was developed by the Malware Working Group of the ICSG (Industry Connections Security Group) under the umbrella of the IEEE. The Taggant System places a cryptographically secure marker in the packed and obfuscated files created by commercial software distribution packaging programs (packers). Legitimate packers are often abused by malware creators to create many, difficult-to-detect variants of their malware. The Taggant System markers identify the specific packer user's license key, used to create an instance of packed malware. That packer user can then be blacklisted, and all files created by that packer user will be reported as suspicious in the Taggant System. For more information please visit: http://standards.ieee.org/develop/indconn/icsg/amss.html <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include "global.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "js.h" #include "types.h" #include "taggant.h" #include "endianness.h" #include "taggant_types.h" #include "callbacks.h" #include "miscellaneous.h" int js_get_ds_offset(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, UNSIGNED64 *offset) { char* buf; int res = 0, err, i, j, found, toread; UNSIGNED64 pos = get_file_size(pCtx, fp); if (pos > 0) { /* allocate buffer for file content*/ buf = memory_alloc(HASH_READ_BLOCK); if (buf) { /* find the end of the file excluding \r and \n */ err = 0; while (pos > 0) { toread = pos > HASH_READ_BLOCK ? HASH_READ_BLOCK : (int)pos; if (file_seek(pCtx, fp, pos - toread, SEEK_SET)) { if (file_read_buffer(pCtx, fp, buf, toread)) { found = 0; for (i = toread - 1; i > 0; i--) { if (buf[i] == '\r' || buf[i] == '\n') { pos--; } else { found = 1; break; } } if (found) { break; } } else { err = 1; break; } } else { err = 1; break; } } /* search for end ds marker */ if (!err) { toread = (int)strlen(JS_DS_END); if (pos >= toread) { if (file_seek(pCtx, fp, pos - toread, SEEK_SET)) { if (file_read_buffer(pCtx, fp, buf, toread)) { if (_strnicmp(buf, JS_DS_END, toread) == 0) { pos -= toread; } else { err = 1; } } else { err = 1; } } else { err = 1; } } } /* search for begin ds marker */ if (!err) { while (pos >= strlen(JS_DS_BEGIN)) { toread = pos > HASH_READ_BLOCK ? HASH_READ_BLOCK : (int)pos; if (file_seek(pCtx, fp, pos - toread, SEEK_SET)) { if (file_read_buffer(pCtx, fp, buf, toread)) { i = toread; while (i != 0) { j = (int)strlen(JS_DS_BEGIN); found = 1; while (j != 0) { i--; j--; if ((buf[i] | 32) != (JS_DS_BEGIN[j] | 32)) { found = 0; break; } } if (found) { *offset = pos - toread + i; res = 1; break; } } if (res) { break; } pos -= toread; if (pos != 0) { pos += strlen(JS_DS_BEGIN) - 1; } } else { err = 1; break; } } else { err = 1; break; } if (res != 0) { break; } } } memory_free(buf); } else { err = 1; } } return res; }<file_sep>/* ==================================================================== * Copyright (c) 2015 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== * * author: <NAME> (<EMAIL>) */ #define __STDC_WANT_LIB_EXT1__ 1 #pragma warning(disable:4706;disable:4820;disable:4255;disable:4668) #include <io.h> #include <malloc.h> #include <stdarg.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <windows.h> #include "taggantlib.h" #define TAGGANT_MARKER_END 0x53544E41 /* 'A'N'T'S' */ #define TAGGANT_ADDRESS_JMP 0x08EB #define TAGGANT_ADDRESS_JMP_SIZE 2 //#define CSA_MODE //#define SKIP_CREATE //#define KEEP_FILES // from types.h typedef struct { UNSIGNED16 Version; UNSIGNED32 CMSLength; UNSIGNED32 TaggantLength; UNSIGNED32 MarkerBegin; } TAGGANT_HEADER2; #define PACKER_ID 3141592653 #define PACKER_MAJOR 1234 #define PACKER_MINOR 2468 #define PACKER_BUILD 3692 #define TESTSTRING1 "ABC" #define TESTSTRING2 "DEFG" #define PR_WIDTH "%-140s" static UNSIGNED32 (STDCALL *pTaggantInitializeLibrary) (_In_opt_ TAGGANTFUNCTIONS *pFuncs, _Out_writes_(1) UNSIGNED64 *puVersion); static UNSIGNED32 (STDCALL *pTaggantContextNewEx) (_Outptr_ PTAGGANTCONTEXT *pTaggantCtx); static UNSIGNED32 (STDCALL *pTaggantObjectNewEx) (_In_opt_ PTAGGANT pTaggant, UNSIGNED64 uVersion, TAGGANTCONTAINER eTaggantType, _Outptr_ PTAGGANTOBJ *pTaggantObj); static PPACKERINFO (STDCALL *pTaggantPackerInfo) (_In_ PTAGGANTOBJ pTaggantObj); static UNSIGNED32 (STDCALL *pTaggantGetLicenseExpirationDate) (_In_ const PVOID pLicense, _Out_writes_(1) UNSIGNED64 *pTime); static UNSIGNED32 (STDCALL *pTaggantAddHashRegion) (_Inout_ PTAGGANTOBJ pTaggantObj, UNSIGNED64 uOffset, UNSIGNED64 uLength); static UNSIGNED32 (STDCALL *pTaggantComputeHashes) (_Inout_ PTAGGANTCONTEXT pCtx, _Inout_ PTAGGANTOBJ pTaggantObj, _In_ PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd, UNSIGNED32 uTaggantSize); static UNSIGNED32 (STDCALL *pTaggantPutInfo) (_Inout_ PTAGGANTOBJ pTaggantObj, ENUMTAGINFO eKey, UNSIGNED16 Size, _In_reads_(Size) PINFO pInfo); static UNSIGNED32 (STDCALL *pTaggantPutTimestamp) (_Inout_ PTAGGANTOBJ pTaggantObj, _In_z_ const char* pTSUrl, UNSIGNED32 uTimeout); static UNSIGNED32 (STDCALL *pTaggantPrepare) (_Inout_ PTAGGANTOBJ pTaggantObj, _In_ const PVOID pLicense, _Out_writes_bytes_(*uTaggantReservedSize) PVOID pTaggantOut, _Inout_updates_(1) UNSIGNED32 *uTaggantReservedSize); static UNSIGNED32 (STDCALL *pTaggantCheckCertificate) (_In_ const PVOID pCert); static UNSIGNED32 (STDCALL *pTaggantGetTaggant) (_In_ PTAGGANTCONTEXT pCtx, _In_ PFILEOBJECT hFile, TAGGANTCONTAINER eContainer, _Inout_ PTAGGANT *pTaggant); static UNSIGNED32 (STDCALL *pTaggantValidateSignature) (_In_ PTAGGANTOBJ pTaggantObj, _In_ PTAGGANT pTaggant, _In_ const PVOID pRootCert); static UNSIGNED32 (STDCALL *pTaggantGetTimestamp) (_In_ PTAGGANTOBJ pTaggantObj, _Out_writes_(1) UNSIGNED64 *pTime, _In_ const PVOID pTSRootCert); static UNSIGNED16 (STDCALL *pTaggantGetHashMapDoubles) (_In_ PTAGGANTOBJ pTaggantObj, _Out_writes_(1) PHASHBLOB_HASHMAP_DOUBLE *pDoubles); static UNSIGNED32 (STDCALL *pTaggantValidateHashMap) (_In_ PTAGGANTCONTEXT pCtx, _In_ PTAGGANTOBJ pTaggantObj, _In_ PFILEOBJECT hFile); static UNSIGNED32 (STDCALL *pTaggantGetInfo) (_In_ PTAGGANTOBJ pTaggantObj, ENUMTAGINFO eKey, _Inout_updates_(1) UNSIGNED32 *pSize, _Out_writes_opt_(*pSize) PINFO pInfo); static UNSIGNED32 (STDCALL *pTaggantValidateDefaultHashes) (_In_ PTAGGANTCONTEXT pCtx, _In_ PTAGGANTOBJ pTaggantObj, _In_ PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd); static UNSIGNED32 (STDCALL *pTaggantFreeTaggant) (_Post_ptr_invalid_ PTAGGANT pTaggant); static void (STDCALL *pTaggantContextFree) (_Post_ptr_invalid_ PTAGGANTCONTEXT pTaggantCtx); static void (STDCALL *pTaggantObjectFree) (_Post_ptr_invalid_ PTAGGANTOBJ pTaggantObj); static void (STDCALL *pTaggantFinalizeLibrary) (void); #if !defined(FALSE) #define FALSE 0 #endif #if !defined(TRUE) #define TRUE 1 #endif enum { METHOD_HMH, METHOD_FFH }; enum { TAMPER_NONE, TAMPER_FILELEN, TAMPER_FILELENM1, TAMPER_FILELENM2, TAMPER_TAGP101, TAMPER_FILELENM2P101, TAMPER_TIME, TAMPER_3 }; enum { TAG_1, TAG_2, TAG_3, TAG_1_HMH, TAG_2_HMH, TAG_2_1_HMH, TAG_1_1, TAG_1_FFH, TAG_2_FFH }; enum { ERR_NONE = TNOERR, ERR_BADOPEN = ERR_NONE + 100, ERR_NOMEM, ERR_BADREAD, ERR_BADPE, ERR_BADLIB, ERR_BADLIBVER, ERR_BADFILE, }; enum { LVL_UNKNOWN, LVL_MSGONLY, LVL_CLOSEDATA, LVL_FREELIC, LVL_FREEROOT = LVL_FREELIC, LVL_FREEPE32, LVL_FREEPE64, LVL_FREEDLL, LVL_FINALISE, }; enum { MODE_SPV, MODE_SSV }; static void print_tagerr(int err) { switch (err) { case TTYPE: { printf("the library does not support the requested version or TaggantType\n"); break; } case TNOTAGGANTS: { printf("the file does not contain a Taggant\n"); break; } case TMEMORY: case ERR_NOMEM: { printf("there is not enough memory to allocate the structure\n"); break; } case TFILEERROR: { printf("object size is larger than the file size\n"); break; } case TBADKEY: { printf("CMS validation has failed\n"); break; } case TMISMATCH: { printf("hashes do not match\n"); break; } case TERRORKEY: { printf("the type of information passed by the ENUMTAGINFO parameter is not supported\n"); break; } case TNONET: { printf("no connection to the internet\n"); break; } /*//// case TTIMEOUT: { printf("the timestamp authority server response time has expired\n"); break; } case TINTERNALERROR: { printf("unspecified error during timestamp operation\n"); break; } case TSERVERERROR: { printf("the timestamp authority server returned an error\n"); break; } */ case TERROR: { printf("TAGGANTOBJ does not contain the TAGGANTBLOB structure\n"); break; } case TNOTIME: { printf("the Taggant does not contain the time of the file's signature\n"); break; } case TINVALID: { printf("the response from the Timestamp Authority server is incorrect\n"); break; } case TLIBNOTINIT: { printf("the Taggant library has not been initialized using the TaggantLibraryInitialize function.\n"); break; } case TINVALIDPEFILE: case ERR_BADPE: { printf("PE file is malformed\n"); break; } case TINVALIDPEENTRYPOINT: { printf("the entry point of the PE file is not found\n"); break; } case TINVALIDTAGGANTOFFSET: { printf("the Taggant structure is incorrect\n"); break; } case TINVALIDTAGGANT: { printf("the Taggant structure is damaged\n"); break; } case TFILEACCESSDENIED: case ERR_BADREAD: { printf("operations with the file returned an error\n"); break; } case TENTRIESEXCEED: { printf("number of regions exceeded the maximum allowed\n"); break; } case TINSUFFICIENTBUFFER: { printf("buffer for data is to small to hold the data\n"); break; } case TNOTFOUND: { printf("the requested tag does not exist\n"); break; } case ERR_BADOPEN: { printf("error opening a file\n"); break; } case ERR_BADFILE: { printf("file seek or read failure\n"); break; } case ERR_BADLIB: { printf("error resolving function or unsupported behaviour\n"); break; } case ERR_BADLIBVER: { printf("library does not support requested version\n"); break; } default: { printf("error: unsupported error number %d\n", err ); } } } #if !defined(KEEP_FILES) static const char *spv_files[] = { "v1test01", "v1test02", "v1test03", "v1test04", "v1test05", "v1test06", "v1test07", "v1test08", "v1test09", "v1test10", "v1test11", "v1test12", "v1tampered1_32", "v1test13", "v1test14", "v1tampered1_64", "v1test15", "v1test16", "v1test17", "v1tampered2_32", "v1test18", "v1tampered2_64", "v1test19", "v1test20", "v1test21", "v1test22", "v1badhmh_32", "v1test23", "v2badhmh_32", "v1test24", "v1badhmh_64", "v1test25", "v2badhmh_64", "v1test26", "v1test27", "v1test28", "v1test29", "v1test30", "v1test31", "v1test32", "v2test01", "v2test02", "v2test03", "v2test04", "v2test05", "v2test06", "v2test07", "v2test08", "v2test09", "v2test10", "v2test11", "v2test12", "v2test13", "v2test14", "v2test15", "v2test16", "v2test17", "v2tampered1_32", "v2test18", "v2test19", "v2tampered1_64", "v2test20", "v2test21", "v2tampered2_32", "v2test22", "v2test23", "v2tampered2_64", "v2test24", "v2test25", "v2test26", "v2test27", "v2test28", "v2test29", "v2test30", "v2test31", "v2test32", "v2test33", "v2test34", "v2test35", "v2test36", "v2test37", "v2test38", "v2test39", "v2test40", "v2test41", "v2test42", "v2test43", "v2test44", "v2test45", "v2test46", "v2test47", "v2test48", "v2test49", "v2test50", "v2test51", "v2test52", "v2test55", "v2test56", "v2test57", "v2test58", "v2test59", "v2test60", "v2test61", "v2test62", "v2test63", "v2test64", "v2test65", "vdstest01", "vdstest02", "vdstest03", "vdstest04", "vdstest05", "vdstest06", "vdstest07", "vdstest08", "vdstest09", "vdstest10", "veoftest01", "veoftest02" }; static void delete_spv(void) { int i; i = 0; do { _unlink(spv_files[i]); } while (++i < (sizeof(spv_files) / sizeof(char *))); } static const char *ssv_files[] = { "vssvtest001", "vssvtest007", "vssvtest023", "vssvtest024", "vssvtest025", "vssvtest026", "vssvtest027", "vssvtest028", "vssvtest029", "vssvtest030", "vssvtest031", "vssvtest032", "vssvtest035", "vssvtest036", "vssvtest037", "vssvtest040", "vssvtest041", "vssvtest042", "vssvtest047", "vssvtest048", "vssvtest049", "vssvtest050", "vssvtest051", "vssvtest052", "vssvtest053", "vssvtest054", "vssvtest055", "vssvtest056", "vssvtest059", "vssvtest060", "vssvtest061", "vssvtest062", "vssvtest063", "vssvtest064", "vssvtest065", "vssvtest066", "vssvtest067", "vssvtest068", "vssvtest115", "vssvtest116", "vssvtest117", "vssvtest118", "vssvtest135" }; static void delete_ssv(void) { int i; delete_spv(); i = 0; do { _unlink(ssv_files[i]); } while (++i < (sizeof(ssv_files) / sizeof(char *))); } #endif static void cleanup_spv(int keepfiles, int level, ... ) { va_list arg; if (!keepfiles) { #if !defined(KEEP_FILES) delete_spv(); #endif } va_start(arg, level ); switch (level) { case LVL_FINALISE: { pTaggantContextFree(va_arg(arg, PTAGGANTCONTEXT ) ); pTaggantFinalizeLibrary(); } /* fall through */ case LVL_FREEDLL: { FreeLibrary(va_arg(arg, HMODULE ) ); free(va_arg(arg, PVOID /* jsfile */ ) ); } /* fall through */ case LVL_FREEPE64: /* pefile64 */ { free(va_arg(arg, PVOID ) ); } /* fall through */ case LVL_FREEPE32: { free(va_arg(arg, /* pefile32 */ PVOID ) ); } /* fall through */ case LVL_FREELIC: /* licdata */ { free(va_arg(arg, UNSIGNED8 * ) ); } /* fall through */ case LVL_CLOSEDATA: { FILE *infile; if ((infile = va_arg(arg, FILE * ) ) != NULL ) { fclose(infile); } } /* fall through */ case LVL_MSGONLY: { int err; if ((err = va_arg(arg, int ) ) != ERR_NONE ) { print_tagerr(err); } break; } default: { printf("error: unsupported level %d\n", level); } } va_end(arg); } static void cleanup_ssv(int level, ... ) { va_list arg; #if !defined(KEEP_FILES) delete_ssv(); #endif va_start(arg, level ); switch (level) { case LVL_FINALISE: { pTaggantContextFree(va_arg(arg, PTAGGANTCONTEXT ) ); pTaggantFinalizeLibrary(); } /* fall through */ case LVL_FREEDLL: { FreeLibrary(va_arg(arg, HMODULE ) ); free(va_arg(arg, PVOID /* tsrootdata */ ) ); } /* fall through */ case LVL_FREEROOT: /* rootdata */ { free(va_arg(arg, PVOID ) ); } /* fall through */ case LVL_CLOSEDATA: { FILE *infile; if ((infile = va_arg(arg, FILE * ) ) != NULL ) { fclose(infile); } } /* fall through */ case LVL_MSGONLY: { int err; if ((err = va_arg(arg, int ) ) != ERR_NONE ) { print_tagerr(err); } break; } default: { printf("error: unsupported level %d\n", level); } } va_end(arg); } static int read_data_file(_In_z_ const char *filename, _Inout_ UNSIGNED8 **pdata, UNSIGNED64 *pdata_len ) { FILE *infile; long filelen; UNSIGNED8 *data; if (fopen_s(&infile, filename, "rb" ) || !infile ) { cleanup_spv(TRUE, LVL_MSGONLY, ERR_BADOPEN ); return ERR_BADOPEN; } if (fseek(infile, 0, SEEK_END ) ) { cleanup_spv(TRUE, LVL_CLOSEDATA, infile, ERR_BADFILE ); return ERR_BADFILE; } if ((data = (UNSIGNED8 *) malloc(filelen = *pdata_len = ftell(infile))) == NULL) { cleanup_spv(TRUE, LVL_CLOSEDATA, infile, ERR_NOMEM ); return ERR_NOMEM; } if (fseek(infile, 0, SEEK_SET ) || ((long) fread(data, 1, filelen, infile ) != filelen ) ) { cleanup_spv(TRUE, LVL_FREELIC, data, infile, ERR_BADREAD ); return ERR_BADREAD; } fclose(infile); *pdata = data; return ERR_NONE; } #if !defined(BIG_ENDIAN) #define read_le16(offset) (*((UINT16 *) (offset))) #define read_le32(offset) (*((UINT32 *) (offset))) #define read_le64(offset) (*((UINT64 *) (offset))) #else #define read_le16(offset) (((unsigned int) *((PINFO) (offset) + 1) << 8) \ + *((PINFO) (offset) + 0) \ ) #define read_le32(offset) (((UNSIGNED32) *((PINFO) (offset) + 3) << 0x18) \ + ((UNSIGNED32) *((PINFO) (offset) + 2) << 0x10) \ + ((UNSIGNED32) *((PINFO) (offset) + 1) << 8) \ + *((PINFO) (offset) + 0) \ ) #define read_le64(offset) (((UNSIGNED64) *((PINFO) (offset) + 7) << 0x38) \ + ((UNSIGNED64) *((PINFO) (offset) + 6) << 0x30) \ + ((UNSIGNED64) *((PINFO) (offset) + 5) << 0x28) \ + ((UNSIGNED64) *((PINFO) (offset) + 4) << 0x20) \ + ((UNSIGNED64) *((PINFO) (offset) + 3) << 0x18) \ + ((UNSIGNED64) *((PINFO) (offset) + 2) << 0x10) \ + ((UNSIGNED64) *((PINFO) (offset) + 1) << 8) \ + *((PINFO) (offset) + 0) \ ) #endif static UNSIGNED32 virttophys(UNSIGNED64 pefile_len, _In_reads_(sectcount) const IMAGE_SECTION_HEADER *secttbl, unsigned int sectcount, UNSIGNED32 virtoff, UNSIGNED32 filealign, _Out_writes_(1) UNSIGNED64 *imagesize ) { if (sectcount) { UNSIGNED32 invalid; UNSIGNED32 physoff; UNSIGNED32 maxsize; unsigned int hdrchk; invalid = 0xffffffff; physoff = virtoff; maxsize = 0; hdrchk = 0; do { UNSIGNED32 rawptr; UNSIGNED32 rawalign; UNSIGNED32 rawsize; UNSIGNED32 readsize; UNSIGNED32 virtsize; UNSIGNED32 virtaddr = 0; // keep compiler happy rawalign = (rawptr = read_le32(&secttbl->PointerToRawData)) & ~0x1ff; readsize = ((rawptr + (rawsize = read_le32(&secttbl->SizeOfRawData)) + filealign - 1) & ~(filealign - 1)) - rawalign; readsize = min(readsize, (rawsize + 0xfff) & ~0xfff); if ((virtsize = read_le32(&secttbl->Misc.VirtualSize)) != 0) { readsize = min(readsize, (virtsize + 0xfff) & ~0xfff ); } if (invalid && ((virtaddr = read_le32(&secttbl->VirtualAddress)) <= virtoff) && ((virtaddr + readsize) > virtoff) ) { physoff = rawalign + virtoff - virtaddr; ++invalid; } if (!hdrchk) { /* if entrypoint is in header */ if (invalid) { invalid += (virtoff < virtaddr); } ++hdrchk; } if (rawptr && readsize && ((rawalign + readsize) > maxsize) ) { maxsize = rawalign + readsize; } ++secttbl; } while (--sectcount); *imagesize = maxsize; return (physoff | invalid); } *imagesize = pefile_len; return virtoff; } static int object_sizes(_In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 pefile_len, UNSIGNED64 *ppeobj_len, UNSIGNED64 *ptag_off, UNSIGNED32 *ptag_len ) { UNSIGNED32 lfanew; UNSIGNED32 entrypoint; unsigned int sectcount; IMAGE_SECTION_HEADER *secttbl; UNSIGNED64 tag_off; const UNSIGNED8 *tmp_ptr; const UNSIGNED8 *tag_ptr = 0; //keep compiler happy UNSIGNED32 tag_len; if (pefile_len < sizeof(IMAGE_DOS_HEADER)) { return ERR_BADPE; } if ((read_le16(pefile) != IMAGE_DOS_SIGNATURE) || (pefile_len < ((lfanew = read_le32(pefile + offsetof(IMAGE_DOS_HEADER, e_lfanew ) ) ) + offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + offsetof(IMAGE_OPTIONAL_HEADER32, BaseOfCode ) ) ) || (read_le32(pefile + lfanew) != IMAGE_NT_SIGNATURE) ) { return ERR_BADPE; } *ppeobj_len = pefile_len; entrypoint = read_le32(pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + offsetof(IMAGE_OPTIONAL_HEADER32, AddressOfEntryPoint ) ); if ((sectcount = read_le16(pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, FileHeader ) + offsetof(IMAGE_FILE_HEADER, NumberOfSections ) ) ) != 0 ) { unsigned int optsize; if (pefile_len < (lfanew + offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + (optsize = read_le16(pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, FileHeader ) + offsetof(IMAGE_FILE_HEADER, SizeOfOptionalHeader ) ) ) + (sectcount * sizeof(IMAGE_SECTION_HEADER)) ) ) { return ERR_BADPE; } if ((entrypoint = virttophys(pefile_len, secttbl = (IMAGE_SECTION_HEADER *) (pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + optsize ), sectcount, entrypoint, read_le32(pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + offsetof(IMAGE_OPTIONAL_HEADER32, FileAlignment ) ), ppeobj_len ) ) == -1 ) { return ERR_BADPE; } } if ((pefile_len < (entrypoint + TAGGANT_ADDRESS_JMP_SIZE + 8)) || (read_le16(pefile + entrypoint) != TAGGANT_ADDRESS_JMP) || (pefile_len < (tag_off = *ptag_off = read_le64(pefile + entrypoint + TAGGANT_ADDRESS_JMP_SIZE))) || ((pefile_len != tag_off) && (pefile_len < (tag_off + sizeof(TAGGANT_MARKER_END))) ) ) { return TNOTAGGANTS; } *ptag_len = 0; if (pefile_len != tag_off) { tmp_ptr = pefile + tag_off; tag_len = (UNSIGNED32) ((pefile_len - tag_off) - (sizeof(TAGGANT_MARKER_END) - 1)); while (tag_len && ((tag_ptr = (const UNSIGNED8 *) memchr(tmp_ptr, TAGGANT_MARKER_END & 0xff, tag_len ) ) != NULL ) && (read_le32(tag_ptr) != TAGGANT_MARKER_END) ) { tag_len -= tag_ptr + 1 - tmp_ptr; tmp_ptr = tag_ptr + 1; } if (!tag_len || !tag_ptr ) { return TNOTAGGANTS; } *ptag_len = (UNSIGNED32) (tag_ptr + sizeof(TAGGANT_MARKER_END) - (pefile + tag_off)); } return ERR_NONE; } static void print_usage(void) { printf("usage: test <license.pem> <PE-32 file> <PE-64 file> <JS file> <root.crt> <tsroot.crt>\n" "PE file must be prepared to receive either v1 or v2 Taggant\n" "(requires either reserved space containing Taggant footer, or Taggant v1 offset=EOF)\n" ); } static int validate_spv_parms(int argc, _In_reads_(argc) char *argv[], UNSIGNED8 **plicdata, UNSIGNED8 **ppefile32, UNSIGNED64 *ppefile32_len, UNSIGNED64 *ppeobj32_len, UNSIGNED64 *ptag32_off, UNSIGNED32 *ptag32_len, UNSIGNED8 **ppefile64, UNSIGNED64 *ppefile64_len, UNSIGNED64 *ppeobj64_len, UNSIGNED64 *ptag64_off, UNSIGNED32 *ptag64_len, UNSIGNED8 **pjsfile, UNSIGNED64 *pjsfile_len ) { int result; result = ERR_BADOPEN; if (argc == 7) { if ((result = read_data_file(argv[1], plicdata, ppefile32_len ) ) != ERR_NONE ) { } else if ((result = read_data_file(argv[2], ppefile32, ppefile32_len ) ) != ERR_NONE ) { cleanup_spv(TRUE, LVL_FREELIC, *plicdata, 0, 0 ); } else if ((result = object_sizes(*ppefile32, *ppefile32_len, ppeobj32_len, ptag32_off, ptag32_len ) ) != ERR_NONE ) { cleanup_spv(TRUE, LVL_FREEPE32, *ppefile32, *plicdata, 0, result ); } else if ((result = read_data_file(argv[3], ppefile64, ppefile64_len ) ) != ERR_NONE ) { cleanup_spv(TRUE, LVL_FREEPE32, *ppefile32, *plicdata, 0, 0 ); } else if ((result = object_sizes(*ppefile64, *ppefile64_len, ppeobj64_len, ptag64_off, ptag64_len ) ) != ERR_NONE ) { cleanup_spv(TRUE, LVL_FREEPE64, *ppefile64, *ppefile32, *plicdata, 0, result ); } else if ((result = read_data_file(argv[4], pjsfile, pjsfile_len ) ) != ERR_NONE ) { cleanup_spv(TRUE, LVL_FREEPE64, *ppefile64, *ppefile32, *plicdata, 0, 0 ); } } if (result) { print_usage(); } return result; } static int validate_ssv_parms(_In_ char *argv[], UNSIGNED8 **prootdata, UNSIGNED8 **ptsrootdata ) { int result; UNSIGNED64 file_len; result = ERR_BADOPEN; if ((result = read_data_file(argv[5], prootdata, &file_len ) ) != ERR_NONE ) { } else if ((result = read_data_file(argv[6], ptsrootdata, &file_len ) ) != ERR_NONE ) { cleanup_ssv(TRUE, LVL_FREEROOT, *prootdata, 0, 0 ); } if (result) { print_usage(); } return result; } static size_t __stdcall my_fread(_In_ PFILEOBJECT fp, _Out_writes_bytes_all_(size) PVOID buffer, size_t size ) { return fread(buffer, 1, size, (FILE *) fp ); } static int __stdcall my_fseek(_In_ PFILEOBJECT fp, UNSIGNED64 offset, int where ) { return fseek((FILE *) fp, (long) offset, where ); } static UNSIGNED64 __stdcall my_ftell(_In_ PFILEOBJECT fp) { return ftell((FILE *) fp); } static int init_library(_In_z_ const char *dllname, _Out_writes_(1) HMODULE *plibsxv ) { HMODULE libsxv; if (((libsxv = *plibsxv = LoadLibraryA(dllname)) == NULL) || ((pTaggantInitializeLibrary = (UNSIGNED32 (STDCALL *) (TAGGANTFUNCTIONS *, UNSIGNED64 * ) ) GetProcAddress(libsxv, "TaggantInitializeLibrary" ) ) == NULL ) || ((pTaggantContextNewEx = (UNSIGNED32 (STDCALL *) (PTAGGANTCONTEXT *)) GetProcAddress(libsxv, "TaggantContextNewEx" ) ) == NULL ) || ((pTaggantObjectNewEx = (UNSIGNED32 (STDCALL *) (PVOID, UNSIGNED64, TAGGANTCONTAINER, PTAGGANTOBJ * ) ) GetProcAddress(libsxv, "TaggantObjectNewEx" ) ) == NULL ) || ((pTaggantPackerInfo = (PPACKERINFO (STDCALL *) (PTAGGANTOBJ)) GetProcAddress(libsxv, "TaggantPackerInfo" ) ) == NULL ) || ((pTaggantContextFree = (void (STDCALL *)(PTAGGANTCONTEXT)) GetProcAddress(libsxv, "TaggantContextFree" ) ) == NULL ) || ((pTaggantObjectFree = (void (STDCALL *)(PTAGGANTOBJ)) GetProcAddress(libsxv, "TaggantObjectFree" ) ) == NULL ) || ((pTaggantFinalizeLibrary = (void (STDCALL *)(void)) GetProcAddress(libsxv, "TaggantFinalizeLibrary" ) ) == NULL ) ) { return ERR_BADLIB; } return ERR_NONE; } static int init_post_library(int mode, UNSIGNED64 reqver, _In_opt_z_ const UNSIGNED8 *licdata, _In_opt_ const UNSIGNED8 *rootdata, _In_opt_ const UNSIGNED8 *tsrootdata, _Inout_updates_(1) PTAGGANTCONTEXT *pcontext ) { int result; UNSIGNED64 uVersion; UNSIGNED64 ltime; if ((result = pTaggantInitializeLibrary(NULL, &uVersion ) != TNOERR ) ) { return result; } if (uVersion < reqver) { return ERR_BADLIBVER; } if (((mode == MODE_SPV) && (!licdata || ((result = pTaggantGetLicenseExpirationDate(licdata, &ltime ) ) != TNOERR ) ) ) || ((mode == MODE_SSV) && (!rootdata || !tsrootdata || ((result = pTaggantCheckCertificate(rootdata)) != TNOERR) || ((result = pTaggantCheckCertificate(tsrootdata)) != TNOERR) ) ) || ((result = pTaggantContextNewEx(pcontext)) != TNOERR) ) { return result; } /* FILE* is not portable across module boundaries */ (*pcontext)->FileReadCallBack = my_fread; (*pcontext)->FileSeekCallBack = my_fseek; (*pcontext)->FileTellCallBack = my_ftell; return ERR_NONE; } static int init_spv_library(_In_ const char *dllname, _Out_writes_(1) HMODULE *plibspv, UNSIGNED64 reqver, _In_z_ const UNSIGNED8 *licdata, PTAGGANTCONTEXT *pcontext ) { int result; HMODULE libspv; if ((result = init_library(dllname, plibspv ) ) != ERR_NONE ) { return result; } if (((pTaggantGetLicenseExpirationDate = (UNSIGNED32 (STDCALL *) (const PVOID, UNSIGNED64 * ) ) GetProcAddress(libspv = *plibspv, "TaggantGetLicenseExpirationDate" ) ) == NULL ) || ((pTaggantAddHashRegion = (UNSIGNED32 (STDCALL *) (PTAGGANTOBJ, UNSIGNED64, UNSIGNED64 ) ) GetProcAddress(libspv, "TaggantAddHashRegion" ) ) == NULL ) || ((pTaggantComputeHashes = (UNSIGNED32 (STDCALL *) (PTAGGANTCONTEXT, PTAGGANTOBJ, PFILEOBJECT, UNSIGNED64, UNSIGNED64, UNSIGNED32 ) ) GetProcAddress(libspv, "TaggantComputeHashes" ) ) == NULL ) || ((pTaggantPutInfo = (UNSIGNED32 (STDCALL *) (PTAGGANTOBJ, ENUMTAGINFO, UNSIGNED16, PINFO ) ) GetProcAddress(libspv, "TaggantPutInfo" ) ) == NULL ) || ((pTaggantPutTimestamp = (UNSIGNED32 (STDCALL *) (PTAGGANTOBJ, const char *, UNSIGNED32 ) ) GetProcAddress(libspv, "TaggantPutTimestamp" ) ) == NULL ) || ((pTaggantPrepare = (UNSIGNED32 (STDCALL *) (PTAGGANTOBJ, const PVOID, PVOID, UNSIGNED32 * ) ) GetProcAddress(libspv, "TaggantPrepare" ) ) == NULL ) ) { return ERR_BADLIB; } return init_post_library(MODE_SPV, reqver, licdata, NULL, NULL, pcontext ); } static int init_ssv_library(_In_z_ const char *dllname, _Outptr_result_maybenull_ HMODULE *plibssv, UNSIGNED64 reqver, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata, _Inout_ PTAGGANTCONTEXT *pcontext ) { int result; HMODULE libssv; if ((result = init_library(dllname, plibssv ) ) != ERR_NONE ) { return result; } if (((pTaggantCheckCertificate = (UNSIGNED32 (STDCALL *) (const PVOID)) GetProcAddress(libssv = *plibssv, "TaggantCheckCertificate" ) ) == NULL ) || ((pTaggantGetTaggant = (UNSIGNED32 (STDCALL *) (PTAGGANTCONTEXT, PFILEOBJECT, TAGGANTCONTAINER, PTAGGANT * ) ) GetProcAddress(libssv, "TaggantGetTaggant" ) ) == NULL ) || ((pTaggantValidateSignature = (UNSIGNED32 (STDCALL *) (PTAGGANTOBJ, PTAGGANT, const PVOID ) ) GetProcAddress(libssv, "TaggantValidateSignature" ) ) == NULL ) || ((pTaggantGetTimestamp = (UNSIGNED32 (STDCALL *) (PTAGGANTOBJ, UNSIGNED64 *, const PVOID ) ) GetProcAddress(libssv, "TaggantGetTimestamp" ) ) == NULL ) || ((pTaggantGetHashMapDoubles = (UNSIGNED16 (STDCALL *) (PTAGGANTOBJ, PHASHBLOB_HASHMAP_DOUBLE * ) ) GetProcAddress(libssv, "TaggantGetHashMapDoubles" ) ) == NULL ) || ((pTaggantValidateHashMap = (UNSIGNED32 (STDCALL *) (PTAGGANTCONTEXT, PTAGGANTOBJ, PFILEOBJECT ) ) GetProcAddress(libssv, "TaggantValidateHashMap" ) ) == NULL ) || ((pTaggantGetInfo = (UNSIGNED32 (STDCALL *) (PTAGGANTOBJ, ENUMTAGINFO, UNSIGNED32 *, PINFO ) ) GetProcAddress(libssv, "TaggantGetInfo" ) ) == NULL ) || ((pTaggantValidateDefaultHashes = (UNSIGNED32 (STDCALL *) (PTAGGANTCONTEXT, PTAGGANTOBJ, PFILEOBJECT, UNSIGNED64, UNSIGNED64 ) ) GetProcAddress(libssv, "TaggantValidateDefaultHashes" ) ) == NULL ) || ((pTaggantFreeTaggant = (UNSIGNED32 (STDCALL *) (PTAGGANT)) GetProcAddress(libssv, "TaggantFreeTaggant" ) ) == NULL ) ) { return ERR_BADLIB; } return init_post_library(MODE_SSV, reqver, NULL, rootdata, tsrootdata, pcontext ); } static int create_tmp_file(_In_z_ const char *filename, _In_reads_(tmpfile_len) const UNSIGNED8 *tmpfile, UNSIGNED64 tmpfile_len ) { int result; FILE *tagfile; result = ERR_BADOPEN; if (!fopen_s(&tagfile, filename, "wb+" ) && tagfile ) { result = ERR_NONE; if (fwrite(tmpfile, 1, (size_t) tmpfile_len, tagfile ) != tmpfile_len ) { result = ERR_BADFILE; } fclose(tagfile); } return result; } static int read_tmp_file(_In_ const char *filename, UNSIGNED8 **ptmpfile, UNSIGNED64 *ptmpfile_len ) { int result; FILE *tagfile; UNSIGNED8 *tmpfile; UNSIGNED64 tmpfile_len; result = ERR_BADOPEN; if (!fopen_s(&tagfile, filename, "rb" ) && tagfile ) { result = ERR_BADFILE; if (!fseek(tagfile, 0, SEEK_END ) && ((tmpfile_len = ftell(tagfile)) != -1) ) { result = ERR_NOMEM; if ((tmpfile = *ptmpfile = (UNSIGNED8 *) malloc((size_t) (*ptmpfile_len = tmpfile_len))) != NULL) { result = ERR_NONE; if (fseek(tagfile, 0, SEEK_SET ) || (fread(tmpfile, 1, (size_t) tmpfile_len, tagfile ) != (size_t) tmpfile_len ) ) { free(tmpfile); result = ERR_BADFILE; } } } fclose(tagfile); } return result; } static int erase_v1_taggant(_In_z_ const char *filename, UNSIGNED8 **ppefile, _Out_writes_(1) UNSIGNED64 *ppefile_len, UNSIGNED32 *ptag_len ) { int result; UNSIGNED64 peobj_len; UNSIGNED64 tag_off; if ((result = read_tmp_file(filename, ppefile, ppefile_len ) ) == ERR_NONE ) { if ((result = object_sizes(*ppefile, *ppefile_len, &peobj_len, &tag_off, ptag_len ) ) != ERR_NONE ) { free(*ppefile); } else { memset(*ppefile + tag_off, 0, *ptag_len - sizeof(TAGGANT_MARKER_END) ); } } return result; } static int append_file(_In_z_ const char *filename, _In_reads_(tmpfile_len) const UNSIGNED8 *tmpfile, UNSIGNED64 tmpfile_len ) { int result; FILE *tagfile; if ((result = create_tmp_file(filename, tmpfile, tmpfile_len ) ) == ERR_NONE ) { result = ERR_BADFILE; if (!fopen_s(&tagfile, filename, "a" ) && tagfile ) { if (fwrite(&result, 1, 1, tagfile ) == 1 ) { result = ERR_NONE; } fclose(tagfile); } } return result; } static int add_hashmap(_In_ FILE *tagfile, _In_ PTAGGANTOBJ object, int badhash ) { int result; UNSIGNED8 lfanew[4]; UNSIGNED8 opthdrsize[2]; result = ERR_BADFILE; if (!fseek(tagfile, offsetof(IMAGE_DOS_HEADER, e_lfanew ), SEEK_SET ) && (fread(lfanew, 1, sizeof(lfanew), tagfile ) == sizeof(lfanew) ) && !fseek(tagfile, read_le32(lfanew) + offsetof(IMAGE_NT_HEADERS32, FileHeader ) + offsetof(IMAGE_FILE_HEADER, SizeOfOptionalHeader ), SEEK_SET ) && (fread(opthdrsize, 1, sizeof(opthdrsize), tagfile ) == sizeof(opthdrsize) ) ) { if ((result = pTaggantAddHashRegion(object, offsetof(IMAGE_DOS_HEADER, e_lfanew ), sizeof(lfanew) ) ) == TNOERR ) { result = pTaggantAddHashRegion(object, read_le32(lfanew), badhash ? 0 : (offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + read_le16(opthdrsize) ) ); } } return result; } static int create_taggant(_In_z_ const char *filename, _In_ const PTAGGANTCONTEXT context, UNSIGNED64 version, TAGGANTCONTAINER tagtype, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len, int hashmap, int badhash, int puttime, int filleb ) { int result; FILE *tagfile; PTAGGANTOBJ object; result = ERR_BADFILE; if (!fopen_s(&tagfile, filename, "rb+" ) && tagfile ) { object = NULL; if ((result = pTaggantObjectNewEx(NULL, version, tagtype, &object ) ) == TNOERR ) { PPACKERINFO packer_info; UNSIGNED8 *taggant; if (hashmap) { result = add_hashmap(tagfile, object, badhash ); } if ((result == ERR_NONE) && filleb ) { PINFO buffer; result = ERR_NOMEM; if ((buffer = (PINFO) malloc(0x10000 - 5)) != NULL) { memset(buffer, 0xdd, 0x10000 - 5 ); result = pTaggantPutInfo(object, ECONTRIBUTORLIST, 0x10000 - 5, buffer ); free(buffer); } } if ((result == ERR_NONE) && ((result = pTaggantComputeHashes(context, object, (PFILEOBJECT) tagfile, peobj_len, file_len, tag_len ) ) == TNOERR ) ) { packer_info = pTaggantPackerInfo(object); packer_info->PackerId = PACKER_ID; packer_info->VersionMajor = PACKER_MAJOR; packer_info->VersionMinor = PACKER_MINOR; packer_info->VersionBuild = PACKER_BUILD; packer_info->Reserved = 0; if (puttime && ((result = pTaggantPutTimestamp(object, "http://taggant-tsa.ieee.org/", 50 ) ) != TNOERR ) ) { print_tagerr(result); } else { if (!tag_len) { tag_len = TAGGANT_MINIMUM_SIZE; } result = ERR_NOMEM; if ((taggant = (UNSIGNED8 *) malloc(tag_len)) != NULL) { if (((result = pTaggantPrepare(object, licdata, taggant, &tag_len ) ) == TINSUFFICIENTBUFFER ) && (version != TAGGANT_LIBRARY_VERSION1) ) { UNSIGNED8 *tmpbuff; result = ERR_NOMEM; if ((tmpbuff = (UNSIGNED8 *) realloc(taggant, tag_len ) ) != NULL ) { result = pTaggantPrepare(object, licdata, taggant = tmpbuff, &tag_len ); } } if (result == ERR_NONE) { result = ERR_BADFILE; if (!fseek(tagfile, (long) tag_off, (version == TAGGANT_LIBRARY_VERSION1) ? SEEK_SET : SEEK_END ) && (fwrite(taggant, 1, tag_len, tagfile ) == tag_len ) ) { result = ERR_NONE; } } free(taggant); } } } pTaggantObjectFree(object); } fclose(tagfile); } return result; } static int create_v1_taggant(_In_z_ const char *filename, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len, int hashmap, int badhash, int puttime ) { return create_taggant(filename, context, TAGGANT_LIBRARY_VERSION1, TAGGANT_PEFILE, licdata, peobj_len, file_len, tag_off, tag_len, hashmap, badhash, puttime, FALSE ); } static int create_v1_v1_taggant(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 file_len, int puttime ) { int result; const UNSIGNED8 *tmpfile; UNSIGNED64 pefile_len; if ((result = read_tmp_file(filename1, (UNSIGNED8 **) &tmpfile, &pefile_len ) ) == ERR_NONE ) { UNSIGNED64 peobj_len; UNSIGNED64 tag_off; UNSIGNED32 tag_len; if (((result = object_sizes(tmpfile, pefile_len, &peobj_len, &tag_off, &tag_len ) ) == ERR_NONE ) && ((result = create_tmp_file(filename2, tmpfile, pefile_len ) ) == ERR_NONE ) ) { result = create_v1_taggant(filename2, context, licdata, peobj_len, file_len, tag_off, tag_len, FALSE, FALSE, puttime ); } free((PVOID) tmpfile); } return result; } static int create_v2_taggant(_In_z_ const char *filename, _In_ const PTAGGANTCONTEXT context, TAGGANTCONTAINER tagtype, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 file_len, int hashmap, int badhash, int puttime, int filleb ) { return create_taggant(filename, context, TAGGANT_LIBRARY_VERSION2, tagtype, licdata, peobj_len, file_len, 0, 0, hashmap, badhash, puttime, filleb ); } static int create_v2_taggant_taggant(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context, TAGGANTCONTAINER tagtype, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, int puttime, int filleb ) { int result; const UNSIGNED8 *tmpfile; UNSIGNED64 pefile_len; if ((result = read_tmp_file(filename1, (UNSIGNED8 **) &tmpfile, &pefile_len ) ) == ERR_NONE ) { if ((result = create_tmp_file(filename2, tmpfile, pefile_len ) ) == ERR_NONE ) { result = create_v2_taggant(filename2, context, tagtype, licdata, peobj_len, 0, FALSE, FALSE, puttime, filleb ); } free((PVOID) tmpfile); } return result; } static int create_tmp_v1_taggant(_In_z_ const char *filename, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len, int hashmap, int puttime ) { int result; if ((result = create_tmp_file(filename, pefile, pefile_len ) ) == ERR_NONE ) { result = create_v1_taggant(filename, context, licdata, peobj_len, file_len, tag_off, tag_len, hashmap, FALSE, puttime ); } return result; } static int create_tmp_v1_v2_taggant(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off, int puttime ) { int result; UNSIGNED8 *tmpfile; UNSIGNED64 tmpfile_len; UNSIGNED32 tag_len; if ((result = erase_v1_taggant(filename1, &tmpfile, &tmpfile_len, &tag_len ) ) == ERR_NONE ) { if (((result = create_tmp_file(filename2, tmpfile, tmpfile_len ) ) == ERR_NONE ) && ((result = create_v2_taggant(filename2, context, TAGGANT_PEFILE, licdata, peobj_len, 0, FALSE, FALSE, puttime, FALSE ) ) == ERR_NONE ) ) { result = create_v1_taggant(filename2, context, licdata, peobj_len, 0, tag_off, tag_len, FALSE, FALSE, puttime ); } free(tmpfile); } return result; } static int append_v1_taggant(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; unsigned char *tmpfile; UNSIGNED64 tmpfile_len; UNSIGNED32 tag_len; if ((result = erase_v1_taggant(filename1, &tmpfile, &tmpfile_len, &tag_len ) ) == ERR_NONE ) { if ((result = append_file(filename2, tmpfile, tmpfile_len ) ) == ERR_NONE ) { result = create_v1_taggant(filename2, context, licdata, peobj_len, tmpfile_len, tag_off, tag_len, FALSE, FALSE, FALSE ); } free(tmpfile); } return result; } static int append_v1_v2_taggant(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; UNSIGNED8 *tmpfile; UNSIGNED64 tmpfile_len; UNSIGNED32 tag_len; if ((result = erase_v1_taggant(filename1, &tmpfile, &tmpfile_len, &tag_len ) ) == ERR_NONE ) { if (((result = append_file(filename2, tmpfile, tmpfile_len ) ) == ERR_NONE ) && ((result = create_v2_taggant(filename2, context, TAGGANT_PEFILE, licdata, peobj_len, tmpfile_len, FALSE, FALSE, FALSE, FALSE ) ) == ERR_NONE ) ) { result = create_v1_taggant(filename2, context, licdata, peobj_len, 0, tag_off, tag_len, FALSE, FALSE, FALSE ); } free(tmpfile); } return result; } static int create_tampered_v1_image(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_z_ const char *filename3, const PTAGGANTCONTEXT context, const UNSIGNED8 *licdata, int tamper1, int tamper2 ) { int result; unsigned char *tmpfile; UNSIGNED64 tmpfile_len; UNSIGNED64 peobj_len; UNSIGNED64 tag_off; UNSIGNED32 tag_len; if ((result = read_tmp_file(filename1, &tmpfile, &tmpfile_len ) ) == ERR_NONE ) { if ((result = object_sizes(tmpfile, tmpfile_len, &peobj_len, &tag_off, &tag_len ) ) == ERR_NONE ) { tmpfile[tag_off + 0x100] += (unsigned char) tamper1; tmpfile[2] += (unsigned char) tamper2; if ((result = create_tmp_file(filename2, tmpfile, tmpfile_len ) ) == ERR_NONE ) { result = create_v1_v1_taggant(filename2, filename3, context, licdata, FALSE, FALSE ); } } free(tmpfile); } return result; } static int create_tampered_v1_v2_image(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_z_ const char *filename3, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off, int badhash, UNSIGNED64 tamper_off ) { int result; UNSIGNED8 *tmpfile1; UNSIGNED64 tmpfile1_len; UNSIGNED32 tag_len; if (((result = erase_v1_taggant(filename1, &tmpfile1, &tmpfile1_len, &tag_len ) ) == ERR_NONE ) ) { UNSIGNED8 *tmpfile2; UNSIGNED64 tmpfile2_len; if (((result = create_tmp_file(filename2, tmpfile1, tmpfile1_len ) ) == ERR_NONE ) && ((result = create_v2_taggant(filename2, context, TAGGANT_PEFILE, licdata, peobj_len, 0, badhash, badhash, FALSE, FALSE ) ) == ERR_NONE ) && ((result = read_tmp_file(filename2, &tmpfile2, &tmpfile2_len ) ) == ERR_NONE ) ) { if (!badhash) { if ((SIGNED64) tamper_off < 0) { tamper_off += tmpfile2_len; } ++tmpfile2[tamper_off]; } if ((result = create_tmp_file(filename3, tmpfile2, tmpfile2_len ) ) == ERR_NONE ) { result = create_v1_taggant(filename3, context, licdata, peobj_len, 0, tag_off, tag_len, FALSE, FALSE, FALSE ); } free(tmpfile2); } free(tmpfile1); } return result; } static int create_bad_v1_hmh(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; if ((result = create_tmp_file(filename1, pefile, pefile_len ) ) == ERR_NONE ) { if ((result = create_v1_taggant(filename1, context, licdata, peobj_len, file_len, tag_off, tag_len, TRUE, TRUE, FALSE ) ) == ERR_NONE ) { result = create_v1_v1_taggant(filename1, filename2, context, licdata, FALSE, FALSE ); } } return result; } static int create_tmp_v2_taggant(_In_z_ const char *filename, _In_ const PTAGGANTCONTEXT context, TAGGANTCONTAINER tagtype, _In_z_ const UNSIGNED8 *licdata, _In_reads_(tmpfile_len) const UNSIGNED8 *tmpfile, UNSIGNED64 peobj_len, UNSIGNED64 tmpfile_len, int hashmap, int puttime ) { int result; if ((result = create_tmp_file(filename, tmpfile, tmpfile_len ) ) == ERR_NONE ) { result = create_v2_taggant(filename, context, tagtype, licdata, peobj_len, (tagtype == TAGGANT_PEFILE) ? 0 : tmpfile_len, hashmap, FALSE, puttime, FALSE ); } return result; } static int append_v2_taggant(_In_z_ const char *filename, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; if ((result = append_file(filename, pefile, pefile_len ) ) == ERR_NONE ) { result = create_v2_taggant(filename, context, TAGGANT_PEFILE, licdata, peobj_len, pefile_len, FALSE, FALSE, FALSE, FALSE ); } return result; } static int create_tampered_v2_image(_In_z_ const char *filename1, _In_z_ const char *filename2, const char *filename3, const PTAGGANTCONTEXT context, const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, int tamper1, int tamper2, int csamode ) { int result; unsigned char *tmpfile; UNSIGNED64 tmpfile_len; if ((result = read_tmp_file(filename1, &tmpfile, &tmpfile_len ) ) == ERR_NONE ) { tmpfile[tmpfile_len - 0x100] += (unsigned char) tamper1; tmpfile[2] += (unsigned char) tamper2; if (((result = create_tmp_file(filename2, tmpfile, tmpfile_len ) ) == ERR_NONE ) && csamode ) { result = create_v2_taggant_taggant(filename2, filename3, context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); } free(tmpfile); } return result; } static int create_bad_v2_hmh(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { return create_v2_taggant_taggant(filename1, filename2, context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); } static int duplicate_tag(_In_z_ const char *filename, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 pefile_len ) { int result; unsigned int size; char buffer[max(sizeof(TESTSTRING1), sizeof(TESTSTRING2))]; PTAGGANTOBJ object; object = NULL; size = sizeof(buffer); if (((result = pTaggantObjectNewEx(NULL, TAGGANT_LIBRARY_VERSION2, TAGGANT_PEFILE, &object ) ) == TNOERR ) && ((result = pTaggantPutInfo(object, ECONTRIBUTORLIST, sizeof(TESTSTRING1), TESTSTRING1 ) ) == TNOERR ) && ((result = pTaggantPutInfo(object, ECONTRIBUTORLIST, sizeof(TESTSTRING2), TESTSTRING2 ) ) == TNOERR ) ) { FILE *tagfile; UNSIGNED32 tag_len; UNSIGNED8 *taggant; result = ERR_BADFILE; if (!fopen_s(&tagfile, filename, "wb+" ) && tagfile ) { if (fwrite(pefile, 1, (size_t) pefile_len, tagfile ) == pefile_len ) { result = ERR_NOMEM; if ((taggant = (UNSIGNED8 *) malloc(tag_len = TAGGANT_MINIMUM_SIZE)) != NULL) { if ((result = pTaggantPrepare(object, licdata, taggant, &tag_len ) ) != TNOERR ) { if (result == TINSUFFICIENTBUFFER) { UNSIGNED8 *tmpbuff; result = ERR_NOMEM; if ((tmpbuff = (UNSIGNED8 *) realloc(taggant, tag_len ) ) != NULL ) { result = pTaggantPrepare(object, licdata, taggant = tmpbuff, &tag_len ); } } } if ((result == ERR_NONE) && (fwrite(taggant, 1, tag_len, tagfile ) != tag_len ) ) { result = ERR_BADFILE; } free(taggant); } } fclose(tagfile); } } pTaggantObjectFree(object); return result; } static int create_ds(_In_z_ const char *filename1, _In_z_ const char *filename2, int mode64 ) { int result; UNSIGNED8 *tmpfile; UNSIGNED64 tmpfile_len; if ((result = read_tmp_file(filename1, &tmpfile, &tmpfile_len ) ) == ERR_NONE ) { PIMAGE_DATA_DIRECTORY secdir; secdir = (PIMAGE_DATA_DIRECTORY) (tmpfile + read_le32(tmpfile + offsetof(IMAGE_DOS_HEADER, e_lfanew ) ) + (mode64 ? (offsetof(IMAGE_NT_HEADERS64, OptionalHeader ) + offsetof(IMAGE_OPTIONAL_HEADER64, DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY] ) ) : (offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + offsetof(IMAGE_OPTIONAL_HEADER32, DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY] ) ) ) ); secdir->VirtualAddress = (DWORD) tmpfile_len; secdir->Size = 1; result = append_file(filename2, tmpfile, tmpfile_len ); free(tmpfile); } return result; } static int create_eof(_In_z_ const char *filename, _In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; UNSIGNED8 *tmpfile; UNSIGNED64 tmpfile_len; result = ERR_NOMEM; if ((tmpfile = (UNSIGNED8 *) malloc((size_t) pefile_len)) != NULL) { UNSIGNED8 *tagptr; UNSIGNED32 lfanew; lfanew = read_le32(pefile + offsetof(IMAGE_DOS_HEADER, e_lfanew ) ); tagptr = (UNSIGNED8 *) memcpy(tmpfile, pefile, (size_t) pefile_len ) + virttophys(pefile_len, (IMAGE_SECTION_HEADER *) (pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + read_le16(pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, FileHeader ) + offsetof(IMAGE_FILE_HEADER, SizeOfOptionalHeader ) ) ), read_le16(pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, FileHeader ) + offsetof(IMAGE_FILE_HEADER, NumberOfSections ) ), read_le32(pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + offsetof(IMAGE_OPTIONAL_HEADER32, AddressOfEntryPoint ) ), read_le32(pefile + lfanew + offsetof(IMAGE_NT_HEADERS32, OptionalHeader ) + offsetof(IMAGE_OPTIONAL_HEADER32, FileAlignment ) ), &peobj_len ); tagptr[2] = (UNSIGNED8) (tmpfile_len = pefile_len + TAGGANT_MINIMUM_SIZE); tagptr[3] = (UNSIGNED8) (tmpfile_len >> 8); tagptr[4] = (UNSIGNED8) (tmpfile_len >> 16); tagptr[5] = (UNSIGNED8) (tmpfile_len >> 24); result = append_v2_taggant(filename, context, licdata, tmpfile, peobj_len, pefile_len ); free(tmpfile); if ((result == ERR_NONE) && ((result = read_tmp_file(filename, &tmpfile, &tmpfile_len ) ) == ERR_NONE ) ) { UNSIGNED8 *tmpbuff; result = ERR_NOMEM; if ((tmpbuff = (UNSIGNED8 *) realloc(tmpfile, (size_t) pefile_len + TAGGANT_MINIMUM_SIZE ) ) != NULL ) { UNSIGNED32 taglen; taglen = read_le32(tmpbuff + tmpfile_len - (sizeof(TAGGANT_HEADER2) - offsetof(TAGGANT_HEADER2, TaggantLength ) ) ); tmpfile = tmpbuff; memmove(tmpfile + pefile_len + TAGGANT_MINIMUM_SIZE - taglen, tmpfile + tmpfile_len - taglen, taglen ); memset(tmpfile + pefile_len, 0, TAGGANT_MINIMUM_SIZE - taglen ); result = create_tmp_v1_taggant(filename, context, licdata, tmpfile, peobj_len, pefile_len + TAGGANT_MINIMUM_SIZE, pefile_len + TAGGANT_MINIMUM_SIZE, pefile_len + TAGGANT_MINIMUM_SIZE, 0, FALSE, FALSE ); } free(tmpfile); } } return result; } static int test_spv_v101(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test01: add v1 Taggant to 32-bit PE file containing no Taggant and no overlay:"); result = create_tmp_v1_taggant("v1test01", context, licdata, pefile, peobj_len, pefile_len, file_len, tag_off, tag_len, FALSE, TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v102(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v1test02: add v1 Taggant to 32-bit PE file containing v1 Taggant and no overlay:"); result = create_v1_v1_taggant("v1test01", "v1test02", context, licdata, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v103(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test03: add v1 Taggant to 32-bit PE file containing v2 Taggant and no overlay:"); result = create_tmp_v1_v2_taggant("v1test01", "v1test03", context, licdata, peobj_len, tag_off, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v104(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test04: add v1 Taggant to 64-bit PE file containing no Taggant and no overlay:"); result = create_tmp_v1_taggant("v1test04", context, licdata, pefile, peobj_len, pefile_len, file_len, tag_off, tag_len, FALSE, TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v105(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v1test05: add v1 Taggant to 64-bit PE file containing v1 Taggant and no overlay:"); result = create_v1_v1_taggant("v1test04", "v1test05", context, licdata, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v106(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test06: add v1 Taggant to 64-bit PE file containing v2 Taggant and no overlay:"); result = create_tmp_v1_v2_taggant("v1test04", "v1test06", context, licdata, peobj_len, tag_off, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v107(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test07: add v1 Taggant to 32-bit PE file containing no Taggant and overlay:"); result = append_v1_taggant("v1test01", "v1test07", context, licdata, peobj_len, tag_off ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v108(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v1test08: add v1 Taggant to 32-bit PE file containing v1 Taggant and overlay:"); result = create_v1_v1_taggant("v1test07", "v1test08", context, licdata, pefile_len, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v109(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test09: add v1 Taggant to 32-bit PE file containing v2 Taggant and overlay:"); result = append_v1_v2_taggant("v1test01", "v1test09", context, licdata, peobj_len, tag_off ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v110(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test10: add v1 Taggant to 64-bit PE file containing no Taggant and overlay:"); result = append_v1_taggant("v1test04", "v1test10", context, licdata, peobj_len, tag_off ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v111(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v1test11: add v1 Taggant to 64-bit PE file containing v1 Taggant and overlay:"); result = create_v1_v1_taggant("v1test10", "v1test11", context, licdata, pefile_len, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v112(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test12: add v1 Taggant to 64-bit PE file containing v2 Taggant and overlay:"); result = append_v1_v2_taggant("v1test04", "v1test12", context, licdata, peobj_len, tag_off ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v113(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v1test13: add v1 Taggant to 32-bit PE file containing tampered v1 Taggant:"); result = create_tampered_v1_image("v1test01", "v1tampered1_32", "v1test13", context, licdata, 1, 0 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v114(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test14: add v1 Taggant to 32-bit PE file containing tampered v2 Taggant:"); result = create_tampered_v1_v2_image("v1test01", "v1test14", "v1test14", context, licdata, peobj_len, tag_off, FALSE, (UNSIGNED64) -0x100 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v115(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v1test15: add v1 Taggant to 64-bit PE file containing tampered v1 Taggant:"); result = create_tampered_v1_image("v1test04", "v1tampered1_64", "v1test15", context, licdata, 1, 0 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v116(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test16: add v1 Taggant to 64-bit PE file containing tampered v2 Taggant:"); result = create_tampered_v1_v2_image("v1test04", "v1test16", "v1test16", context, licdata, peobj_len, tag_off, FALSE, (UNSIGNED64) -0x100 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v117(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v1test17: add v1 Taggant to 32-bit PE file containing good v1 Taggant and tampered image:"); result = create_tampered_v1_image("v1tampered1_32", "v1tampered2_32", "v1test17", context, licdata, -1, 1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v118(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test18: add v1 Taggant to 32-bit PE file containing good v2 Taggant and tampered image:"); result = create_tampered_v1_v2_image("v1test01", "v1test18", "v1test18", context, licdata, peobj_len, tag_off, FALSE, 2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v119(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v1test19: add v1 Taggant to 64-bit PE file containing good v1 Taggant and tampered image:"); result = create_tampered_v1_image("v1tampered1_64", "v1tampered2_64", "v1test19", context, licdata, -1, 1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v120(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test20: add v1 Taggant to 64-bit PE file containing good v2 Taggant and tampered image:"); result = create_tampered_v1_v2_image("v1test04", "v1test20", "v1test20", context, licdata, peobj_len, tag_off, FALSE, 2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v121(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test21: add v1 Taggant HashMap to 32-bit PE file containing no Taggant:"); result = create_tmp_v1_taggant("v1test21", context, licdata, pefile, peobj_len, pefile_len, file_len, tag_off, tag_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v122(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test22: add v1 Taggant HashMap to 64-bit PE file containing no Taggant:"); result = create_tmp_v1_taggant("v1test22", context, licdata, pefile, peobj_len, pefile_len, file_len, tag_off, tag_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v123(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test23: add v1 Taggant to 32-bit PE file containing good v1 Taggant and broken HMH and good image:"); result = create_bad_v1_hmh("v1badhmh_32", "v1test23", context, licdata, pefile, peobj_len, pefile_len, file_len, tag_off, tag_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v124(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test24: add v1 Taggant to 32-bit PE file containing good v2 Taggant and broken HMH and good image:"); result = create_tampered_v1_v2_image("v1test01", "v2badhmh_32", "v1test24", context, licdata, peobj_len, tag_off, TRUE, 0 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v125(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test25: add v1 Taggant to 64-bit PE file containing good v1 Taggant and broken HMH and good image:"); result = create_bad_v1_hmh("v1badhmh_64", "v1test25", context, licdata, pefile, peobj_len, pefile_len, file_len, tag_off, tag_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v126(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len, UNSIGNED64 tag_off ) { int result; printf(PR_WIDTH, "v1test26: add v1 Taggant to 64-bit PE file containing good v2 Taggant and broken HMH and good image:"); result = create_tampered_v1_v2_image("v1test04", "v2badhmh_64", "v1test26", context, licdata, peobj_len, tag_off, TRUE, 0 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v127(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test27: add v1 Taggant without timestamp to 32-bit PE file:"); result = create_tmp_v1_taggant("v1test27", context, licdata, pefile, peobj_len, pefile_len, file_len, tag_off, tag_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v128(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v1test28: add v1 Taggant with timestamp to 32-bit PE file containing v1 Taggant without timestamp:"); result = create_v1_v1_taggant("v1test27", "v1test28", context, licdata, FALSE, TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v129(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test29: add v1 Taggant with timestamp to 32-bit PE file containing v2 Taggant without timestamp:"); if ((result = create_tmp_v2_taggant("v1test29", context, TAGGANT_PEFILE, licdata, pefile, peobj_len, pefile_len, FALSE, FALSE ) ) == ERR_NONE ) { result = create_v1_taggant("v1test29", context, licdata, peobj_len, pefile_len, tag_off, tag_len, FALSE, FALSE, TRUE ); } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v130(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 file_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test30: add v1 Taggant without timestamp to 64-bit PE file:"); result = create_tmp_v1_taggant("v1test30", context, licdata, pefile, peobj_len, pefile_len, file_len, tag_off, tag_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v131(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v1test31: add v1 Taggant with timestamp to 64-bit PE file containing v1 Taggant without timestamp:"); result = create_v1_v1_taggant("v1test30", "v1test31", context, licdata, FALSE, TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v132(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len, UNSIGNED64 tag_off, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "v1test32: add v1 Taggant with timestamp to 64-bit PE file containing v2 Taggant without timestamp:"); if ((result = create_tmp_v2_taggant("v1test32", context, TAGGANT_PEFILE, licdata, pefile, peobj_len, pefile_len, FALSE, FALSE ) ) == ERR_NONE ) { result = create_v1_taggant("v1test32", context, licdata, peobj_len, pefile_len, tag_off, tag_len, FALSE, FALSE, TRUE ); } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v133(void) { int result; PTAGGANTOBJ object; printf(PR_WIDTH, "v1test33: add data to v1 ExtraBlob:"); object = NULL; if ((result = pTaggantObjectNewEx(NULL, TAGGANT_LIBRARY_VERSION1, TAGGANT_PEFILE, &object ) ) == TNOERR ) { result = pTaggantPutInfo(object, ECONTRIBUTORLIST, 1, (PINFO) &result /* anything */ ); pTaggantObjectFree(object); if (result == TNOERR) { result = ERR_BADLIB; } else if (result == TERRORKEY) { result = ERR_NONE; } } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v134(void) { int result; PTAGGANTOBJ object; printf(PR_WIDTH, "v1test34: add v1 Taggant to JS file:"); object = NULL; result = pTaggantObjectNewEx(NULL, TAGGANT_LIBRARY_VERSION1, TAGGANT_JSFILE, &object ); pTaggantObjectFree(object); if (result == TNOERR) { result = ERR_BADLIB; } else if (result == TTYPE) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v201(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test01: add v2 Taggant to 32-bit PE file containing no Taggant and no overlay:"); result = create_tmp_v2_taggant("v2test01", context, TAGGANT_PEFILE, licdata, pefile, peobj_len, pefile_len, FALSE, TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v202(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test02: add v2 Taggant to 32-bit PE file containing v1 Taggant and no overlay:"); result = create_v2_taggant_taggant("v1test01", "v2test02", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v203(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test03: add v2 Taggant to 32-bit PE file containing v2 Taggant and no overlay:"); result = create_v2_taggant_taggant("v2test01", "v2test03", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v204(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test04: add v2 Taggant to 32-bit PE file containing v2 Taggant and v1 Taggant and no overlay:"); result = create_v2_taggant_taggant("v2test02", "v2test04", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v205(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test05: add v2 Taggant to 64-bit PE file containing no Taggant and no overlay:"); result = create_tmp_v2_taggant("v2test05", context, TAGGANT_PEFILE, licdata, pefile, peobj_len, pefile_len, FALSE, TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v206(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test06: add v2 Taggant to 64-bit PE file containing v1 Taggant and no overlay:"); result = create_v2_taggant_taggant("v1test04", "v2test06", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v207(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test07: add v2 Taggant to 64-bit PE file containing v2 Taggant and no overlay:"); result = create_v2_taggant_taggant("v2test05", "v2test07", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v208(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test08: add v2 Taggant to 64-bit PE file containing v2 Taggant and v1 Taggant and no overlay:"); result = create_v2_taggant_taggant("v2test06", "v2test08", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v209(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test09: add v2 Taggant to 32-bit PE file containing no Taggant and overlay:"); result = append_v2_taggant("v2test09", context, licdata, pefile, peobj_len, pefile_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v210(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test10: add v2 Taggant to 32-bit PE file containing v1 Taggant and overlay:"); result = create_v2_taggant_taggant("v1test07", "v2test10", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v211(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test11: add v2 Taggant to 32-bit PE file containing v2 Taggant and overlay:"); result = create_v2_taggant_taggant("v2test09", "v2test11", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v212(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test12: add v2 Taggant to 32-bit PE file containing v2 Taggant and v1 Taggant and overlay:"); result = create_v2_taggant_taggant("v2test10", "v2test12", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v213(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test13: add v2 Taggant to 64-bit PE file containing no Taggant and overlay:"); result = append_v2_taggant("v2test13", context, licdata, pefile, peobj_len, pefile_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v214(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test14: add v2 Taggant to 64-bit PE file containing v1 Taggant and overlay:"); result = create_v2_taggant_taggant("v1test10", "v2test14", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v215(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test15: add v2 Taggant to 64-bit PE file containing v2 Taggant and overlay:"); result = create_v2_taggant_taggant("v2test13", "v2test15", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v216(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test16: add v2 Taggant to 64-bit PE file containing v2 Taggant and v1 Taggant and overlay:"); result = create_v2_taggant_taggant("v2test14", "v2test16", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } #if defined(CSA_MODE) static int test_spv_v217(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test17: add v2 Taggant to 32-bit PE file containing tampered v1 Taggant:"); if ((result = create_v2_taggant_taggant("v1tampered1_32", "v2test17", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } #endif static int test_spv_v218(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; #if defined(CSA_MODE) printf(PR_WIDTH, "v2test18: add v2 Taggant to 32-bit PE file containing tampered v2 Taggant:"); if ((result = create_tampered_v2_image("v2test01", "v2tampered1_32", "v2test18", context, licdata, peobj_len, 1, 0, FALSE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } #else UNREFERENCED_PARAMETER(context); UNREFERENCED_PARAMETER(licdata); UNREFERENCED_PARAMETER(peobj_len); printf(PR_WIDTH, "v2test18: create 32-bit PE file containing tampered v2 Taggant:"); result = create_tampered_v2_image("v2test01", "v2tampered1_32", NULL, NULL, NULL, 0, 1, 0, FALSE ); #endif if (result == ERR_NONE) { printf("pass\n"); } return result; } #if defined(CSA_MODE) static int test_spv_v219(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test19: add v2 Taggant to 64-bit PE file containing tampered v1 Taggant:"); if ((result = create_v2_taggant_taggant("v1tampered1_64", "v2test19", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } #endif static int test_spv_v220(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; #if defined(CSA_MODE) printf(PR_WIDTH, "v2test20: add v2 Taggant to 64-bit PE file containing tampered v2 Taggant:"); if ((result = create_tampered_v2_image("v2test05", "v2tampered1_64", "v2test20", context, licdata, peobj_len, 1, 0, FALSE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } #else UNREFERENCED_PARAMETER(context); UNREFERENCED_PARAMETER(licdata); UNREFERENCED_PARAMETER(peobj_len); printf(PR_WIDTH, "v2test20: create 64-bit PE file containing tampered v2 Taggant:"); result = create_tampered_v2_image("v2test05", "v2tampered1_64", NULL, NULL, NULL, 0, 1, 0, FALSE ); #endif if (result == ERR_NONE) { printf("pass\n"); } return result; } #if defined(CSA_MODE) static int test_spv_v221(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test21: add v2 Taggant to 32-bit PE file containing good v1 Taggant and tampered image:"); if ((result = create_v2_taggant_taggant("v1tampered2_32", "v2test21", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v222(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test22: add v2 Taggant to 32-bit PE file containing good v2 Taggant and tampered image:"); if ((result = create_tampered_v2_image("v2tampered1_32", "v2tampered2_32", "v2test22", context, licdata, peobj_len, -1, 1, FALSE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v223(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test23: add v2 Taggant to 64-bit PE file containing good v1 Taggant and tampered image:"); if ((result = create_v2_taggant_taggant("v1tampered2_64", "v2test23", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v224(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test24: add v2 Taggant to 64-bit PE file containing good v2 Taggant and tampered image:"); if ((result = create_tampered_v2_image("v2tampered1_64", "v2tampered2_64", "v2test24", context, licdata, peobj_len, -1, 1, FALSE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } #endif static int test_spv_v225(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test25: add v2 Taggant HashMap to 32-bit PE file containing no Taggant:"); result = create_tmp_v2_taggant("v2test25", context, TAGGANT_PEFILE, licdata, pefile, peobj_len, pefile_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v226(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test26: add v2 Taggant to 32-bit PE file containing v1 HashMap Taggant:"); result = create_v2_taggant_taggant("v1test21", "v2test26", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v227(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test27: add v2 Taggant to 32-bit PE file containing v2 HashMap Taggant:"); result = create_v2_taggant_taggant("v2test25", "v2test27", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v228(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test28: add v2 Taggant to 32-bit PE file containing v2 Taggant and v1 HashMap Taggant:"); result = create_v2_taggant_taggant("v2test26", "v2test28", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v229(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test29: add v2 Taggant HashMap to 64-bit PE file containing no Taggant:"); result = create_tmp_v2_taggant("v2test29", context, TAGGANT_PEFILE, licdata, pefile, peobj_len, pefile_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v230(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test30: add v2 Taggant to 64-bit PE file containing v1 HashMap Taggant:"); result = create_v2_taggant_taggant("v1test22", "v2test30", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v231(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test31: add v2 Taggant to 64-bit PE file containing v2 HashMap Taggant:"); result = create_v2_taggant_taggant("v2test29", "v2test31", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v232(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test32: add v2 Taggant to 64-bit PE file containing v2 Taggant and v1 HashMap Taggant:"); result = create_v2_taggant_taggant("v2test30", "v2test32", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } #if defined(CSA_MODE) static int test_spv_v233(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test33: add v2 Taggant to 32-bit PE file containing good v1 Taggant and broken HMH and good image:"); result = create_v2_taggant_taggant("v1badhmh_32", "v2test33", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v234(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test34: add v2 Taggant to 32-bit PE file containing good v2 Taggant and broken HMH and good image:"); result = create_bad_v2_hmh("v2badhmh_32", "v2test34", context, licdata, peobj_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v235(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test35: add v2 Taggant to 64-bit PE file containing good v1 Taggant and broken HMH and good image:"); result = create_v2_taggant_taggant("v1badhmh_64", "v2test35", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v236(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test36: add v2 Taggant to 64-bit PE file containing good v2 Taggant and broken HMH and good image:"); result = create_bad_v2_hmh("v2badhmh_64", "v2test36", context, licdata, peobj_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } #endif static int test_spv_v237(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test37: add v2 Taggant without timestamp to 32-bit PE file:"); result = create_tmp_v2_taggant("v2test37", context, TAGGANT_PEFILE, licdata, pefile, peobj_len, pefile_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v238(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test38: add v2 Taggant with timestamp to 32-bit PE file containing v1 Taggant without timestamp:"); result = create_v2_taggant_taggant("v1test27", "v2test38", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v239(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test39: add v2 Taggant with timestamp to 32-bit PE file containing v2 Taggant without timestamp:"); result = create_v2_taggant_taggant("v2test37", "v2test39", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v240(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test40: add v2 Taggant with timestamp to 32-bit PE file containing v2 Taggant with timestamp and v1 Taggant without timestamp:"); result = create_v2_taggant_taggant("v2test38", "v2test40", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v241(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test41: add v2 Taggant without timestamp to 32-bit PE file containing v1 Taggant with timestamp:"); result = create_v2_taggant_taggant("v1test01", "v2test41", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v242(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test42: add v2 Taggant without timestamp to 32-bit PE file containing v2 Taggant with timestamp:"); result = create_v2_taggant_taggant("v2test01", "v2test42", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v243(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test43: add v2 Taggant with timestamp to 32-bit PE file containing v2 Taggant without timestamp and v1 Taggant with timestamp:"); result = create_v2_taggant_taggant("v2test41", "v2test43", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v244(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test44: add v2 Taggant without timestamp to 64-bit PE file:"); result = create_tmp_v2_taggant("v2test44", context, TAGGANT_PEFILE, licdata, pefile, peobj_len, pefile_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v245(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test45: add v2 Taggant with timestamp to 64-bit PE file containing v1 Taggant without timestamp:"); result = create_v2_taggant_taggant("v1test30", "v2test45", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v246(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test46: add v2 Taggant with timestamp to 64-bit PE file containing v2 Taggant without timestamp:"); result = create_v2_taggant_taggant("v2test44", "v2test46", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v247(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test47: add v2 Taggant with timestamp to 64-bit PE file containing v2 Taggant with timestamp and v1 Taggant without timestamp:"); result = create_v2_taggant_taggant("v2test45", "v2test47", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v248(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test48: add v2 Taggant without timestamp to 64-bit PE file containing v1 Taggant with timestamp:"); result = create_v2_taggant_taggant("v1test04", "v2test48", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v249(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test49: add v2 Taggant without timestamp to 64-bit PE file containing v2 Taggant with timestamp:"); result = create_v2_taggant_taggant("v2test05", "v2test49", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v250(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test50: add v2 Taggant with timestamp to 64-bit PE file containing v2 Taggant without timestamp and v1 Taggant with timestamp:"); result = create_v2_taggant_taggant("v2test48", "v2test50", context, TAGGANT_PEFILE, licdata, peobj_len, TRUE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v251(_In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test51: add duplicated tag to 32-bit v2 ExtraBlob:"); result = duplicate_tag("v2test51", licdata, pefile, pefile_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v252(_In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test52: add duplicated tag to 64-bit v2 ExtraBlob:"); result = duplicate_tag("v2test52", licdata, pefile, pefile_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v253(void) { int result; char *buffer; PTAGGANTOBJ object; printf(PR_WIDTH, "v2test53: add single data of > 64kb to v2 ExtraBlob:"); if ((buffer = (char *) malloc(0xffff)) == NULL) { return TMEMORY; } object = NULL; if ((result = pTaggantObjectNewEx(NULL, TAGGANT_LIBRARY_VERSION2, TAGGANT_PEFILE, &object ) ) == TNOERR ) { result = pTaggantPutInfo(object, ECONTRIBUTORLIST, 0xffff, buffer ); pTaggantObjectFree(object); if (result == TNOERR) { result = ERR_BADLIB; } else if (result == TINSUFFICIENTBUFFER) { result = ERR_NONE; } } free(buffer); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v254(void) { int result; char *buffer; PTAGGANTOBJ object; printf(PR_WIDTH, "v2test54: add total data of > 64kb to v2 ExtraBlob:"); if ((buffer = (char *) malloc(0x10000)) == NULL) { return TMEMORY; } object = NULL; if (((result = pTaggantObjectNewEx(NULL, TAGGANT_LIBRARY_VERSION2, TAGGANT_PEFILE, &object ) ) == TNOERR ) && ((result = pTaggantPutInfo(object, (ENUMTAGINFO) 0x8000, (54 * 1024) - 4, buffer ) ) == ERR_NONE ) && ((result = pTaggantPutInfo(object, (ENUMTAGINFO) 0x8002, (4 * 1024) - 4, buffer ) ) == ERR_NONE ) ) { if ((result = pTaggantPutInfo(object, (ENUMTAGINFO) 0x8003, (10 * 1024) - 4, buffer ) ) == TNOERR ) { result = ERR_BADLIB; } else if (result == TINSUFFICIENTBUFFER) { result = ERR_NONE; } } pTaggantObjectFree(object); free(buffer); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v255(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test55: add v2 Taggant to 32-bit PE file containing v1 Taggant and full v2 ExtraBlob:"); if ((result = create_v2_taggant_taggant("v1test01", "v2test55", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, TRUE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TINSUFFICIENTBUFFER) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v256(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test56: add v2(a) Taggant to 32-bit PE file containing v2(b) Taggant and full v2(a) ExtraBlob:"); if ((result = create_v2_taggant_taggant("v2test01", "v2test56", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, TRUE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TINSUFFICIENTBUFFER) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v257(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test57: add v2 Taggant to 64-bit PE file containing v1 Taggant and full v2 ExtraBlob:"); if ((result = create_v2_taggant_taggant("v1test04", "v2test57", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, TRUE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TINSUFFICIENTBUFFER) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v258(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, UNSIGNED64 peobj_len ) { int result; printf(PR_WIDTH, "v2test58: add v2(a) Taggant to 64-bit PE file containing v2(b) Taggant and full v2(a) ExtraBlob:"); if ((result = create_v2_taggant_taggant("v2test05", "v2test58", context, TAGGANT_PEFILE, licdata, peobj_len, FALSE, TRUE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TINSUFFICIENTBUFFER) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v259(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(jsfile_len) const UNSIGNED8 *jsfile, UNSIGNED64 jsfile_len ) { int result; printf(PR_WIDTH, "v2test59: add v2 Taggant to JS file:"); result = create_tmp_v2_taggant("v2test59", context, TAGGANT_JSFILE, licdata, jsfile, 0, jsfile_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v260(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v2test60: add v2 Taggant to JS file containing v2 Taggant:"); result = create_v2_taggant_taggant("v2test59", "v2test60", context, TAGGANT_JSFILE, licdata, 0, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v261(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test61: add v2 JS Taggant to 32-bit PE file:"); result = create_tmp_v2_taggant("v2test61", context, TAGGANT_JSFILE, licdata, pefile, peobj_len, pefile_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v262(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v2test62: add v2 PE Taggant to 32-bit PE file containing v2 JS Taggant:"); result = create_v2_taggant_taggant("v2test61", "v2test62", context, TAGGANT_PEFILE, licdata, 0, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v263(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(jsfile_len) const UNSIGNED8 *jsfile, UNSIGNED64 jsfile_len ) { int result; printf(PR_WIDTH, "v2test63: add v2 PE Taggant to JS file:"); if ((result = create_tmp_v2_taggant("v2test63", context, TAGGANT_PEFILE, licdata, jsfile, 0, jsfile_len, FALSE, FALSE ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TINVALIDPEFILE) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v264(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(pefile_len) const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "v2test64: add v2 JS Taggant to 64-bit PE file:"); result = create_tmp_v2_taggant("v2test64", context, TAGGANT_JSFILE, licdata, pefile, peobj_len, pefile_len, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_v265(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata ) { int result; printf(PR_WIDTH, "v2test65: add v2 PE Taggant to 64-bit PE file containing v2 JS Taggant:"); result = create_v2_taggant_taggant("v2test64", "v2test65", context, TAGGANT_PEFILE, licdata, 0, FALSE, FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds01(void) { int result; printf(PR_WIDTH, "vdstest01: add DS to 32-bit PE file containing v1 Taggant:"); result = create_ds("v1test01", "vdstest01", FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds02(void) { int result; printf(PR_WIDTH, "vdstest02: add DS to 32-bit PE file containing v2 Taggant:"); result = create_ds("v2test01", "vdstest02", FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds03(void) { int result; printf(PR_WIDTH, "vdstest03: add DS to 32-bit PE file containing good v2 Taggant and good v1 Taggant:"); result = create_ds("v2test02", "vdstest03", FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds04(void) { int result; printf(PR_WIDTH, "vdstest04: add DS to 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant:"); result = create_ds("v2test03", "vdstest04", FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds05(void) { int result; printf(PR_WIDTH, "vdstest05: add DS to 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant:"); result = create_ds("v2test04", "vdstest05", FALSE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds06(void) { int result; printf(PR_WIDTH, "vdstest06: add DS to 64-bit PE file containing v1 Taggant:"); result = create_ds("v1test04", "vdstest06", TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds07(void) { int result; printf(PR_WIDTH, "vdstest07: add DS to 64-bit PE file containing v2 Taggant:"); result = create_ds("v2test32", "vdstest07", TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds08(void) { int result; printf(PR_WIDTH, "vdstest08: add DS to 64-bit PE file containing good v2 Taggant and good v1 Taggant:"); result = create_ds("v2test06", "vdstest08", TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds09(void) { int result; printf(PR_WIDTH, "vdstest09: add DS to 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant:"); result = create_ds("v2test07", "vdstest09", TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_ds10(void) { int result; printf(PR_WIDTH, "vdstest10: add DS to 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant:"); result = create_ds("v2test08", "vdstest10", TRUE ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_eof01(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_ const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "veoftest01: add v1 Taggant at EOF of 32-bit PE file containing v2 Taggant:"); result = create_eof("veoftest01", context, licdata, pefile, peobj_len, pefile_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_eof02(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_ const UNSIGNED8 *pefile, UNSIGNED64 peobj_len, UNSIGNED64 pefile_len ) { int result; printf(PR_WIDTH, "veoftest02: add v1 Taggant at EOF of 64-bit PE file containing v2 Taggant:"); result = create_eof("veoftest02", context, licdata, pefile, peobj_len, pefile_len ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_spv_pe(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_ const UNSIGNED8 *pefile32, UNSIGNED64 peobj32_len, UNSIGNED64 pefile32_len, UNSIGNED64 tag32_off, UNSIGNED32 tag32_len, _In_ const UNSIGNED8 *pefile64, UNSIGNED64 peobj64_len, UNSIGNED64 pefile64_len, UNSIGNED64 tag64_off, UNSIGNED32 tag64_len ) { int result; UNSIGNED64 file32_len; UNSIGNED64 file64_len; file32_len = tag32_len ? 0 : pefile32_len; file64_len = tag64_len ? 0 : pefile64_len; if (((result = test_spv_v101(context, licdata, pefile32, peobj32_len, pefile32_len, file32_len, tag32_off, tag32_len ) ) != ERR_NONE ) || ((result = test_spv_v102(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v103(context, licdata, peobj32_len, tag32_off ) ) != ERR_NONE ) || ((result = test_spv_v104(context, licdata, pefile64, peobj64_len, pefile64_len, file64_len, tag64_off, tag64_len ) ) != ERR_NONE ) || ((result = test_spv_v105(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v106(context, licdata, peobj64_len, tag64_off ) ) != ERR_NONE ) || ((result = test_spv_v107(context, licdata, peobj32_len, tag32_off ) ) != ERR_NONE ) || ((result = test_spv_v108(context, licdata, pefile32_len ) ) != ERR_NONE ) || ((result = test_spv_v109(context, licdata, peobj32_len, tag32_off ) ) != ERR_NONE ) || ((result = test_spv_v110(context, licdata, peobj64_len, tag64_off ) ) != ERR_NONE ) || ((result = test_spv_v111(context, licdata, pefile64_len ) ) != ERR_NONE ) || ((result = test_spv_v112(context, licdata, peobj64_len, tag64_off ) ) != ERR_NONE ) || ((result = test_spv_v113(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v114(context, licdata, peobj32_len, tag32_off ) ) != ERR_NONE ) || ((result = test_spv_v115(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v116(context, licdata, peobj64_len, tag64_off ) ) != ERR_NONE ) || ((result = test_spv_v117(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v118(context, licdata, peobj32_len, tag32_off ) ) != ERR_NONE ) || ((result = test_spv_v119(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v120(context, licdata, peobj64_len, tag64_off ) ) != ERR_NONE ) || ((result = test_spv_v121(context, licdata, pefile32, peobj32_len, pefile32_len, file32_len, tag32_off, tag32_len ) ) != ERR_NONE ) || ((result = test_spv_v122(context, licdata, pefile64, peobj64_len, pefile64_len, file64_len, tag64_off, tag64_len ) ) != ERR_NONE ) || ((result = test_spv_v123(context, licdata, pefile32, peobj32_len, pefile32_len, file32_len, tag32_off, tag32_len ) ) != ERR_NONE ) || ((result = test_spv_v124(context, licdata, peobj32_len, tag32_off ) ) != ERR_NONE ) || ((result = test_spv_v125(context, licdata, pefile64, peobj64_len, pefile64_len, file64_len, tag64_off, tag64_len ) ) != ERR_NONE ) || ((result = test_spv_v126(context, licdata, peobj64_len, tag64_off ) ) != ERR_NONE ) || ((result = test_spv_v127(context, licdata, pefile32, peobj32_len, pefile32_len, file32_len, tag32_off, tag32_len ) ) != ERR_NONE ) || ((result = test_spv_v128(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v129(context, licdata, pefile32, peobj32_len, pefile32_len, tag32_off, tag32_len ) ) != ERR_NONE ) || ((result = test_spv_v130(context, licdata, pefile64, peobj64_len, pefile64_len, file64_len, tag64_off, tag64_len ) ) != ERR_NONE ) || ((result = test_spv_v131(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v132(context, licdata, pefile64, peobj64_len, pefile64_len, tag64_off, tag64_len ) ) != ERR_NONE ) || ((result = test_spv_v133() ) != ERR_NONE ) || ((result = test_spv_v134() ) != ERR_NONE ) || ((result = test_spv_v201(context, licdata, pefile32, peobj32_len, pefile32_len ) ) != ERR_NONE ) || ((result = test_spv_v202(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v203(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v204(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v205(context, licdata, pefile64, peobj64_len, pefile64_len ) ) != ERR_NONE ) || ((result = test_spv_v206(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v207(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v208(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v209(context, licdata, pefile32, peobj32_len, pefile32_len ) ) != ERR_NONE ) || ((result = test_spv_v210(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v211(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v212(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v213(context, licdata, pefile64, peobj64_len, pefile64_len ) ) != ERR_NONE ) || ((result = test_spv_v214(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v215(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v216(context, licdata, peobj64_len ) ) != ERR_NONE ) #if defined(CSA_MODE) || ((result = test_spv_v217(context, licdata, peobj32_len ) ) != ERR_NONE ) #endif || ((result = test_spv_v218(context, licdata, peobj32_len ) ) != ERR_NONE ) #if defined(CSA_MODE) || ((result = test_spv_v219(context, licdata, peobj64_len ) ) != ERR_NONE ) #endif || ((result = test_spv_v220(context, licdata, peobj64_len ) ) != ERR_NONE ) #if defined(CSA_MODE) || ((result = test_spv_v221(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v222(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v223(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v224(context, licdata, peobj64_len ) ) != ERR_NONE ) #endif || ((result = test_spv_v225(context, licdata, pefile32, peobj32_len, pefile32_len ) ) != ERR_NONE ) || ((result = test_spv_v226(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v227(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v228(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v229(context, licdata, pefile64, peobj64_len, pefile64_len ) ) != ERR_NONE ) || ((result = test_spv_v230(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v231(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v232(context, licdata, peobj64_len ) ) != ERR_NONE ) #if defined(CSA_MODE) || ((result = test_spv_v233(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v234(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v235(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v236(context, licdata, peobj64_len ) ) != ERR_NONE ) #endif || ((result = test_spv_v237(context, licdata, pefile32, peobj32_len, pefile32_len ) ) != ERR_NONE ) || ((result = test_spv_v238(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v239(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v240(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v241(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v242(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v243(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v244(context, licdata, pefile64, peobj64_len, pefile64_len ) ) != ERR_NONE ) || ((result = test_spv_v245(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v246(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v247(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v248(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v249(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v250(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v251(licdata, pefile32, pefile32_len ) ) != ERR_NONE ) || ((result = test_spv_v252(licdata, pefile32, pefile32_len ) ) != ERR_NONE ) || ((result = test_spv_v253() ) != ERR_NONE ) || ((result = test_spv_v254() ) != ERR_NONE ) || ((result = test_spv_v255(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v256(context, licdata, peobj32_len ) ) != ERR_NONE ) || ((result = test_spv_v257(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v258(context, licdata, peobj64_len ) ) != ERR_NONE ) || ((result = test_spv_v261(context, licdata, pefile32, peobj32_len, pefile32_len ) ) != ERR_NONE ) || ((result = test_spv_v262(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v264(context, licdata, pefile64, peobj64_len, pefile64_len ) ) != ERR_NONE ) || ((result = test_spv_v265(context, licdata ) ) != ERR_NONE ) ) { printf("fail\n"); } return result; } static int test_spv_js(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_reads_(jsfile_len) const UNSIGNED8 *jsfile, UNSIGNED64 jsfile_len ) { int result; if (((result = test_spv_v134()) != ERR_NONE) || ((result = test_spv_v259(context, licdata, jsfile, jsfile_len ) ) != ERR_NONE ) || ((result = test_spv_v260(context, licdata ) ) != ERR_NONE ) || ((result = test_spv_v263(context, licdata, jsfile, jsfile_len ) ) != ERR_NONE ) ) { printf("fail\n"); } return result; } static int test_spv_ds(void) { int result; if (((result = test_spv_ds01()) != ERR_NONE) || ((result = test_spv_ds02()) != ERR_NONE) || ((result = test_spv_ds03()) != ERR_NONE) || ((result = test_spv_ds04()) != ERR_NONE) || ((result = test_spv_ds05()) != ERR_NONE) || ((result = test_spv_ds06()) != ERR_NONE) || ((result = test_spv_ds07()) != ERR_NONE) || ((result = test_spv_ds08()) != ERR_NONE) || ((result = test_spv_ds09()) != ERR_NONE) || ((result = test_spv_ds10()) != ERR_NONE) ) { printf("fail\n"); } return result; } static int test_spv_eof(_In_ const PTAGGANTCONTEXT context, _In_z_ const UNSIGNED8 *licdata, _In_ const UNSIGNED8 *pefile32, UNSIGNED64 peobj32_len, UNSIGNED64 pefile32_len, _In_ const UNSIGNED8 *pefile64, UNSIGNED64 peobj64_len, UNSIGNED64 pefile64_len ) { int result; if (((result = test_spv_eof01(context, licdata, pefile32, peobj32_len, pefile32_len ) ) != ERR_NONE ) || ((result = test_spv_eof02(context, licdata, pefile64, peobj64_len, pefile64_len ) ) != ERR_NONE ) ) { printf("fail\n"); } return result; } static int validate_taggant(_In_ const char *filename, __deref_inout PTAGGANT *ptaggant, _In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_opt_ const UNSIGNED8 *tsrootdata, int gettime, int ignorehmh, TAGGANTCONTAINER tagtype, int *ptaglast, int *pmethod ) { int result; FILE *infile; PTAGGANTOBJ object; UNSIGNED64 timest; if (gettime && !tsrootdata ) { return TNOTIME; } if (fopen_s(&infile, filename, "rb" ) || !infile ) { return ERR_BADOPEN; } object = NULL; if (((result = pTaggantGetTaggant(context, infile, tagtype, ptaggant ) ) == TNOERR ) && ((result = pTaggantObjectNewEx(*ptaggant, 0, (TAGGANTCONTAINER) 0, &object ) ) == TNOERR ) && ((result = pTaggantValidateSignature(object, *ptaggant, (PVOID) rootdata ) ) == TNOERR ) && (!gettime || ((result = pTaggantGetTimestamp(object, &timest, (PVOID) tsrootdata ) ) == TNOERR ) ) ) { UNSIGNED8 *tmpfile; UNSIGNED64 tmpfile_len; if ((result = read_tmp_file(filename, &tmpfile, &tmpfile_len ) ) == ERR_NONE ) { PHASHBLOB_HASHMAP_DOUBLE doubles; UNSIGNED32 size; char info; size = 0; if (!ignorehmh && ((ignorehmh = !pTaggantGetHashMapDoubles(object, &doubles ) ) == FALSE ) ) { ignorehmh = pTaggantGetInfo(object, EIGNOREHMH, &size, &info ) == TINSUFFICIENTBUFFER; } if (!ignorehmh) { *pmethod = METHOD_HMH; result = pTaggantValidateHashMap(context, object, (PVOID) infile ); } else { char file_len[8]; UNSIGNED64 obj_len; UNSIGNED64 tag_off; UNSIGNED32 tag_len; size = 8; obj_len = 0; if (((result = pTaggantGetInfo(object, EFILEEND, &size, file_len ) ) == TNOERR ) && ((tagtype != TAGGANT_PEFILE) || ((result = object_sizes(tmpfile, tmpfile_len, &obj_len, &tag_off, &tag_len ) ) == ERR_NONE ) ) ) { *pmethod = METHOD_FFH; result = pTaggantValidateDefaultHashes(context, object, (PVOID) infile, obj_len, read_le64(file_len) ); } } if (result == TNOERR) { size = 1; *ptaglast = pTaggantGetInfo(object, ETAGPREV, &size, &info ); //// pTaggantPackerInfo() } free(tmpfile); } } pTaggantObjectFree(object); fclose(infile); return result; } static int validate_taggant_taggant(_In_ const char *filename, __deref_inout PTAGGANT *ptaggant, _In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_opt_ const UNSIGNED8 *tsrootdata, int gettime, int ignorehmh, TAGGANTCONTAINER tagtype, __out_bcount_full(sizeof(int)) int *ptaglast, __out_bcount_full(sizeof(int)) int *pmethod ) { int result; if (((result = validate_taggant(filename, ptaggant, context, rootdata, tsrootdata, gettime, ignorehmh, tagtype, ptaglast, pmethod ) ) == ERR_NONE ) && ((result = *ptaglast) == ERR_NONE) ) { if (!ignorehmh && (*pmethod != METHOD_HMH) ) { result = ERR_BADLIB; } else { result = validate_taggant(filename, ptaggant, context, rootdata, tsrootdata, gettime, ignorehmh, tagtype, ptaglast, pmethod ); } } return result; } static int validate_taggant_taggant_taggant(_In_ const char *filename, __deref_inout PTAGGANT *ptaggant, _In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_opt_ const UNSIGNED8 *tsrootdata, int gettime, int ignorehmh, TAGGANTCONTAINER tagtype ) { int result; int taglast; int method; if (((result = validate_taggant_taggant(filename, ptaggant, context, rootdata, tsrootdata, gettime, ignorehmh, tagtype, &taglast, &method ) ) == ERR_NONE ) && ((result = taglast) == ERR_NONE) ) { if (!ignorehmh && (method != METHOD_HMH) ) { result = ERR_BADLIB; } else { result = validate_taggant(filename, ptaggant, context, rootdata, tsrootdata, gettime, ignorehmh, tagtype, &taglast, &method ); } } return result; } static int validate_no_taggant(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context ) { int result; UNSIGNED8 *tmpfile; UNSIGNED64 tmpfile_len; UNSIGNED32 tag_len; if ((result = erase_v1_taggant(filename1, &tmpfile, &tmpfile_len, &tag_len ) ) == ERR_NONE ) { FILE *infile; if ((result = create_tmp_file(filename2, tmpfile, tmpfile_len ) ) == ERR_NONE ) { PTAGGANT taggant; if (fopen_s(&infile, filename2, "rb" ) || !infile ) { free(tmpfile); return ERR_BADOPEN; } taggant = NULL; result = pTaggantGetTaggant(context, infile, TAGGANT_PEFILE, &taggant ); pTaggantFreeTaggant(taggant); fclose(infile); if (result == TNOERR) { result = ERR_BADLIB; } else if (result == TNOTAGGANTS) { result = ERR_NONE; } } free(tmpfile); } return result; } static int validate_tampered(_In_opt_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, int tamper_lvl, int tag_lvl ) { int result; UNSIGNED8 *tmpfile; UNSIGNED64 tmpfile_len; result = ERR_NONE; if ((tamper_lvl != TAMPER_NONE) && ((result = read_tmp_file(filename1, &tmpfile, &tmpfile_len ) ) == ERR_NONE ) ) { UNSIGNED64 tamper_off; switch (tamper_lvl) { case TAMPER_FILELEN: case TAMPER_FILELENM1: case TAMPER_FILELENM2: { tamper_off = tmpfile_len; while (--tamper_lvl) { tamper_off -= read_le32(tmpfile + tamper_off - (sizeof(TAGGANT_HEADER2) - offsetof(TAGGANT_HEADER2, TaggantLength ) ) ); } break; } case TAMPER_TAGP101: { UNSIGNED64 peobj_len; UNSIGNED64 tag_off; UNSIGNED32 tag_len; result = object_sizes(tmpfile, tmpfile_len, &peobj_len, &tag_off, &tag_len ); tamper_off = tag_off + 0x101; break; } case TAMPER_FILELENM2P101: { tamper_off = tmpfile_len - read_le32(tmpfile + tmpfile_len - (sizeof(TAGGANT_HEADER2) - offsetof(TAGGANT_HEADER2, TaggantLength ) ) ); tamper_off -= read_le32(tmpfile + tamper_off - (sizeof(TAGGANT_HEADER2) - offsetof(TAGGANT_HEADER2, TaggantLength ) ) ) - 0x101; break; } case TAMPER_TIME: { tamper_off = read_le32(tmpfile + offsetof(IMAGE_DOS_HEADER, e_lfanew ) ) + offsetof(IMAGE_NT_HEADERS32, FileHeader ) + offsetof(IMAGE_FILE_HEADER, TimeDateStamp ) + 1; break; } case TAMPER_3: { tamper_off = 3; break; } default: { tamper_off = 0; result = ERR_BADLIB; } } if (result == ERR_NONE) { ++tmpfile[tamper_off - 1]; result = create_tmp_file(filename2, tmpfile, tmpfile_len ); } free(tmpfile); } if (result == ERR_NONE) { PTAGGANT taggant; int taglast; int method; taggant = NULL; switch (tag_lvl) { case TAG_1: { result = validate_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); break; } case TAG_2: { result = validate_taggant_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); break; } case TAG_3: { result = validate_taggant_taggant_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE ); break; } case TAG_1_HMH: case TAG_1_FFH: { int ignore_hmh; int method_cmp; ignore_hmh = FALSE; method_cmp = METHOD_HMH; if (tag_lvl == TAG_1_FFH) { ignore_hmh = TRUE; method_cmp = METHOD_FFH; } if ((result = validate_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, ignore_hmh, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if ((method == method_cmp) && (result == TMISMATCH) ) { result = ERR_NONE; } break; } case TAG_2_HMH: { if ((result = validate_taggant_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if ((method == METHOD_HMH) && (result == TMISMATCH) ) { result = ERR_NONE; } break; } case TAG_2_1_HMH: case TAG_2_FFH: { int ignore_hmh; int method_cmp; ignore_hmh = FALSE; method_cmp = METHOD_HMH; if (tag_lvl == TAG_2_FFH) { ignore_hmh = TRUE; method_cmp = METHOD_FFH; } if ((result = validate_taggant_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { if (taglast || (method != METHOD_HMH) || ((result = validate_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, ignore_hmh, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) ) { result = ERR_BADLIB; } else if ((method == method_cmp) && (result == TMISMATCH) ) { result = ERR_NONE; } } break; } case TAG_1_1: { if ((result = validate_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { if (taglast || (method != METHOD_HMH) || ((result = validate_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, TRUE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) ) { result = ERR_BADLIB; } else if ((method == METHOD_FFH) && (result == TMISMATCH) ) { result = ERR_NONE; } } break; } default: { result = ERR_BADLIB; } } pTaggantFreeTaggant(taggant); } return result; } #if defined(CSA_MODE) static int validate_eignore(_In_z_ const char *filename, _In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; FILE *infile; PTAGGANT taggant; PTAGGANTOBJ object; if (fopen_s(&infile, filename, "rb" ) || !infile ) { return ERR_BADOPEN; } taggant = NULL; if (((result = pTaggantGetTaggant(context, infile, TAGGANT_PEFILE, &taggant ) ) == TNOERR ) && ((result = pTaggantObjectNewEx(taggant, 0, (TAGGANTCONTAINER) 0, &object ) ) == TNOERR ) && ((result = pTaggantValidateSignature(object, taggant, (PVOID) rootdata ) ) == TNOERR ) ) { UNSIGNED32 size; char info; size = 0; result = pTaggantGetInfo(object, EIGNOREHMH, &size, &info ); pTaggantObjectFree(object); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TINSUFFICIENTBUFFER) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); fclose(infile); return result; } #endif static int validate_appended(_In_z_ const char *filename1, _In_z_ const char *filename2, _In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, TAGGANTCONTAINER tagtype, int errtype ) { int result; unsigned char *tmpfile; UNSIGNED64 tmpfile_len; if ((result = read_tmp_file(filename1, &tmpfile, &tmpfile_len ) ) == ERR_NONE ) { if ((result = append_file(filename2, tmpfile, tmpfile_len ) ) == ERR_NONE ) { PTAGGANT taggant; int taglast; int method; taggant = NULL; result = validate_taggant(filename2, &taggant, context, rootdata, NULL, FALSE, TRUE, tagtype, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == errtype) { result = ERR_NONE; } } free(tmpfile); } return result; } static int validate_extra(_In_z_ const char *filename, _In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; FILE *infile; PTAGGANT taggant; PTAGGANTOBJ object; if (fopen_s(&infile, filename, "rb" ) || !infile ) { return ERR_BADOPEN; } taggant = NULL; if (((result = pTaggantGetTaggant(context, infile, TAGGANT_PEFILE, &taggant ) ) == TNOERR ) && ((result = pTaggantObjectNewEx(taggant, 0, (TAGGANTCONTAINER) 0, &object ) ) == TNOERR ) && ((result = pTaggantValidateSignature(object, taggant, (PVOID) rootdata ) ) == TNOERR ) ) { UNSIGNED32 size; char info[sizeof(TESTSTRING2)]; size = sizeof(info); result = pTaggantGetInfo(object, ECONTRIBUTORLIST, &size, info ); pTaggantObjectFree(object); } pTaggantFreeTaggant(taggant); fclose(infile); return result; } static int test_ssv_001(_In_ const PTAGGANTCONTEXT context) { int result; printf(PR_WIDTH, "(001)testing 32-bit PE file containing no Taggant:"); result = validate_no_taggant("v1test01", "vssvtest001", context ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_002(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(002)testing 32-bit PE file containing good v1 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant("v1test01", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_003(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(003)testing 32-bit PE file containing good v2 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant("v2test01", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_004(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(004)testing 32-bit PE file containing good v2 Taggant and good v1 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant_taggant("v2test02", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_005(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(005)testing 32-bit PE file containing good v2 Taggant and good v2 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant_taggant("v2test03", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_006(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; printf(PR_WIDTH, "(006)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant_taggant_taggant("v2test04", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_007(_In_ const PTAGGANTCONTEXT context) { int result; printf(PR_WIDTH, "(007)testing 64-bit PE file containing no Taggant:"); result = validate_no_taggant("v1test04", "vssvtest007", context ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_008(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(008)testing 64-bit PE file containing good v1 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant("v1test04", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_009(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(009)testing 64-bit PE file containing good v2 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant("v2test05", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_010(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(010)testing 64-bit PE file containing good v2 Taggant and good v1 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant_taggant("v2test06", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_011(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(011)testing 64-bit PE file containing good v2 Taggant and good v2 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant_taggant("v2test07", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_012(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; printf(PR_WIDTH, "(012)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and good image and no overlay:"); taggant = NULL; result = validate_taggant_taggant_taggant("v2test08", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_013(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(013)testing 32-bit PE file containing good v1 Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant("v1test04", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_014(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(014)testing 32-bit PE file containing good v2 Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant("v2test09", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_015(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(015)testing 32-bit PE file containing good v2 Taggant and good v1 Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant_taggant("v2test10", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_016(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(016)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant_taggant("v2test11", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_017(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; printf(PR_WIDTH, "(017)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant_taggant_taggant("v2test12", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_018(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(018)testing 64-bit PE file containing good v1 Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant("v1test10", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_019(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(019)testing 64-bit PE file containing good v2 Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant("v2test13", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_020(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(020)testing 64-bit PE file containing good v2 Taggant and good v1 Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant_taggant("v2test14", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_021(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(021)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant_taggant("v2test15", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_022(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; printf(PR_WIDTH, "(022)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and good image and good overlay:"); taggant = NULL; result = validate_taggant_taggant_taggant("v2test16", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_023(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(023)testing 32-bit PE file containing good v1 Taggant and good image and tampered overlay:"); result = validate_tampered("v1test07", "vssvtest023", context, rootdata, TAMPER_FILELEN, TAG_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_024(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(013)testing 32-bit PE file containing good v2 Taggant and good image and tampered overlay:"); result = validate_tampered("v2test09", "vssvtest024", context, rootdata, TAMPER_FILELENM1, TAG_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_025(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(025)testing 32-bit PE file containing good v2 Taggant and good v1 Taggant and good image and tampered overlay:"); result = validate_tampered("v2test10", "vssvtest025", context, rootdata, TAMPER_FILELENM1, TAG_2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_026(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(026)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good image and tampered overlay:"); result = validate_tampered("v2test11", "vssvtest026", context, rootdata, TAMPER_FILELENM2, TAG_2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_027(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(027)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and good image and tampered overlay:"); result = validate_tampered("v2test12", "vssvtest027", context, rootdata, TAMPER_FILELENM2, TAG_3 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_028(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(028)testing 64-bit PE file containing good v1 Taggant and good image and tampered overlay:"); result = validate_tampered("v1test10", "vssvtest028", context, rootdata, TAMPER_FILELEN, TAG_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_029(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(029)testing 64-bit PE file containing good v2 Taggant and good image and tampered overlay:"); result = validate_tampered("v2test13", "vssvtest029", context, rootdata, TAMPER_FILELENM1, TAG_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_030(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(030)testing 64-bit PE file containing good v2 Taggant and good v1 Taggant and good image and tampered overlay:"); result = validate_tampered("v2test14", "vssvtest030", context, rootdata, TAMPER_FILELENM1, TAG_2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_031(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(031)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good image and tampered overlay:"); result = validate_tampered("v2test15", "vssvtest031", context, rootdata, TAMPER_FILELENM2, TAG_2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_032(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(032)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and good image and tampered overlay:"); result = validate_tampered("v2test16", "vssvtest032", context, rootdata, TAMPER_FILELENM2, TAG_3 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_033(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(033)testing 32-bit PE file containing tampered v1 Taggant:"); taggant = NULL; result = validate_taggant("v1tampered1_32", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_034(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(034)testing 32-bit PE file containing tampered v2 Taggant:"); taggant = NULL; result = validate_taggant("v2tampered1_32", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_035(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(035)testing 32-bit PE file containing good v2 Taggant and tampered v1 Taggant:"); result = validate_tampered("v2test02", "vssvtest035", context, rootdata, TAMPER_TAGP101, TAG_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_036(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(036)testing 32-bit PE file containing good v2 Taggant and tampered v2 Taggant:"); result = validate_tampered("v2test03", "vssvtest036", context, rootdata, TAMPER_FILELENM2P101, TAG_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_037(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(037)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and tampered v1 Taggant:"); result = validate_tampered("v2test04", "vssvtest037", context, rootdata, TAMPER_TAGP101, TAG_2_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_038(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(038)testing 64-bit PE file containing tampered v1 Taggant:"); taggant = NULL; result = validate_taggant("v1tampered1_64", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_039(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(039)testing 64-bit PE file containing tampered v2 Taggant:"); taggant = NULL; result = validate_taggant("v2tampered1_64", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TBADKEY) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_040(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(040)testing 64-bit PE file containing good v2 Taggant and tampered v1 Taggant:"); result = validate_tampered("v2test06", "vssvtest040", context, rootdata, TAMPER_TAGP101, TAG_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_041(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(041)testing 64-bit PE file containing good v2 Taggant and tampered v2 Taggant:"); result = validate_tampered("v2test07", "vssvtest041", context, rootdata, TAMPER_FILELENM2P101, TAG_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_042(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(042)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and tampered v1 Taggant:"); result = validate_tampered("v2test08", "vssvtest042", context, rootdata, TAMPER_TAGP101, TAG_2_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_043(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(043)testing 32-bit PE file containing good v1 Taggant and good v2 Taggant (v1 at eof) and good image"); taggant = NULL; if ((result = validate_taggant("veoftest01", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { if ((result = validate_taggant("veoftest01", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TNOTAGGANTS) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_044(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(044)testing 32-bit PE file containing good v1 Taggant and good v2 Taggant (v2 at eof) and good image:"); taggant = NULL; result = validate_taggant("v1test03", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TMISMATCH) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_045(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(045)testing 64-bit PE file containing good v1 Taggant and good v2 Taggant (v1 at eof) and good image"); taggant = NULL; if ((result = validate_taggant("veoftest02", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { if ((result = validate_taggant("veoftest02", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TNOTAGGANTS) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_046(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(046)testing 64-bit PE file containing good v1 Taggant and good v2 Taggant (v2 at eof) and good image:"); taggant = NULL; result = validate_taggant("v1test06", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TMISMATCH) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_047(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(047)testing 32-bit PE file containing good v1 Taggant and tampered HMH region:"); result = validate_tampered("v1test21", "vssvtest047", context, rootdata, TAMPER_TIME, TAG_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_048(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(048)testing 32-bit PE file containing good v1 Taggant and tampered non-HMH region:"); result = validate_tampered("v1test21", "vssvtest048", context, rootdata, TAMPER_3, TAG_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_049(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(049)testing 32-bit PE file containing good v2 Taggant and tampered HMH region:"); result = validate_tampered("v2test25", "vssvtest049", context, rootdata, TAMPER_TIME, TAG_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_050(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(050)testing 32-bit PE file containing good v2 Taggant and tampered non-HMH region:"); result = validate_tampered("v2test25", "vssvtest050", context, rootdata, TAMPER_3, TAG_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_051(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(051)testing 32-bit PE file containing good v2 Taggant and good v1 Taggant and tampered v1 HMH region:"); result = validate_tampered("v2test26", "vssvtest051", context, rootdata, TAMPER_TIME, TAG_2_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_052(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(052)testing 32-bit PE file containing good v2 Taggant and good v1 Taggant and tampered non-HMH region:"); result = validate_tampered("v2test26", "vssvtest052", context, rootdata, TAMPER_3, TAG_2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_053(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(053)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and tampered v2(b) HMH region:"); result = validate_tampered("v2test27", "vssvtest053", context, rootdata, TAMPER_TIME, TAG_2_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_054(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(054)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and tampered non-HMH region:"); result = validate_tampered("v2test27", "vssvtest054", context, rootdata, TAMPER_3, TAG_2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_055(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(055)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and tampered v1 HMH region:"); result = validate_tampered("v2test28", "vssvtest055", context, rootdata, TAMPER_TIME, TAG_2_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_056(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(056)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and tampered non-HMH region:"); result = validate_tampered("v2test28", "vssvtest056", context, rootdata, TAMPER_3, TAG_3 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } #if defined(CSA_MODE) static int test_ssv_057(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(057)testing 32-bit PE file containing good v2 Taggant and good v1 Taggant and broken HMH has EIGNOREHMH:"); result = validate_eignore("v2test33", context, rootdata ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_058(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(058)testing 32-bit PE file containing good v2 Taggant and good v2 Taggant and broken HMH has EIGNOREHMH:"); result = validate_eignore("v2test34", context, rootdata ); if (result == ERR_NONE) { printf("pass\n"); } return result; } #endif static int test_ssv_059(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(059)testing 64-bit PE file containing good v1 Taggant and tampered HMH region:"); result = validate_tampered("v1test22", "vssvtest059", context, rootdata, TAMPER_TIME, TAG_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_060(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(060)testing 64-bit PE file containing good v1 Taggant and tampered non-HMH region:"); result = validate_tampered("v1test22", "vssvtest060", context, rootdata, TAMPER_3, TAG_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_061(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(061)testing 64-bit PE file containing good v2 Taggant and tampered HMH region:"); result = validate_tampered("v2test29", "vssvtest061", context, rootdata, TAMPER_TIME, TAG_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_062(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(062)testing 64-bit PE file containing good v2 Taggant and tampered non-HMH region:"); result = validate_tampered("v2test29", "vssvtest062", context, rootdata, TAMPER_3, TAG_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_063(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(063)testing 64-bit PE file containing good v2 Taggant and good v1 Taggant and tampered v1 HMH region:"); result = validate_tampered("v2test30", "vssvtest063", context, rootdata, TAMPER_TIME, TAG_2_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_064(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(064)testing 64-bit PE file containing good v2 Taggant and good v1 Taggant and tampered non-HMH region:"); result = validate_tampered("v2test30", "vssvtest064", context, rootdata, TAMPER_3, TAG_2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_065(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(065)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and tampered v2(b) HMH region:"); result = validate_tampered("v2test31", "vssvtest065", context, rootdata, TAMPER_TIME, TAG_2_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_066(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(066)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and tampered non-HMH region:"); result = validate_tampered("v2test31", "vssvtest066", context, rootdata, TAMPER_3, TAG_2 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_067(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(067)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and tampered v1 HMH region:"); result = validate_tampered("v2test32", "vssvtest067", context, rootdata, TAMPER_TIME, TAG_2_1_HMH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_068(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(068)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and tampered non-HMH region:"); result = validate_tampered("v2test32", "vssvtest068", context, rootdata, TAMPER_3, TAG_3 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } #if defined(CSA_MODE) static int test_ssv_069(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(069)testing 64-bit PE file containing good v2 Taggant and good v1 Taggant and broken HMH has EIGNOREHMH:"); result = validate_eignore("v2test35", context, rootdata ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_070(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(070)testing 64-bit PE file containing good v2 Taggant and good v2 Taggant and broken HMH has EIGNOREHMH:"); result = validate_eignore("v2test36", context, rootdata ); if (result == ERR_NONE) { printf("pass\n"); } return result; } #endif static int test_ssv_071(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(071)testing EIGNOREHMH 32-bit PE file containing good v1 Taggant and tampered image:"); result = validate_tampered(NULL, "vssvtest047", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_072(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(072)testing EIGNOREHMH 32-bit PE file containing good v2 Taggant and tampered image:"); result = validate_tampered(NULL, "vssvtest049", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_073(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(073)testing 32-bit PE file containing good v2 Taggant and good v1(EIH) Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest051", context, rootdata, TAMPER_NONE, TAG_1_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_074(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(074)testing 32-bit PE file containing good v2(EIH) Taggant and good v1 Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest051", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_075(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(075)testing 32-bit PE file containing good v2(a) Taggant and good v2(b(EIH)) Taggant and tampered v2(b) image:"); result = validate_tampered(NULL, "vssvtest053", context, rootdata, TAMPER_NONE, TAG_1_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_076(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(076)testing 32-bit PE file containing good v2(a(EIH)) Taggant and good v2(b) Taggant and tampered v2(b) image:"); result = validate_tampered(NULL, "vssvtest053", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_077(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(077)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1(EIH) Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest055", context, rootdata, TAMPER_NONE, TAG_2_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_078(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(078)testing 32-bit PE file containing good v2(a) Taggant and good v2(b(EIH)) Taggant and good v1 Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest055", context, rootdata, TAMPER_NONE, TAG_1_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_079(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(079)testing 32-bit PE file containing good v2(a(EIH)) Taggant and good v2(b) Taggant and good v1 Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest055", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_080(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(080)testing EIGNOREHMH 64-bit PE file containing good v1 Taggant and tampered image:"); result = validate_tampered(NULL, "vssvtest059", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_081(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(081)testing EIGNOREHMH 64-bit PE file containing good v2 Taggant and tampered image:"); result = validate_tampered(NULL, "vssvtest061", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_082(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(082)testing 64-bit PE file containing good v2 Taggant and good v1(EIH) Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest063", context, rootdata, TAMPER_NONE, TAG_1_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_083(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(083)testing 64-bit PE file containing good v2(EIH) Taggant and good v1 Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest063", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_084(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(084)testing 64-bit PE file containing good v2(a) Taggant and good v2(b(EIH)) Taggant and tampered v2(b) image:"); result = validate_tampered(NULL, "vssvtest065", context, rootdata, TAMPER_NONE, TAG_1_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_085(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(085)testing 64-bit PE file containing good v2(a(EIH)) Taggant and good v2(b) Taggant and tampered v2(b) image:"); result = validate_tampered(NULL, "vssvtest065", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_086(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(086)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1(EIH) Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest067", context, rootdata, TAMPER_NONE, TAG_2_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_087(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(087)testing 64-bit PE file containing good v2(a) Taggant and good v2(b(EIH)) Taggant and good v1 Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest067", context, rootdata, TAMPER_NONE, TAG_1_1 ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_088(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(088)testing 64-bit PE file containing good v2(a(EIH)) Taggant and good v2(b) Taggant and good v1 Taggant and tampered v1 image:"); result = validate_tampered(NULL, "vssvtest067", context, rootdata, TAMPER_NONE, TAG_1_FFH ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_089(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(089)testing 32-bit PE file containing good v1(TS) Taggant:"); taggant = NULL; result = validate_taggant("v1test01", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_090(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(090)testing 32-bit PE file containing bad v1(TS) Taggant:"); taggant = NULL; result = validate_taggant("v1test27", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_091(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(091)testing 32-bit PE file containing good v2(TS) Taggant:"); taggant = NULL; result = validate_taggant("v2test01", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_092(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(092)testing 32-bit PE file containing bad v2(TS) Taggant:"); taggant = NULL; result = validate_taggant("v2test37", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_093(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(093)testing 32-bit PE file containing good v2(TS) Taggant and good v1(TS):"); taggant = NULL; result = validate_taggant_taggant("v2test02", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_094(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(094)testing 32-bit PE file containing good v2(TS) Taggant and bad v1(TS):"); taggant = NULL; if (((result = validate_taggant("v2test38", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) && ((result = taglast) == ERR_NONE) ) { result = validate_taggant("v2test38", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_095(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(095)testing 32-bit PE file containing bad v2(TS) Taggant and good v1(TS) Taggant:"); taggant = NULL; result = validate_taggant("v2test41", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_096(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(096)testing 32-bit PE file containing good v2(a(TS)) Taggant and good v2(b(TS)) Taggant:"); taggant = NULL; result = validate_taggant_taggant("v2test03", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_097(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(097)testing 32-bit PE file containing good v2(a(TS)) Taggant and bad v2(b(TS)) Taggant:"); taggant = NULL; if (((result = validate_taggant("v2test39", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) && ((result = taglast) == ERR_NONE) ) { result = validate_taggant("v2test39", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_098(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(098)testing 32-bit PE file containing bad v2(a(TS)) Taggant and good v2(b(TS)) Taggant:"); taggant = NULL; result = validate_taggant("v2test42", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_099(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; printf(PR_WIDTH, "(099)testing 32-bit PE file containing good v2(a(TS)) Taggant and good v2(b(TS)) Taggant and good v1(TS) Taggant:"); taggant = NULL; result = validate_taggant_taggant_taggant("v2test04", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_100(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(100)testing 32-bit PE file containing good v2(a(TS)) Taggant and good v2(b(TS)) Taggant and bad v1(TS) Taggant:"); taggant = NULL; if (((result = validate_taggant_taggant("v2test40", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) && ((result = taglast) == ERR_NONE) ) { result = validate_taggant("v2test40", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_101(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(101)testing 32-bit PE file containing good v2(a(TS)) Taggant and bad v2(b(TS)) Taggant and good v1(TS) Taggant:"); taggant = NULL; if (((result = validate_taggant("v2test43", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) && ((result = taglast) == ERR_NONE) ) { result = validate_taggant("v2test43", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_102(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(102)testing 64-bit PE file containing good v1(TS) Taggant:"); taggant = NULL; result = validate_taggant("v1test04", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_103(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(103)testing 64-bit PE file containing bad v1(TS) Taggant:"); taggant = NULL; result = validate_taggant("v1test30", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_104(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(104)testing 64-bit PE file containing good v2(TS) Taggant:"); taggant = NULL; result = validate_taggant("v2test05", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_105(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(105)testing 64-bit PE file containing bad v2(TS) Taggant:"); taggant = NULL; result = validate_taggant("v2test44", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_106(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(106)testing 64-bit PE file containing good v2(TS) Taggant and good v1(TS):"); taggant = NULL; result = validate_taggant_taggant("v2test06", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_107(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(107)testing 64-bit PE file containing good v2(TS) Taggant and bad v1(TS):"); taggant = NULL; if (((result = validate_taggant("v2test45", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) && ((result = taglast) == ERR_NONE) ) { result = validate_taggant("v2test45", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_108(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(108)testing 64-bit PE file containing bad v2(TS) Taggant and good v1(TS) Taggant:"); taggant = NULL; result = validate_taggant("v2test48", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_109(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(109)testing 64-bit PE file containing good v2(a(TS)) Taggant and good v2(b(TS)) Taggant:"); taggant = NULL; result = validate_taggant_taggant("v2test07", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_110(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(110)testing 32-bit PE file containing good v2(a(TS)) Taggant and bad v2(b(TS)) Taggant:"); taggant = NULL; if (((result = validate_taggant("v2test46", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) && ((result = taglast) == ERR_NONE) ) { result = validate_taggant("v2test46", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_111(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(111)testing 64-bit PE file containing bad v2(a(TS)) Taggant and good v2(b(TS)) Taggant:"); taggant = NULL; result = validate_taggant("v2test49", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_112(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; printf(PR_WIDTH, "(112)testing 64-bit PE file containing good v2(a(TS)) Taggant and good v2(b(TS)) Taggant and good v1(TS) Taggant:"); taggant = NULL; result = validate_taggant_taggant_taggant("v2test08", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_113(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(113)testing 64-bit PE file containing good v2(a(TS)) Taggant and good v2(b(TS)) Taggant and bad v1(TS) Taggant:"); taggant = NULL; if (((result = validate_taggant_taggant("v2test47", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) && ((result = taglast) == ERR_NONE) ) { result = validate_taggant("v2test47", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_114(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(114)testing 64-bit PE file containing good v2(a(TS)) Taggant and bad v2(b(TS)) Taggant and good v1(TS) Taggant:"); taggant = NULL; if (((result = validate_taggant("v2test50", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) && ((result = taglast) == ERR_NONE) ) { result = validate_taggant("v2test50", &taggant, context, rootdata, tsrootdata, TRUE, FALSE, TAGGANT_PEFILE, &taglast, &method ); if (result == ERR_NONE) { result = ERR_BADLIB; } else if (result == TNOTIME) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_115(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "(115)testing 32-bit PE file containing good v1 Taggant and unexpected appended data:"); result = ERR_NONE; if (tag_len) { result = validate_appended("v1test01", "vssvtest115", context, rootdata, TAGGANT_PEFILE, TMISMATCH ); } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_116(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(116)testing 32-bit PE file containing good v2 Taggant and unexpected appended data:"); result = validate_appended("v2test01", "vssvtest116", context, rootdata, TAGGANT_PEFILE, TNOTAGGANTS ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_117(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, UNSIGNED32 tag_len ) { int result; printf(PR_WIDTH, "(117)testing 64-bit PE file containing good v1 Taggant and unexpected appended data:"); result = ERR_NONE; if (tag_len) { result = validate_appended("v1test04", "vssvtest117", context, rootdata, TAGGANT_PEFILE, TMISMATCH ); } if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_118(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(118)testing 64-bit PE file containing good v2 Taggant and unexpected appended data:"); result = validate_appended("v2test05", "vssvtest118", context, rootdata, TAGGANT_PEFILE, TNOTAGGANTS ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_119(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(119)testing 32-bit PE file containing good v1 Taggant and digital signature:"); taggant = NULL; result = validate_taggant("vdstest01", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_120(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(120)testing 32-bit PE file containing good v2 Taggant and digital signature:"); taggant = NULL; result = validate_taggant("vdstest02", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_121(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(121)testing 32-bit PE file containing good v2 Taggant and good v1 Taggant and digital signature:"); taggant = NULL; result = validate_taggant_taggant("vdstest03", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_122(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(122)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and digital signature:"); taggant = NULL; result = validate_taggant_taggant("vdstest04", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_123(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; printf(PR_WIDTH, "(123)testing 32-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and digital signature:"); taggant = NULL; result = validate_taggant_taggant_taggant("vdstest05", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_124(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(124)testing 64-bit PE file containing good v1 Taggant and digital signature:"); taggant = NULL; result = validate_taggant("vdstest06", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_125(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(125)testing 64-bit PE file containing good v2 Taggant and digital signature:"); taggant = NULL; result = validate_taggant("vdstest07", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_126(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(126)testing 64-bit PE file containing good v2 Taggant and good v1 Taggant and digital signature:"); taggant = NULL; result = validate_taggant_taggant("vdstest08", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_127(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(127)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and digital signature:"); taggant = NULL; result = validate_taggant_taggant("vdstest09", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_128(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; printf(PR_WIDTH, "(128)testing 64-bit PE file containing good v2(a) Taggant and good v2(b) Taggant and good v1 Taggant and digital signature:"); taggant = NULL; result = validate_taggant_taggant_taggant("vdstest10", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_129(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(129)testing extracted data from ExtraBlob matches what was added:"); result = validate_extra("v2test51", context, rootdata ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_130(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(130)testing extracted data from ExtraBlob matches what was added:"); result = validate_extra("v2test52", context, rootdata ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_131(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(131)testing JS file containing good v2 Taggant and good image:"); taggant = NULL; result = validate_taggant("v2test59", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_JSFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_132(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(132)testing JS file containing good v2(a) Taggant and good v2(b) Taggant and good image:"); taggant = NULL; result = validate_taggant_taggant("v2test60", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_JSFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_133(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(133)testing 32-bit PE file containing textual Taggant:"); taggant = NULL; result = validate_taggant("v2test61", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_JSFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_134(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(134)testing 64-bit PE file containing textual Taggant:"); taggant = NULL; result = validate_taggant("v2test64", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_JSFILE, &taglast, &method ); pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_135(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; printf(PR_WIDTH, "(135)testing JS file containing good v2 Taggant and unexpected appended data:"); result = validate_appended("v2test59", "vssvtest135", context, rootdata, TAGGANT_JSFILE, TNOTAGGANTS ); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_138(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(138)testing 32-bit PE file containing binary v2(a) Taggant and textual (b) Taggant:"); taggant = NULL; if ((result = validate_taggant("v2test62", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { if ((result = validate_taggant("v2test62", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_JSFILE, &taglast, &method ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TNOTAGGANTS) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_139(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; PTAGGANT taggant; int taglast; int method; printf(PR_WIDTH, "(139)testing 64-bit PE file containing binary v2(a) Taggant and textual (b) Taggant:"); taggant = NULL; if ((result = validate_taggant("v2test65", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_PEFILE, &taglast, &method ) ) == ERR_NONE ) { if ((result = validate_taggant("v2test65", &taggant, context, rootdata, NULL, FALSE, FALSE, TAGGANT_JSFILE, &taglast, &method ) ) == ERR_NONE ) { result = ERR_BADLIB; } else if (result == TNOTAGGANTS) { result = ERR_NONE; } } pTaggantFreeTaggant(taggant); if (result == ERR_NONE) { printf("pass\n"); } return result; } static int test_ssv_pe(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata, _In_ const UNSIGNED8 *tsrootdata, UNSIGNED32 tag32_len, UNSIGNED32 tag64_len ) { int result; if (((result = test_ssv_001(context)) != ERR_NONE) || ((result = test_ssv_002(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_003(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_004(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_005(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_006(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_007(context) ) != ERR_NONE ) || ((result = test_ssv_008(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_009(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_010(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_011(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_012(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_013(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_014(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_015(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_016(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_017(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_018(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_019(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_020(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_021(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_022(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_023(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_024(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_025(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_026(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_027(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_028(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_029(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_030(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_031(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_032(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_033(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_034(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_035(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_036(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_037(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_038(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_039(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_040(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_041(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_042(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_043(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_044(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_045(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_046(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_047(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_048(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_049(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_050(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_051(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_052(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_053(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_054(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_055(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_056(context, rootdata ) ) != ERR_NONE ) #if defined(CSA_MODE) || ((result = test_ssv_057(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_058(context, rootdata ) ) != ERR_NONE ) #endif || ((result = test_ssv_059(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_060(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_061(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_062(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_063(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_064(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_065(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_066(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_067(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_068(context, rootdata ) ) != ERR_NONE ) #if defined(CSA_MODE) || ((result = test_ssv_069(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_070(context, rootdata ) ) != ERR_NONE ) #endif || ((result = test_ssv_071(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_072(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_073(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_074(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_075(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_076(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_077(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_078(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_079(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_080(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_081(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_082(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_083(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_084(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_085(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_086(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_087(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_088(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_089(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_090(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_091(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_092(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_093(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_094(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_095(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_096(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_097(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_098(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_099(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_100(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_101(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_102(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_103(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_104(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_105(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_106(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_107(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_108(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_109(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_110(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_111(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_112(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_113(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_114(context, rootdata, tsrootdata ) ) != ERR_NONE ) || ((result = test_ssv_115(context, rootdata, tag32_len ) ) != ERR_NONE ) || ((result = test_ssv_116(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_117(context, rootdata, tag64_len ) ) != ERR_NONE ) || ((result = test_ssv_118(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_119(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_120(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_121(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_122(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_123(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_124(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_125(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_126(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_127(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_128(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_129(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_130(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_131(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_132(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_133(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_134(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_135(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_138(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_139(context, rootdata ) ) != ERR_NONE ) ) { printf("fail\n"); } return result; } static int test_ssv_js(_In_ const PTAGGANTCONTEXT context, _In_ const UNSIGNED8 *rootdata ) { int result; if (((result = test_ssv_131(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_132(context, rootdata ) ) != ERR_NONE ) || ((result = test_ssv_135(context, rootdata ) ) != ERR_NONE ) ) { printf("fail\n"); } return result; } int main(int argc, char *argv[] ) { int result; const UNSIGNED8 *licdata; const UNSIGNED8 *pefile32; UNSIGNED64 pefile32_len; UNSIGNED64 peobj32_len; UNSIGNED64 tag32_off; UNSIGNED32 tag32_len; const UNSIGNED8 *pefile64; UNSIGNED64 pefile64_len; UNSIGNED64 peobj64_len; UNSIGNED64 tag64_off; UNSIGNED32 tag64_len; const UNSIGNED8 *jsfile; UNSIGNED64 jsfile_len; HMODULE libspv; PTAGGANTCONTEXT context; HMODULE libssv; const UNSIGNED8 *rootdata; const UNSIGNED8 *tsrootdata; printf("checking SPV parameters\n"); if ((result = validate_spv_parms(argc, argv, (UNSIGNED8 **) &licdata, (UNSIGNED8 **) &pefile32, &pefile32_len, &peobj32_len, &tag32_off, &tag32_len, (UNSIGNED8 **) &pefile64, &pefile64_len, &peobj64_len, &tag64_off, &tag64_len, (UNSIGNED8 **) &jsfile, &jsfile_len ) ) != ERR_NONE ) { return result; } printf("loading SPV functions\n"); if ((result = init_spv_library("libspv", &libspv, TAGGANT_LIBRARY_VERSION2, licdata, &context ) ) != ERR_NONE ) { cleanup_spv(TRUE, LVL_FREEDLL, libspv, jsfile, pefile32, pefile64, licdata, 0, result ); return result; } #if !defined(SKIP_CREATE) { printf("performing PE creation tests\n"); if ((result = test_spv_pe(context, licdata, pefile32, peobj32_len, pefile32_len, tag32_off, tag32_len, pefile64, peobj64_len, pefile64_len, tag64_off, tag64_len ) ) != ERR_NONE ) { cleanup_spv(FALSE, LVL_FINALISE, context, libspv, jsfile, pefile64, pefile32, licdata, 0, result ); return result; } printf("performing JS creation tests\n"); if ((result = test_spv_js(context, licdata, jsfile, jsfile_len ) ) != ERR_NONE ) { cleanup_spv(FALSE, LVL_FINALISE, context, libspv, jsfile, pefile64, pefile32, licdata, 0, result ); return result; } printf("performing DS creation tests\n"); if ((result = test_spv_ds()) != ERR_NONE) { cleanup_spv(FALSE, LVL_FINALISE, context, libspv, jsfile, pefile64, pefile32, licdata, 0, result ); return result; } printf("performing EOF creation tests\n"); result = test_spv_eof(context, licdata, pefile32, peobj32_len, pefile32_len, pefile64, peobj64_len, pefile64_len ); cleanup_spv(!result, LVL_FINALISE, context, libspv, jsfile, pefile64, pefile32, licdata, 0, result ); if (result != ERR_NONE) { return result; } printf("completed creation tests\n"); } #endif printf("checking SSV parameters\n"); if ((result = validate_ssv_parms(argv, (UNSIGNED8 **) &rootdata, (UNSIGNED8 **) &tsrootdata ) ) != ERR_NONE ) { #if !defined(KEEP_FILES) delete_spv(); #endif return result; } printf("loading SSV functions\n"); if ((result = init_ssv_library("libssv", &libssv, TAGGANT_LIBRARY_VERSION2, rootdata, tsrootdata, &context ) ) != ERR_NONE ) { cleanup_ssv(LVL_FREEDLL, libssv, tsrootdata, rootdata, 0, result ); return result; } printf("performing PE validation tests\n"); if ((result = test_ssv_pe(context, rootdata, tsrootdata, tag32_len, tag64_len ) ) != ERR_NONE ) { cleanup_ssv(LVL_FINALISE, context, libssv, tsrootdata, rootdata, 0, result ); return result; } printf("performing JS validation tests\n"); result = test_ssv_js(context, rootdata ); cleanup_ssv(LVL_FINALISE, context, libssv, tsrootdata, rootdata, 0, result ); if (result != ERR_NONE) { return result; } printf("completed verification tests\n"); return ERR_NONE; } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #ifndef TAGGANTLIB_HEADER #define TAGGANTLIB_HEADER #include "taggant_types.h" #ifdef TAGGANT_LIBRARY #include "types.h" #endif #ifdef _WIN32 # define STDCALL __stdcall #else # define STDCALL #endif #if defined(_WIN32) && !defined(TAGGANT_STATIC) # ifdef __cplusplus # define EXPORT extern "C" __declspec (dllexport) # else # define EXPORT __declspec (dllexport) # endif #else # ifdef __cplusplus # define EXPORT extern "C" # else # define EXPORT # endif #endif #ifdef __GNUC__ #define DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) #define DEPRECATED __declspec(deprecated) #else #pragma message("WARNING: DEPRECATED attribute is not supported by the compiler") #define DEPRECATED #endif /* #define SSV_LIBRARY */ /* #define SPV_LIBRARY */ EXPORT UNSIGNED32 STDCALL TaggantInitializeLibrary(__in_opt TAGGANTFUNCTIONS *pFuncs, __out UNSIGNED64 *puVersion); EXPORT void STDCALL TaggantFinalizeLibrary(void); EXPORT PTAGGANTOBJ STDCALL TaggantObjectNew(__in_opt PTAGGANT pTaggant); EXPORT __success(return == TNOERR) UNSIGNED32 STDCALL TaggantObjectNewEx(__in_opt PTAGGANT pTaggant, UNSIGNED64 uVersion, TAGGANTCONTAINER eTaggantType, __out PTAGGANTOBJ *pTaggantObj); EXPORT void STDCALL TaggantObjectFree(__deref PTAGGANTOBJ pTaggantObj); EXPORT PTAGGANTCONTEXT STDCALL TaggantContextNew(void); EXPORT __success(return == TNOERR) UNSIGNED32 STDCALL TaggantContextNewEx(__out PTAGGANTCONTEXT *pCtx); EXPORT void STDCALL TaggantContextFree(__deref PTAGGANTCONTEXT pTaggantCtx); /* Deprecated function, use TaggantGetInfo/TaggantPutInfo with EPACKERINFO parameter instead */ EXPORT DEPRECATED PPACKERINFO STDCALL TaggantPackerInfo(__in PTAGGANTOBJ pTaggantObj); #ifdef SSV_LIBRARY EXPORT __success(return > 0) UNSIGNED16 STDCALL TaggantGetHashMapDoubles(__in PTAGGANTOBJ pTaggantObj, __out PHASHBLOB_HASHMAP_DOUBLE *pDoubles); EXPORT UNSIGNED32 STDCALL TaggantValidateDefaultHashes(__in PTAGGANTCONTEXT pCtx, __in PTAGGANTOBJ pTaggantObj, __in PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd); EXPORT UNSIGNED32 STDCALL TaggantValidateHashMap(__in PTAGGANTCONTEXT pCtx, __in PTAGGANTOBJ pTaggantObj, __in PFILEOBJECT hFile); EXPORT UNSIGNED32 STDCALL TaggantGetTaggant(__in PTAGGANTCONTEXT pCtx, __in PFILEOBJECT hFile, TAGGANTCONTAINER eContainer, __inout PTAGGANT *pTaggant); EXPORT void STDCALL TaggantFreeTaggant(__deref PTAGGANT pTaggant); EXPORT UNSIGNED32 STDCALL TaggantValidateSignature(__in PTAGGANTOBJ pTaggantObj, __in PTAGGANT pTaggant, __in PVOID pRootCert); EXPORT UNSIGNED32 STDCALL TaggantGetInfo(__in PTAGGANTOBJ pTaggantObj, ENUMTAGINFO eKey, __inout UNSIGNED32 *pSize, __out_bcount_full_opt(*pSize) PINFO pInfo); EXPORT __success(return == TNOERR) UNSIGNED32 STDCALL TaggantGetTimestamp(__in PTAGGANTOBJ pTaggantObj, __out UNSIGNED64 *pTime, __in PVOID pTSRootCert); EXPORT UNSIGNED32 STDCALL TaggantCheckCertificate(__in PVOID pCert); #endif #ifdef SPV_LIBRARY EXPORT UNSIGNED32 STDCALL TaggantPutInfo(__inout PTAGGANTOBJ pTaggantObj, ENUMTAGINFO eKey, UNSIGNED32 pSize, __in_bcount(pSize) PINFO pInfo); EXPORT UNSIGNED32 STDCALL TaggantComputeHashes(__in PTAGGANTCONTEXT pCtx, __inout PTAGGANTOBJ pTaggantObj, __in PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd, UNSIGNED32 uTaggantSize); EXPORT __success(return == TNOERR) UNSIGNED32 STDCALL TaggantGetLicenseExpirationDate(__in const PVOID pLicense, __out UNSIGNED64 *pTime); EXPORT UNSIGNED32 STDCALL TaggantAddHashRegion(__inout PTAGGANTOBJ pTaggantObj, UNSIGNED64 uOffset, UNSIGNED64 uLength); EXPORT UNSIGNED32 STDCALL TaggantPrepare(__inout PTAGGANTOBJ pTaggantObj, __in const PVOID pLicense, __out_bcount_part(*uTaggantReservedSize, *uTaggantReservedSize) PVOID pTaggantOut, __inout UNSIGNED32 *uTaggantReservedSize); EXPORT UNSIGNED32 STDCALL TaggantPutTimestamp(__inout PTAGGANTOBJ pTaggantObj, __in const char* pTSUrl, UNSIGNED32 uTimeout); #endif #endif /* TAGGANTLIB_HEADER */ <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include "global.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "types.h" #include "taggant.h" #include "taggant2.h" #include "winpe.h" #include "miscellaneous.h" #include "callbacks.h" #include "endianness.h" #include "taggant_types.h" #include "timestamp.h" #include "verify_helper.h" #include <openssl/sha.h> #include <openssl/err.h> #include <openssl/pem.h> #ifdef SSV_LIBRARY /* * Create X509 certificate from the buffer. * Buffer must contain base64 encoded certificate (PEM format) * Caller must free returned certificate after usage */ X509* buffer_to_X509(PVOID pCert) { BIO* certbio = NULL; X509* cert = NULL; if (pCert) { certbio = BIO_new(BIO_s_mem()); if (certbio) { BIO_write(certbio, pCert, (int)strlen((const char*)pCert)); /* Load certificate */ cert = PEM_read_bio_X509(certbio, NULL, 0, NULL); /* Free bio */ BIO_free(certbio); } } return cert; } /* Check if the "null area" contains only zeros * Null area is a region between end of CMS and end of pTaggant.CMS structure */ int check_null_area(PTAGGANT1 pTaggant) { int i; /* pTaggant->Header.TaggantLength is always greater than the sum of sizeof(TAGGANT_HEADER) and sizeof(TAGGANT_FOOTER) */ for (i = (int)pTaggant->Header.CMSLength; i < (int)(pTaggant->Header.TaggantLength - sizeof(TAGGANT_HEADER) - sizeof(TAGGANT_FOOTER)); i++) { if (((char*)pTaggant->CMSBuffer)[i] != '\0') { return 0; } } return 1; } UNSIGNED32 taggant_compare_hash_map(PTAGGANTBLOB pTagBlob1, PTAGGANTBLOB pTagBlob2) { UNSIGNED32 res = TMISMATCH; if (pTagBlob1->Hash.Hashmap.Header.Version == pTagBlob2->Hash.Hashmap.Header.Version && pTagBlob1->Hash.Hashmap.Header.Version == HASHBLOB_VERSION1 && pTagBlob1->Hash.Hashmap.Header.Type == pTagBlob2->Hash.Hashmap.Header.Type && pTagBlob1->Hash.Hashmap.Header.Type == TAGGANT_HASBLOB_HASHMAP && pTagBlob1->Hash.Hashmap.Entries == pTagBlob2->Hash.Hashmap.Entries && (memcmp((char*)pTagBlob1 + pTagBlob1->Hash.Hashmap.DoublesOffset, (char*)pTagBlob2 + pTagBlob2->Hash.Hashmap.DoublesOffset, pTagBlob1->Hash.Hashmap.Entries * sizeof(HASHBLOB_HASHMAP_DOUBLE)) == 0) && (memcmp(&pTagBlob1->Hash.Hashmap.Header.Hash, &pTagBlob2->Hash.Hashmap.Header.Hash, sizeof(pTagBlob1->Hash.Hashmap.Header.Hash)) == 0)) { res = TNOERR; } return res; } #endif void taggant_free_taggant(PTAGGANT1 pTaggant) { /* Make sure taggant object is not null */ if (pTaggant) { if (pTaggant->CMSBuffer) { memory_free(pTaggant->CMSBuffer); } memory_free(pTaggant); } } UNSIGNED32 compute_region_hash(PTAGGANTCONTEXT pCtx, PFILEOBJECT hFile, EVP_MD_CTX* evp, HASHBLOB_HASHMAP_DOUBLE* region, char* buf) { UNSIGNED64 bytestoread; UNSIGNED64 bytesread; if (file_seek(pCtx, hFile, region->AbsoluteOffset, SEEK_SET)) { bytestoread = region->Length; while (bytestoread != 0) { bytesread = (bytestoread >= HASH_READ_BLOCK) ? HASH_READ_BLOCK : bytestoread; if (file_read_buffer(pCtx, hFile, buf, (size_t)bytesread)) { EVP_DigestUpdate(evp, buf, (size_t)bytesread); bytestoread -= bytesread; } else { return TFILEACCESSDENIED; } } return TNOERR; } return TFILEACCESSDENIED; } /* * Bubble sort an array of hashmap doubles. * lenindex contains "array length" - 1 value. */ void bubblesort_hashmap(PHASHBLOB_HASHMAP_DOUBLE regions, UNSIGNED32 lenindex) { int i, j; HASHBLOB_HASHMAP_DOUBLE t; if (lenindex) { for (i = (int)lenindex; i >= 0; i--) { for (j = 0; j <= (int)lenindex - 1; j++) { if (regions[j].AbsoluteOffset > regions[j + 1].AbsoluteOffset) { t = regions[j]; regions[j] = regions[j + 1]; regions[j + 1] = t; } } } } } int exclude_region_from_hashmap(PHASHBLOB_HASHMAP_DOUBLE regions, UNSIGNED64 offset, UNSIGNED64 size) { int i = 0, j = 0; int arraylen = 0, newarraylen = 0; HASHBLOB_HASHMAP_DOUBLE t; if (size) { /* search the index that has to be divided and free index */ for (i = 0; i < HASHMAP_MAX_LENGTH; i++) { if (regions[i].AbsoluteOffset || regions[i].Length) { if (offset > regions[i].AbsoluteOffset && offset < (regions[i].AbsoluteOffset + regions[i].Length) && (offset + size) < (regions[i].AbsoluteOffset + regions[i].Length)) { /* Find free region */ for (j = 0; j < HASHMAP_MAX_LENGTH; j++) { if (regions[j].AbsoluteOffset == 0 && regions[j].Length == 0) { /* divide the region */ regions[j].AbsoluteOffset = offset + size; regions[j].Length = (regions[i].AbsoluteOffset + regions[i].Length) - regions[j].AbsoluteOffset; arraylen = j + 1; break; } } regions[i].Length = offset - regions[i].AbsoluteOffset; /* Break the loop */ break; } else if (offset <= regions[i].AbsoluteOffset && (offset + size) > regions[i].AbsoluteOffset && (offset + size) < (regions[i].AbsoluteOffset + regions[i].Length)) { /* Truncate region from begin */ regions[i].Length -= (offset + size) - regions[i].AbsoluteOffset; regions[i].AbsoluteOffset = offset + size; } else if (offset >= regions[i].AbsoluteOffset && offset < (regions[i].AbsoluteOffset + regions[i].Length) && (offset + size) >= (regions[i].AbsoluteOffset + regions[i].Length)) { /* Truncate region from end */ regions[i].Length = offset - regions[i].AbsoluteOffset; } else if (offset <= regions[i].AbsoluteOffset && (offset + size) >= (regions[i].AbsoluteOffset + regions[i].Length)) { /* Delete region at all */ regions[i].AbsoluteOffset = 0; regions[i].Length = 0; } arraylen++; } else { break; } } newarraylen = 0; /* Sort regions and move items with zero size at the end of array */ for (i = arraylen-1; i >= 0; i--) { for (j = 0; j <= arraylen - 2; j++) { if (regions[j].Length < regions[j + 1].Length) { t = regions[j]; regions[j] = regions[j + 1]; regions[j + 1] = t; } } } newarraylen = 0; for (i = 0; i < arraylen; i++) { if (regions[i].Length == 0) { regions[i].AbsoluteOffset = 0; } else { newarraylen++; } } if (newarraylen) { bubblesort_hashmap(regions, newarraylen - 1); } } else { for (i = 0; i < HASHMAP_MAX_LENGTH; i++) { if (regions[i].AbsoluteOffset != 0 || regions[i].Length != 0) { newarraylen++; } } } return newarraylen; } UNSIGNED32 taggant_compute_default_hash(PTAGGANTCONTEXT pCtx, PHASHBLOB_FULLFILE pHash, PFILEOBJECT hFile, PE_ALL_HEADERS *peh, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd, UNSIGNED32 uTaggantSize) { UNSIGNED32 res = TINVALIDPEFILE; /* for the default hash there are HASHMAP_MAX_LENGTH number of regions is needed * Full File Hash contains from a hash of two regions: * - from file start to end of PE file (default hash) * - from end of PE file to end of physical file (extended hash) * * For the first region we have to exclude from the hashing: * - Checksum from optinal header * - Digital Signature header from optinal header * - Taggant itself * * For the second region, we have to exclude from hashing: * - Taggant itself */ HASHBLOB_HASHMAP_DOUBLE regions[HASHMAP_MAX_LENGTH]; UNSIGNED64 fileend = uFileEnd, filesize; UNSIGNED64 epoffset; UNSIGNED64 taggantoffset; EVP_MD_CTX evp, evp_ext; char* buf = NULL; int i, len; filesize = get_file_size(pCtx, hFile); /* Check if the end of physical file is less then end of PE file */ if (fileend == 0) { fileend = filesize; } if (fileend < uObjectEnd) { return TFILEERROR; } /* Calculate default hash */ memset(&regions, 0, sizeof(regions)); /* set the entire file region from file start to file end by default */ regions[0].AbsoluteOffset = 0; regions[0].Length = uObjectEnd; /* exclude Checksum from region */ exclude_region_from_hashmap(&regions[0], peh->dh.e_lfanew + sizeof(peh->signature) + sizeof(peh->fh) + 64, sizeof(UNSIGNED32)); /* exclude PE Header Digital Signature */ if (winpe_is_pe64(peh)) { exclude_region_from_hashmap(&regions[0], peh->dh.e_lfanew + sizeof(peh->signature) + sizeof(peh->fh) + 144, sizeof(TAG_IMAGE_DATA_DIRECTORY)); } else { exclude_region_from_hashmap(&regions[0], peh->dh.e_lfanew + sizeof(peh->signature) + sizeof(peh->fh) + 128, sizeof(TAG_IMAGE_DATA_DIRECTORY)); } if (!winpe_entry_point_physical_offset(pCtx, hFile, peh, &epoffset)) { return TINVALIDPEENTRYPOINT; } /* exclude taggant */ if (!winpe_taggant_physical_offset(pCtx, hFile, peh, epoffset, &taggantoffset)) { return TINVALIDTAGGANTOFFSET; } /* make sure that (taggant offset + taggant length) does not point outside of the file */ if ((taggantoffset + uTaggantSize) > filesize) { return TINVALIDTAGGANTOFFSET; } len = exclude_region_from_hashmap(&regions[0], taggantoffset, uTaggantSize); /* allocate buffer for file reading */ buf = (char*)memory_alloc(HASH_READ_BLOCK); if (!buf) { return TMEMORY; } /* calculate hash */ EVP_MD_CTX_init (&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); for (i = 0; i < len; i++) { if ((res = compute_region_hash(pCtx, hFile, &evp, &regions[i], buf)) != TNOERR) { break; } } if (res == TNOERR) { memset(pHash, 0, sizeof(HASHBLOB_FULLFILE)); pHash->DefaultHash.Header.Type = TAGGANT_HASBLOB_DEFAULT; pHash->DefaultHash.Header.Length = sizeof(HASHBLOB_DEFAULT); pHash->DefaultHash.Header.Version = HASHBLOB_VERSION1; /* Copy context before destroying it by calling EVP_DigestFinal_ex */ EVP_MD_CTX_copy(&evp_ext, &evp); /* Get default file hash */ EVP_DigestFinal_ex(&evp, pHash->DefaultHash.Header.Hash, NULL); /* Calculate extended hash */ pHash->ExtendedHash.Header.Type = TAGGANT_HASBLOB_EXTENDED; pHash->ExtendedHash.Header.Length = sizeof(HASHBLOB_EXTENDED); pHash->ExtendedHash.Header.Version = HASHBLOB_VERSION1; /* remember the file end offset */ pHash->ExtendedHash.PhysicalEnd = uFileEnd; memset(&regions, 0, sizeof(regions)); /* set the initial region for extended file hash from end of PE file to end of physical file */ regions[0].AbsoluteOffset = uObjectEnd; regions[0].Length = fileend - uObjectEnd; if (regions[0].Length != 0) { /* Exclude the taggant from the extended hash */ len = exclude_region_from_hashmap(&regions[0], taggantoffset, uTaggantSize); for (i = 0; i < len; i++) { if ((res = compute_region_hash(pCtx, hFile, &evp_ext, &regions[i], buf)) != TNOERR) { break; } } if (res == TNOERR) { EVP_DigestFinal_ex(&evp_ext, pHash->ExtendedHash.Header.Hash, NULL); } } /* Clean extended hashing context */ EVP_MD_CTX_cleanup (&evp_ext); } memory_free(buf); /* Clean main hashing context */ EVP_MD_CTX_cleanup (&evp); return res; } UNSIGNED32 taggant_compute_hash_map(PTAGGANTCONTEXT pCtx, PFILEOBJECT hFile, PTAGGANTBLOB pTagBlob) { UNSIGNED32 res = TFILEACCESSDENIED; EVP_MD_CTX evp; char* buf = NULL; int i; PHASHBLOB_HASHMAP_DOUBLE hmd; /* Compute hashes */ EVP_MD_CTX_init (&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* allocate buffer for file reading */ buf = (char*)memory_alloc(HASH_READ_BLOCK); if (buf) { /* compute hashmaps */ hmd = (PHASHBLOB_HASHMAP_DOUBLE)((char*)pTagBlob + sizeof(TAGGANTBLOB)); for (i = 0; i < pTagBlob->Hash.Hashmap.Entries; i++) { if ((res = compute_region_hash(pCtx, hFile, &evp, hmd, buf)) != TNOERR) { break; } hmd++; } memory_free(buf); } else { res = TMEMORY; } if (res == TNOERR) { pTagBlob->Hash.Hashmap.DoublesOffset = sizeof(TAGGANTBLOB); pTagBlob->Hash.Hashmap.Header.Type = TAGGANT_HASBLOB_HASHMAP; pTagBlob->Hash.Hashmap.Header.Length = sizeof(HASHBLOB_HASHMAP); pTagBlob->Hash.Hashmap.Header.Version = HASHBLOB_VERSION1; EVP_DigestFinal_ex(&evp, pTagBlob->Hash.Hashmap.Header.Hash, NULL); } EVP_MD_CTX_cleanup (&evp); return res; } #ifdef SPV_LIBRARY UNSIGNED32 taggant_prepare(PTAGGANTOBJ1 pTaggantObj, const PVOID pLicense, PVOID pTaggantOut, UNSIGNED32 *uTaggantReservedSize) { UNSIGNED32 res = TBADKEY; BIO* licbio = NULL; X509* liccert = NULL, * licspv = NULL; EVP_PKEY* lickey = NULL; BIO* inbio = NULL; BIO* cmsbio = NULL; UNSIGNED32 cmslength = 0; int maxlen = MAX_INTEGER; STACK_OF(X509) *intermediate = NULL; char *tmptb = NULL, *tagbuffer = NULL; /* Load user license certificate and private key */ licbio = BIO_new(BIO_s_mem()); if (licbio) { BIO_write(licbio, pLicense, (int)strlen((const char*)pLicense)); licspv = PEM_read_bio_X509(licbio, NULL, 0, NULL); if (licspv) { liccert = PEM_read_bio_X509(licbio, NULL, 0, NULL); if (liccert) { lickey = PEM_read_bio_PrivateKey(licbio, NULL, 0, NULL); if (lickey) { inbio = BIO_new(BIO_s_mem()); if (inbio) { /* Allocate buffer for copy of taggant blob */ tmptb = memory_alloc(pTaggantObj->pTagBlob->Header.Length); if (tmptb) { /* Copy TAGGANTBLOB */ memcpy(tmptb, pTaggantObj->pTagBlob, pTaggantObj->pTagBlob->Header.Length); if (IS_BIG_ENDIAN) { /* Convert TAGGANTBLOB to little endian */ TAGGANTBLOB_to_little_endian((PTAGGANTBLOB)tmptb, (PTAGGANTBLOB)tmptb); } BIO_write(inbio, tmptb, pTaggantObj->pTagBlob->Header.Length); /* Push TSA response to the CMS signed data */ i2d_TS_RESP_bio(inbio, pTaggantObj->TSResponse); /* Create store with intermediate certificate(s) */ intermediate = sk_X509_new_null(); if (intermediate) { if (sk_X509_push(intermediate, licspv)) { /* Sign CMS */ pTaggantObj->CMS = CMS_sign(liccert, lickey, intermediate, inbio, CMS_BINARY); if (pTaggantObj->CMS) { cmsbio = BIO_new(BIO_s_mem()); if (cmsbio) { if (i2d_CMS_bio(cmsbio, pTaggantObj->CMS)) { /* Get bio size */ maxlen = MAX_INTEGER; cmslength = (UNSIGNED32)BIO_read(cmsbio, NULL, maxlen); /* Make sure the buffer reserved for taggant is enough */ if (*uTaggantReservedSize >= (sizeof(TAGGANT_HEADER) + cmslength + sizeof(TAGGANT_FOOTER))) { tagbuffer = pTaggantOut; /* Clear buffer for taggant */ memset(tagbuffer, 0, *uTaggantReservedSize); /* Fill out taggant header */ ((PTAGGANT_HEADER)tagbuffer)->MarkerBegin = TAGGANT_MARKER_BEGIN; ((PTAGGANT_HEADER)tagbuffer)->TaggantLength = *uTaggantReservedSize; ((PTAGGANT_HEADER)tagbuffer)->CMSLength = cmslength; ((PTAGGANT_HEADER)tagbuffer)->Version = TAGGANT_VERSION1; tagbuffer += sizeof(TAGGANT_HEADER); /* Fill out taggant CMS */ BIO_read(cmsbio, tagbuffer, cmslength); tagbuffer += *uTaggantReservedSize - sizeof(TAGGANT_FOOTER) - sizeof(TAGGANT_HEADER); /* Fill out taggant footer */ ((PTAGGANT_FOOTER)tagbuffer)->Extrablob.Length = 0; ((PTAGGANT_FOOTER)tagbuffer)->MarkerEnd = TAGGANT_MARKER_END; if (IS_BIG_ENDIAN) { TAGGANT_to_little_endian(pTaggantOut, pTaggantOut); } /* return successful result */ res = TNOERR; } else { *uTaggantReservedSize = sizeof(TAGGANT_HEADER) + cmslength + sizeof(TAGGANT_FOOTER); res = TINSUFFICIENTBUFFER; } } BIO_free(cmsbio); } } } sk_X509_free(intermediate); } memory_free(tmptb); } BIO_free(inbio); } EVP_PKEY_free(lickey); } X509_free(liccert); } X509_free(licspv); } BIO_free(licbio); } if (res != TNOERR) { if (pTaggantObj->CMS) { CMS_ContentInfo_free(pTaggantObj->CMS); pTaggantObj->CMS = NULL; } } return res; } #endif UNSIGNED32 taggant_read_binary(PTAGGANTCONTEXT pCtx, PFILEOBJECT fp, PTAGGANT1 *pTaggant) { UNSIGNED32 res = TNOTAGGANTS; PE_ALL_HEADERS peh; UNSIGNED64 epoffset; UNSIGNED64 taggantoffset; PTAGGANT1 tagbuf = NULL; UNSIGNED32 tagsize; if (winpe_is_correct_pe_file(pCtx, fp, &peh)) { if (winpe_entry_point_physical_offset(pCtx, fp, &peh, &epoffset)) { if (winpe_taggant_physical_offset(pCtx, fp, &peh, epoffset, &taggantoffset)) { /* seek from the file begin to the taggant */ if (file_seek(pCtx, fp, taggantoffset, SEEK_SET)) { /* allocate memory for taggant */ tagbuf = memory_alloc(sizeof(TAGGANT1)); if (tagbuf) { memset(tagbuf, 0, sizeof(TAGGANT1)); /* read taggant header */ if (file_read_buffer(pCtx, fp, &tagbuf->Header, sizeof(TAGGANT_HEADER))) { if (IS_BIG_ENDIAN) { TAGGANT_HEADER_to_big_endian(&tagbuf->Header, &tagbuf->Header); } if (tagbuf->Header.Version == TAGGANT_VERSION1 && tagbuf->Header.MarkerBegin == TAGGANT_MARKER_BEGIN && tagbuf->Header.TaggantLength >= TAGGANT_MINIMUM_SIZE && tagbuf->Header.TaggantLength <= TAGGANT_MAXIMUM_SIZE && tagbuf->Header.CMSLength && (tagbuf->Header.CMSLength <= (tagbuf->Header.TaggantLength - sizeof(TAGGANT_HEADER) - sizeof(TAGGANT_FOOTER)))) { /* allocate buffer for CMS */ tagsize = tagbuf->Header.TaggantLength - sizeof(TAGGANT_HEADER) - sizeof(TAGGANT_FOOTER); tagbuf->CMSBuffer = memory_alloc(tagsize); if (tagbuf->CMSBuffer) { memset(tagbuf->CMSBuffer, 0, tagsize); /* read CMS */ if (file_read_buffer(pCtx, fp, tagbuf->CMSBuffer, tagsize)) { /* read taggant footer */ if (file_read_buffer(pCtx, fp, &tagbuf->Footer, sizeof(TAGGANT_FOOTER))) { if (IS_BIG_ENDIAN) { TAGGANT_FOOTER_to_big_endian(&tagbuf->Footer, &tagbuf->Footer); } if (tagbuf->Footer.MarkerEnd == TAGGANT_MARKER_END) { tagbuf->offset = taggantoffset; *pTaggant = tagbuf; res = TNOERR; } else { res = TNOTAGGANTS; } } else { res = TFILEACCESSDENIED; } } else { res = TFILEACCESSDENIED; } } else { res = TMEMORY; } } else { res = TNOTAGGANTS; } } else { res = TFILEACCESSDENIED; } if (res != TNOERR) { taggant_free_taggant(tagbuf); } } else { res = TMEMORY; } } else { res = TFILEACCESSDENIED; } } else { res = TINVALIDTAGGANTOFFSET; } } else { res = TINVALIDPEENTRYPOINT; } } else { res = TINVALIDPEFILE; } return res; } #ifdef SSV_LIBRARY /* This function saves CMS to the BIO and returns it's size * It is used to check if the CMSLength parameter from TAGGANT_HEADER is correct */ UNSIGNED32 get_cms_size(CMS_ContentInfo *cms) { UNSIGNED32 res = 0; BIO *bio = NULL; int maxlen = MAX_INTEGER; bio = BIO_new(BIO_s_mem()); if (bio) { if (i2d_CMS_bio(bio, cms)) { /* Get bio size */ res = (UNSIGNED32)BIO_read(bio, NULL, maxlen); } BIO_free(bio); } return res; } UNSIGNED32 taggant_validate_signature(PTAGGANTOBJ1 pTaggantObj, PTAGGANT1 pTaggant, PVOID pRootCert) { UNSIGNED32 res = TBADKEY; BIO *cmsbio = NULL; BIO *signedbio = NULL; BIO *tsbio = NULL; X509_STORE *trusted_store = NULL; X509_VERIFY_PARAM *vpm = NULL; char *buf = NULL, *tmpbuf; int biolength = 0; int tagsize; X509* tmpcer; STACK_OF(X509) *cms_certs = NULL; int maxlen = MAX_INTEGER, err; EVP_PKEY *pkey; res = TBADKEY; /* Load root certificate */ pTaggantObj->root = buffer_to_X509(pRootCert); if (pTaggantObj->root) { /* Compare taggant version */ if (pTaggant->Header.Version == TAGGANT_VERSION1 && pTaggant->Header.CMSLength > 0) { cmsbio = BIO_new(BIO_s_mem()); if (cmsbio) { BIO_write(cmsbio, pTaggant->CMSBuffer, pTaggant->Header.CMSLength); pTaggantObj->CMS = d2i_CMS_bio(cmsbio, NULL); if (pTaggantObj->CMS) { /* Check if CMS size matches the one from the header */ if (get_cms_size(pTaggantObj->CMS) == pTaggant->Header.CMSLength) { /* Check the "null area" */ if (check_null_area(pTaggant)) { signedbio = BIO_new(BIO_s_mem()); if (signedbio) { /* Create a store with trusted certificates */ trusted_store = X509_STORE_new(); if (trusted_store) { /* Add root certificate to the trusted store */ if (X509_STORE_add_cert(trusted_store, pTaggantObj->root)) { vpm = X509_VERIFY_PARAM_new(); if (vpm) { /* We have to set the purpose to "any" to be used for signing certificate CMS_Verify expects that signer certificate has the purpose "smimeencrypt" but it does not. */ X509_VERIFY_PARAM_set_purpose(vpm, X509_PURPOSE_ANY); X509_STORE_set1_param(trusted_store, vpm); /* Set the custom cb function to suppress certificate time errors */ X509_STORE_set_verify_cb(trusted_store, verify_cms_cb); if (CMS_verify(pTaggantObj->CMS, NULL, trusted_store, NULL, signedbio, CMS_BINARY)) { /* Make sure there are 2 certificate in CMS */ cms_certs = CMS_get1_certs(pTaggantObj->CMS); if (cms_certs) { if (sk_X509_num(cms_certs) == CERTIFICATES_IN_TAGGANT_CHAIN) { /* Set the spv and user certificates, check first certificate against second one */ pTaggantObj->spv = X509_dup(sk_X509_value(cms_certs, 0)); pTaggantObj->user = X509_dup(sk_X509_value(cms_certs, 1)); pkey = X509_get_pubkey(pTaggantObj->spv); if (pkey) { if (!X509_verify(pTaggantObj->user, pkey)) { tmpcer = pTaggantObj->user; pTaggantObj->user = pTaggantObj->spv; pTaggantObj->spv = tmpcer; } EVP_PKEY_free(pkey); } /* CMS is OK, next try to read a timestamp */ res = TMEMORY; /* get size of the signed data */ biolength = BIO_read(signedbio, NULL, maxlen); buf = (char*)memory_alloc(biolength); if (buf) { BIO_read(signedbio, buf, biolength); /* Check if buffer has enough size for taggant blob */ if (biolength >= sizeof(TAGGANTBLOB)) { tagsize = ((PTAGGANTBLOB)buf)->Header.Length; if (IS_BIG_ENDIAN) { tagsize = UNSIGNED16_to_big_endian((char*)&tagsize); } if (biolength >= tagsize) { tmpbuf = memory_realloc(pTaggantObj->pTagBlob, tagsize); if (tmpbuf) { pTaggantObj->pTagBlob = (PTAGGANTBLOB)tmpbuf; memcpy((char*)pTaggantObj->pTagBlob, buf, tagsize); if (IS_BIG_ENDIAN) { TAGGANTBLOB_to_big_endian(pTaggantObj->pTagBlob, pTaggantObj->pTagBlob); } /* check if the hasmap doubles offset is correct */ err = 0; if (pTaggantObj->pTagBlob->Hash.Hashmap.Entries) { if (pTaggantObj->pTagBlob->Hash.Hashmap.DoublesOffset != sizeof(TAGGANTBLOB)) { err = 1; } else { /* Make sure TAGGANTBLOB fits add hashmap doubles */ if (pTaggantObj->pTagBlob->Header.Length != sizeof(TAGGANTBLOB) + pTaggantObj->pTagBlob->Hash.Hashmap.Entries * sizeof(HASHBLOB_HASHMAP_DOUBLE)) { err = 1; } } } if (!err) { /* check if the timestamp response exists in the taggant */ if ((biolength - (int)pTaggantObj->pTagBlob->Header.Length) > 0) { /* load TS response, better to use d2i_TS_RESP instead of d2i_TS_RESP_bio */ tsbio = BIO_new(BIO_s_mem()); if (tsbio) { BIO_write(tsbio, buf + pTaggantObj->pTagBlob->Header.Length, biolength - pTaggantObj->pTagBlob->Header.Length); pTaggantObj->TSResponse = d2i_TS_RESP_bio(tsbio, NULL); BIO_free(tsbio); } } res = TNOERR; } } } } /* free memory buffer */ memory_free(buf); } } sk_X509_pop_free(cms_certs, X509_free); } } X509_VERIFY_PARAM_free(vpm); } } X509_STORE_free(trusted_store); } BIO_free(signedbio); } } } } BIO_free(cmsbio); } } } if (res != TNOERR) { taggant_free_taggantobj_content(pTaggantObj); } return res; } UNSIGNED32 taggant_compare_default_hash(PHASHBLOB_DEFAULT pHash1, PHASHBLOB_DEFAULT pHash2) { UNSIGNED32 res = TMISMATCH; /* Check if hashblob of default hashes matches */ if (pHash1->Header.Version == pHash2->Header.Version && pHash1->Header.Version == HASHBLOB_VERSION1 && pHash1->Header.Type == pHash2->Header.Type && pHash1->Header.Type == TAGGANT_HASBLOB_DEFAULT && (memcmp(&pHash1->Header.Hash, &pHash2->Header.Hash, sizeof(pHash1->Header.Hash)) == 0) ) { res = TNOERR; } return res; } UNSIGNED32 taggant_compare_extended_hash(PHASHBLOB_EXTENDED pHash1, PHASHBLOB_EXTENDED pHash2) { UNSIGNED32 res = TMISMATCH; /* Check if extended hash matches */ if (pHash1->Header.Version == pHash2->Header.Version && pHash1->Header.Version == HASHBLOB_VERSION1 && pHash1->Header.Type == pHash2->Header.Type && pHash1->Header.Type == TAGGANT_HASBLOB_EXTENDED && (memcmp(&pHash1->Header.Hash, &pHash2->Header.Hash, sizeof(pHash1->Header.Hash)) == 0) && (!pHash1->PhysicalEnd || (pHash1->PhysicalEnd == pHash2->PhysicalEnd)) ) { res = TNOERR; } return res; } UNSIGNED32 taggant_validate_default_hashes(PTAGGANTCONTEXT pCtx, PTAGGANTOBJ1 pTaggantObj, PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd) { PE_ALL_HEADERS peh; UNSIGNED32 res = TMEMORY; HASHBLOB_FULLFILE tmphb; UNSIGNED32 ds_offset, ds_size; UNSIGNED64 fileend = uFileEnd; int valid_ds = 1; int valid_file = 0; PTAGGANT2 taggant2 = NULL; if (winpe_is_correct_pe_file(pCtx, hFile, &peh)) { /* If PhysicalEnd value in the taggant = 0 then use file size as PhysicalEnd */ if (pTaggantObj->pTagBlob->Hash.FullFile.ExtendedHash.PhysicalEnd == 0) { /* if the fileend value is not specified, take the file size */ if (!fileend) { fileend = get_file_size(pCtx, hFile); } /* Check if the file contains digital signature and if it is placed at the end of the file * If it is, then reduce fileend value to exclude digital signature, otherwise * mark file as there is no taggant */ if (winpe_is_pe64(&peh)) { ds_offset = (UNSIGNED32)peh.oh.pe64.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; ds_size = (UNSIGNED32)peh.oh.pe64.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; } else { ds_offset = (UNSIGNED32)peh.oh.pe32.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; ds_size = (UNSIGNED32)peh.oh.pe32.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; } if (ds_offset != 0 && ds_size != 0) { if ((ds_offset + ds_size) != fileend) { valid_ds = 0; } else { fileend -= ds_size; } } valid_file = valid_ds; /* exclude taggant v2 */ if (valid_file) { while (taggant2_read_binary(pCtx, hFile, fileend, &taggant2, TAGGANT_PEFILE) == TNOERR) { fileend -= taggant2->Header.TaggantLength; /* Free the taggant object */ taggant2_free_taggant(taggant2); } } } else { fileend = pTaggantObj->pTagBlob->Hash.FullFile.ExtendedHash.PhysicalEnd; valid_file = 1; } if (valid_file && (!uFileEnd || (uFileEnd && fileend <= uFileEnd))) { /* Allocate a copy of taggant blob */ tmphb = pTaggantObj->pTagBlob->Hash.FullFile; /* Compute default hash */ if ((res = taggant_compute_default_hash(pCtx, &tmphb, hFile, &peh, uObjectEnd, fileend, pTaggantObj->uTaggantSize)) == TNOERR) { if ((res = taggant_compare_default_hash(&pTaggantObj->pTagBlob->Hash.FullFile.DefaultHash, &tmphb.DefaultHash)) == TNOERR) { res = taggant_compare_extended_hash(&pTaggantObj->pTagBlob->Hash.FullFile.ExtendedHash, &tmphb.ExtendedHash); } } } else { res = TERROR; } } else { res = TINVALIDPEFILE; } return res; } UNSIGNED32 taggant_validate_hashmap(PTAGGANTCONTEXT pCtx, PTAGGANTOBJ1 pTaggantObj, PFILEOBJECT hFile) { UNSIGNED32 res = TMEMORY; PTAGGANTBLOB ptmpb = NULL; PHASHBLOB_HASHMAP_DOUBLE hmd; int i; if ((pTaggantObj->pTagBlob->Hash.Hashmap.DoublesOffset + (pTaggantObj->pTagBlob->Hash.Hashmap.Entries * sizeof(HASHBLOB_HASHMAP_DOUBLE))) > pTaggantObj->pTagBlob->Header.Length) { return TMEMORY; } /* Allocate a copy of taggant blob */ ptmpb = (PTAGGANTBLOB)memory_alloc(pTaggantObj->pTagBlob->Header.Length); if (ptmpb) { res = TNOERR; memcpy(ptmpb, pTaggantObj->pTagBlob, pTaggantObj->pTagBlob->Header.Length); /* Make sure the regions in hashmap are ordered correctly (from lowest offset to highest) */ hmd = (PHASHBLOB_HASHMAP_DOUBLE)((char*)ptmpb + sizeof(TAGGANTBLOB)); for (i = 1; i < ptmpb->Hash.Hashmap.Entries; i++) { if (hmd[i - 1].AbsoluteOffset >= hmd[i].AbsoluteOffset) { res = TERROR; break; } } if (res == TNOERR) { /* Check if hashmap contains regions with zero size */ for (i = 0; i < ptmpb->Hash.Hashmap.Entries; i++) { if (hmd[i].Length == 0) { res = TERROR; break; } } } if (res == TNOERR) { /* Compute hash map */ res = taggant_compute_hash_map(pCtx, hFile, ptmpb); if (res == TNOERR) { res = taggant_compare_hash_map(pTaggantObj->pTagBlob, ptmpb); } } memory_free(ptmpb); } return res; } UNSIGNED32 taggant_get_timestamp(PTAGGANTOBJ1 pTaggantObj, UNSIGNED64 *pTime, PVOID pTSRootCert) { UNSIGNED32 res = TERROR; char hash[HASH_SHA256_DIGEST_SIZE]; char* ptmp = NULL; BIO *tmpbio; EVP_MD_CTX evp; int year = 0; int month = 0; int day = 0; int hour = 0; int minute = 0; int second = 0; int temp; int err = 0; X509 *cert = NULL; X509_STORE *store; TS_TST_INFO* tstInfo = NULL; const ASN1_GENERALIZEDTIME* asn1Time = NULL; if (pTaggantObj->TSResponse == NULL) { return TNOTIME; } /* Calculate the hash of the taggant blob structure */ err = 0; EVP_MD_CTX_init (&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); if (IS_BIG_ENDIAN) { /* Allocate a copy of taggant blob and convert it to little endian */ ptmp = memory_alloc(pTaggantObj->pTagBlob->Header.Length); if (ptmp) { memcpy(ptmp, pTaggantObj->pTagBlob, pTaggantObj->pTagBlob->Header.Length); TAGGANTBLOB_to_little_endian((PTAGGANTBLOB)ptmp, (PTAGGANTBLOB)ptmp); EVP_DigestUpdate(&evp, ptmp, pTaggantObj->pTagBlob->Header.Length); memory_free(ptmp); } else { err = 1; } } else { EVP_DigestUpdate(&evp, pTaggantObj->pTagBlob, pTaggantObj->pTagBlob->Header.Length); } EVP_DigestFinal_ex(&evp, (unsigned char *)&hash, NULL); EVP_MD_CTX_cleanup (&evp); /* Load all provided certificates */ if (!err) { tmpbio = BIO_new(BIO_s_mem()); if (tmpbio) { BIO_write(tmpbio, pTSRootCert, (int)strlen((const char*)pTSRootCert)); if ((store = X509_STORE_new())) { while ((cert = PEM_read_bio_X509(tmpbio, NULL, 0, NULL))) { err = X509_STORE_add_cert(store, cert) ? 0 : 1; X509_free(cert); if (err) { X509_STORE_free(store); break; } } if (!err) { if (check_time_stamp(pTaggantObj->TSResponse, store, (char*)&hash, sizeof(hash))) { tstInfo = TS_RESP_get_tst_info(pTaggantObj->TSResponse); asn1Time = TS_TST_INFO_get_time(tstInfo); temp = sscanf((const char*)ASN1_STRING_data((ASN1_STRING*)asn1Time), "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second); if (temp == 6) { *pTime = time_as_unsigned64(year, month, day, hour, minute, second); res = TNOERR; } else { res = TINVALID; } } else { res = TINVALID; } } } BIO_free(tmpbio); } } return res; } UNSIGNED32 taggant_get_info(PTAGGANTOBJ1 pTaggantObj, ENUMTAGINFO eKey, UNSIGNED32 *pSize, PINFO pInfo) { UNSIGNED32 res = TERRORKEY; int biolength = 0; BIO *tmpbio = NULL; int maxlen = MAX_INTEGER; if (pTaggantObj->CMS == NULL || pTaggantObj->pTagBlob == NULL) { return TNOTAGGANTS; } switch (eKey) { case ETAGGANTBLOB: /* get the TAGGANTBLOB information Make sure input buffer is enough to store BIO data */ if (*pSize >= pTaggantObj->pTagBlob->Header.Length && pInfo != NULL) { memcpy(pInfo, pTaggantObj->pTagBlob, pTaggantObj->pTagBlob->Header.Length); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = pTaggantObj->pTagBlob->Header.Length; break; case ESPVCERT: res = TERROR; if (pTaggantObj->spv) { tmpbio = BIO_new(BIO_s_mem()); if (tmpbio) { if (i2d_X509_bio(tmpbio, pTaggantObj->spv)) { /* Get bio size */ maxlen = MAX_INTEGER; biolength = BIO_read(tmpbio, NULL, maxlen); if (biolength >= 0) { /* Make sure input buffer is enough to store BIO data */ if (*pSize >= (UNSIGNED32)biolength && pInfo != NULL) { BIO_read(tmpbio, pInfo, biolength); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = (UNSIGNED32)biolength; } } BIO_free(tmpbio); } else { res = TMEMORY; } } break; case EUSERCERT: res = TERROR; if (pTaggantObj->user) { tmpbio = BIO_new(BIO_s_mem()); if (tmpbio) { if (i2d_X509_bio(tmpbio, pTaggantObj->user)) { /* Get bio size */ maxlen = MAX_INTEGER; biolength = BIO_read(tmpbio, NULL, maxlen); if (biolength >= 0) { /* Make sure input buffer is enough to store BIO data */ if (*pSize >= (UNSIGNED32)biolength && pInfo != NULL) { BIO_read(tmpbio, pInfo, biolength); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = (UNSIGNED32)biolength; } } BIO_free(tmpbio); } else { res = TMEMORY; } } break; case EFILEEND: /* get the PhysicalEnd value from the taggant */ if (*pSize >= sizeof(pTaggantObj->pTagBlob->Hash.FullFile.ExtendedHash.PhysicalEnd) && pInfo != NULL) { memcpy(pInfo, &pTaggantObj->pTagBlob->Hash.FullFile.ExtendedHash.PhysicalEnd, sizeof(pTaggantObj->pTagBlob->Hash.FullFile.ExtendedHash.PhysicalEnd)); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = sizeof(pTaggantObj->pTagBlob->Hash.FullFile.ExtendedHash.PhysicalEnd); break; case EPACKERINFO: /* get the packer information from the taggant */ if (*pSize >= sizeof(PACKERINFO) && pInfo != NULL) { memcpy(pInfo, &pTaggantObj->pTagBlob->Header.PackerInfo, sizeof(PACKERINFO)); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } *pSize = sizeof(PACKERINFO); break; } return res; } #endif #ifdef SPV_LIBRARY UNSIGNED32 taggant_put_timestamp(PTAGGANTOBJ1 pTaggantObj, const char* pTSUrl, UNSIGNED32 uTimeout) { UNSIGNED32 res = TNONET; char hash[HASH_SHA256_DIGEST_SIZE]; EVP_MD_CTX evp; TS_RESP* tsResponse = NULL; char* ptmp = NULL; if (pTaggantObj->TSResponse != NULL) { TS_RESP_free(pTaggantObj->TSResponse); pTaggantObj->TSResponse = NULL; } /* Calculate the hash of the taggant blob structure */ EVP_MD_CTX_init (&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); if (IS_BIG_ENDIAN) { /* Allocate a copy of taggant blob and convert it to little endian */ ptmp = memory_alloc(pTaggantObj->pTagBlob->Header.Length); if (ptmp) { memcpy(ptmp, pTaggantObj->pTagBlob, pTaggantObj->pTagBlob->Header.Length); TAGGANTBLOB_to_little_endian((PTAGGANTBLOB)ptmp, (PTAGGANTBLOB)ptmp); EVP_DigestUpdate(&evp, ptmp, pTaggantObj->pTagBlob->Header.Length); memory_free(ptmp); } else { return TMEMORY; } } else { EVP_DigestUpdate(&evp, pTaggantObj->pTagBlob, pTaggantObj->pTagBlob->Header.Length); } EVP_DigestFinal_ex(&evp, (unsigned char *)&hash, NULL); EVP_MD_CTX_cleanup (&evp); if ((res = get_timestamp_response(pTSUrl, (char*)&hash, sizeof(hash), uTimeout, &tsResponse)) == TNOERR) { pTaggantObj->TSResponse = tsResponse; } return res; } UNSIGNED32 taggant_add_hash_region(PTAGGANTOBJ1 pTaggantObj, UNSIGNED64 uOffset, UNSIGNED64 uLength) { PHASHBLOB_HASHMAP_DOUBLE hmd; HASHBLOB_HASHMAP_DOUBLE t; int i, j; UNSIGNED16 count; UNSIGNED64 a, b, c, d; char *tmpbuf; /* Check if the number of existing regions does not exceed allowed */ if (pTaggantObj->pTagBlob->Hash.Hashmap.Entries >= HASHMAP_MAXIMUM_ENTRIES) { return TENTRIESEXCEED; } /* Realloc taggant blob to contain sufficient buffer for additional region */ tmpbuf = memory_realloc(pTaggantObj->pTagBlob, pTaggantObj->pTagBlob->Header.Length + sizeof(HASHBLOB_HASHMAP_DOUBLE)); if (!tmpbuf) { return TMEMORY; } pTaggantObj->pTagBlob = (PTAGGANTBLOB)tmpbuf; hmd = (PHASHBLOB_HASHMAP_DOUBLE) ((char*)pTaggantObj->pTagBlob + sizeof(TAGGANTBLOB)); hmd[pTaggantObj->pTagBlob->Hash.Hashmap.Entries].AbsoluteOffset = uOffset; hmd[pTaggantObj->pTagBlob->Hash.Hashmap.Entries].Length = uLength; /* bubble sort hashmap array */ bubblesort_hashmap(hmd, pTaggantObj->pTagBlob->Hash.Hashmap.Entries); pTaggantObj->pTagBlob->Hash.Hashmap.Entries++; /* increase size of taggant blob */ pTaggantObj->pTagBlob->Header.Length += sizeof(HASHBLOB_HASHMAP_DOUBLE); /* searching for overlapped regions */ count = 0; for (i = 0; i < pTaggantObj->pTagBlob->Hash.Hashmap.Entries - 1; i++) { a = b = hmd[i].AbsoluteOffset; b += hmd[i].Length; c = d = hmd[i+1].AbsoluteOffset; d += hmd[i+1].Length; if (((a >= c) && (a <= d)) || ((b >= c) && (b <= d)) || ((c >= a) && (c <= b)) || ((d >= a) && (d <= b))) { /* overlapping here */ hmd[i+1].AbsoluteOffset = (a < c) ? a : c; hmd[i+1].Length = (b > d) ? b - hmd[i+1].AbsoluteOffset : d - hmd[i+1].AbsoluteOffset; hmd[i].AbsoluteOffset = 0; hmd[i].Length = 0; count++; } } /* if overlapped regions are found, then resize the array and remove zero size regions */ if (count > 0) { /* sort in descending order to move zero size regions at the end of array */ for (i = pTaggantObj->pTagBlob->Hash.Hashmap.Entries - 1; i >= 0; i--) { for (j = 0; j <= pTaggantObj->pTagBlob->Hash.Hashmap.Entries - 2; j++) { if (hmd[j].Length < hmd[j + 1].Length) { t = hmd[j]; hmd[j] = hmd[j + 1]; hmd[j + 1] = t; } } } /* decrease Entries on a number of intersections */ pTaggantObj->pTagBlob->Hash.Hashmap.Entries = pTaggantObj->pTagBlob->Hash.Hashmap.Entries - count; /* decrease the size of TaggantBlob */ pTaggantObj->pTagBlob->Header.Length -= count * sizeof(HASHBLOB_HASHMAP_DOUBLE); /* sort regions array */ bubblesort_hashmap(hmd, pTaggantObj->pTagBlob->Hash.Hashmap.Entries - 1); /* realloc TaggantBlob*/ tmpbuf = memory_realloc(pTaggantObj->pTagBlob, pTaggantObj->pTagBlob->Header.Length); if (!tmpbuf) { return TMEMORY; } pTaggantObj->pTagBlob = (PTAGGANTBLOB)tmpbuf; } return TNOERR; } UNSIGNED32 taggant_put_info(PTAGGANTOBJ1 pTaggantObj, ENUMTAGINFO eKey, UNSIGNED32 uSize, PINFO pInfo) { UNSIGNED32 res = TERRORKEY; switch (eKey) { case EPACKERINFO: /* set the packer information to the taggant */ if (uSize >= sizeof(PACKERINFO) && pInfo != NULL) { memcpy(&pTaggantObj->pTagBlob->Header.PackerInfo, pInfo, sizeof(PACKERINFO)); res = TNOERR; } else { res = TINSUFFICIENTBUFFER; } break; } return res; } #endif void taggant_free_taggantobj_content(PTAGGANTOBJ1 pTaggantObj) { /* Free taggant blob */ if (pTaggantObj->pTagBlob) { memory_free(pTaggantObj->pTagBlob); pTaggantObj->pTagBlob = NULL; } /* Free CMS */ if (pTaggantObj->CMS) { CMS_ContentInfo_free(pTaggantObj->CMS); pTaggantObj->CMS = NULL; } /* Free TSA response */ if (pTaggantObj->TSResponse) { TS_RESP_free(pTaggantObj->TSResponse); pTaggantObj->TSResponse = NULL; } /* Free user certificate*/ if (pTaggantObj->user) { X509_free(pTaggantObj->user); pTaggantObj->user = NULL; } /* Free spv certificate*/ if (pTaggantObj->spv) { X509_free(pTaggantObj->spv); pTaggantObj->spv = NULL; } /* Free root certificate*/ if (pTaggantObj->root) { X509_free(pTaggantObj->root); pTaggantObj->root = NULL; } }<file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #ifndef TIMESTAMP_HEADER #define TIMESTAMP_HEADER #include <openssl/ts.h> #include <openssl/err.h> #include <openssl/cms.h> #include <openssl/bio.h> #include <openssl/pem.h> TS_REQ* get_timestamp_request(char* hash, int hash_size, ASN1_INTEGER *nonce_asn1); #ifdef SPV_LIBRARY UNSIGNED32 get_timestamp_response(const char* urlStr, char* hash, UNSIGNED32 hash_size, UNSIGNED32 httpTimeOut, TS_RESP** tsResponse); #endif UNSIGNED64 time_as_unsigned64(int year, int month, int day, int hour, int minute, int second); int check_time_stamp(TS_RESP* tsResponse, X509_STORE* caStore, char* hash, UNSIGNED32 hash_size); #endif /* TIMESTAMP_HEADER */ <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include "global.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "taggant_types.h" #include "types.h" void UNSIGNED64_to_little_endian(UNSIGNED64 value, char* buffer) { int i; for (i = 0; i < 8; i++) { buffer[i] = (char)value; value = value >> 8; } } void UNSIGNED32_to_little_endian(UNSIGNED32 value, char* buffer) { int i; for (i = 0; i < 4; i++) { buffer[i] = (char)value; value = value >> 8; } } void UNSIGNED16_to_little_endian(UNSIGNED16 value, char* buffer) { int i; for (i = 0; i < 2; i++) { buffer[i] = (char)value; value = value >> 8; } } void PACKERINFO_to_little_endian(PPACKERINFO in_packer_info, PPACKERINFO out_packer_info) { UNSIGNED32_to_little_endian(in_packer_info->PackerId, (char*)&out_packer_info->PackerId); UNSIGNED16_to_little_endian(in_packer_info->VersionMajor, (char*)&out_packer_info->VersionMajor); UNSIGNED16_to_little_endian(in_packer_info->VersionMinor, (char*)&out_packer_info->VersionMinor); UNSIGNED16_to_little_endian(in_packer_info->VersionBuild, (char*)&out_packer_info->VersionBuild); UNSIGNED16_to_little_endian(in_packer_info->Reserved, (char*)&out_packer_info->Reserved); } void TAGGANTBLOB_HEADER_to_little_endian(PTAGGANTBLOB_HEADER in_tag_blob_header, PTAGGANTBLOB_HEADER out_tag_blob_header) { UNSIGNED16_to_little_endian(in_tag_blob_header->Length, (char*)&out_tag_blob_header->Length); UNSIGNED16_to_little_endian(in_tag_blob_header->Version, (char*)&out_tag_blob_header->Version); PACKERINFO_to_little_endian(&in_tag_blob_header->PackerInfo, &out_tag_blob_header->PackerInfo); } void HASHBLOB_HEADER_to_little_endian(PHASHBLOB_HEADER in_hash_blob_header, PHASHBLOB_HEADER out_hash_blob_header) { UNSIGNED16_to_little_endian(in_hash_blob_header->Length, (char*)&out_hash_blob_header->Length); UNSIGNED16_to_little_endian(in_hash_blob_header->Type, (char*)&out_hash_blob_header->Type); UNSIGNED16_to_little_endian(in_hash_blob_header->Version, (char*)&out_hash_blob_header->Version); memcpy(&out_hash_blob_header->Hash, &in_hash_blob_header->Hash, sizeof(in_hash_blob_header->Hash)); } void HASHBLOB_DEFAULT_to_little_endian(PHASHBLOB_DEFAULT in_hash_blob_default, PHASHBLOB_DEFAULT out_hash_blob_default) { HASHBLOB_HEADER_to_little_endian(&in_hash_blob_default->Header, &out_hash_blob_default->Header); } void HASHBLOB_EXTENDED_to_little_endian(PHASHBLOB_EXTENDED in_hash_blob_extended, PHASHBLOB_EXTENDED out_hash_blob_extended) { HASHBLOB_HEADER_to_little_endian(&in_hash_blob_extended->Header, &out_hash_blob_extended->Header); UNSIGNED64_to_little_endian(in_hash_blob_extended->PhysicalEnd, (char*)&out_hash_blob_extended->PhysicalEnd); } void HASHBLOB_FULLFILE_to_little_endian(PHASHBLOB_FULLFILE in_hash_blob_full_file, PHASHBLOB_FULLFILE out_hash_blob_full_file){ HASHBLOB_DEFAULT_to_little_endian(&in_hash_blob_full_file->DefaultHash, &out_hash_blob_full_file->DefaultHash); HASHBLOB_EXTENDED_to_little_endian(&in_hash_blob_full_file->ExtendedHash, &out_hash_blob_full_file->ExtendedHash); } void HASHBLOB_HASHMAP_DOUBLE_to_little_endian(PHASHBLOB_HASHMAP_DOUBLE in_hash_blob_hash_map_double, PHASHBLOB_HASHMAP_DOUBLE out_hash_blob_hash_map_double) { UNSIGNED64_to_little_endian(in_hash_blob_hash_map_double->AbsoluteOffset, (char*)&out_hash_blob_hash_map_double->AbsoluteOffset); UNSIGNED64_to_little_endian(in_hash_blob_hash_map_double->Length, (char*)&out_hash_blob_hash_map_double->Length); } void HASHBLOB_HASHMAP_to_little_endian(PHASHBLOB_HASHMAP in_hash_blob_hash_map, PHASHBLOB_HASHMAP out_hash_blob_hash_map) { HASHBLOB_HEADER_to_little_endian(&in_hash_blob_hash_map->Header, &out_hash_blob_hash_map->Header); UNSIGNED16_to_little_endian(in_hash_blob_hash_map->Entries, (char*)&out_hash_blob_hash_map->Entries); UNSIGNED16_to_little_endian(in_hash_blob_hash_map->DoublesOffset, (char*)&out_hash_blob_hash_map->DoublesOffset); } void HASHBLOB_to_little_endian(PHASHBLOB in_hash_blob, PHASHBLOB out_hash_blob) { HASHBLOB_FULLFILE_to_little_endian(&in_hash_blob->FullFile, &out_hash_blob->FullFile); HASHBLOB_HASHMAP_to_little_endian(&in_hash_blob->Hashmap, &out_hash_blob->Hashmap); } void EXTRABLOB_to_little_endian(PEXTRABLOB in_extra_blob, PEXTRABLOB out_extra_blob) { UNSIGNED16_to_little_endian(in_extra_blob->Length, (char*)&out_extra_blob->Length); } void EXTRABLOB2_to_little_endian(PEXTRABLOB2 in_extra_blob, PEXTRABLOB2 out_extra_blob) { UNSIGNED16_to_little_endian(in_extra_blob->Length, (char*)&out_extra_blob->Length); } void TAGGANTBLOB_to_little_endian(PTAGGANTBLOB in_tag_blob, PTAGGANTBLOB out_tag_blob) { int i; PHASHBLOB_HASHMAP_DOUBLE hmd; /* Convert doubles */ hmd = (PHASHBLOB_HASHMAP_DOUBLE)((char*)in_tag_blob + in_tag_blob->Hash.Hashmap.DoublesOffset); for (i = 0; i < in_tag_blob->Hash.Hashmap.Entries; i++) { HASHBLOB_HASHMAP_DOUBLE_to_little_endian(&hmd[i], &hmd[i]); } /* Walk through whole structure and convert numbers */ TAGGANTBLOB_HEADER_to_little_endian(&in_tag_blob->Header, &out_tag_blob->Header); HASHBLOB_to_little_endian(&in_tag_blob->Hash, &out_tag_blob->Hash); EXTRABLOB_to_little_endian(&in_tag_blob->Extrablob, &out_tag_blob->Extrablob); } void TAGGANT_HEADER_to_little_endian(PTAGGANT_HEADER in_tag_header, PTAGGANT_HEADER out_tag_header) { UNSIGNED32_to_little_endian(in_tag_header->MarkerBegin, (char*)&out_tag_header->MarkerBegin); UNSIGNED32_to_little_endian(in_tag_header->TaggantLength, (char*)&out_tag_header->TaggantLength); UNSIGNED32_to_little_endian(in_tag_header->CMSLength, (char*)&out_tag_header->CMSLength); UNSIGNED16_to_little_endian(in_tag_header->Version, (char*)&out_tag_header->Version); } void TAGGANT_HEADER2_to_little_endian(PTAGGANT_HEADER2 in_tag_header, PTAGGANT_HEADER2 out_tag_header) { UNSIGNED16_to_little_endian(in_tag_header->Version, (char*)&out_tag_header->Version); UNSIGNED32_to_little_endian(in_tag_header->CMSLength, (char*)&out_tag_header->CMSLength); UNSIGNED32_to_little_endian(in_tag_header->TaggantLength, (char*)&out_tag_header->TaggantLength); UNSIGNED32_to_little_endian(in_tag_header->MarkerBegin, (char*)&out_tag_header->MarkerBegin); } void TAGGANT_FOOTER_to_little_endian(PTAGGANT_FOOTER in_tag_footer, PTAGGANT_FOOTER out_tag_footer) { EXTRABLOB_to_little_endian(&in_tag_footer->Extrablob, &out_tag_footer->Extrablob); UNSIGNED32_to_little_endian(in_tag_footer->MarkerEnd, (char*)&out_tag_footer->MarkerEnd); } void TAGGANT_FOOTER2_to_little_endian(PTAGGANT_FOOTER2 in_tag_footer, PTAGGANT_FOOTER2 out_tag_footer) { UNSIGNED32_to_little_endian(in_tag_footer->MarkerEnd, (char*)&out_tag_footer->MarkerEnd); } void TAGGANT_to_little_endian(PVOID in_tag, PVOID out_tag) { UNSIGNED32 cmslength = ((PTAGGANT_HEADER)in_tag)->CMSLength; /* Convert taggant header */ TAGGANT_HEADER_to_little_endian((PTAGGANT_HEADER)in_tag, (PTAGGANT_HEADER)out_tag); in_tag = (char*)in_tag + sizeof(TAGGANT_HEADER); out_tag = (char*)out_tag + sizeof(TAGGANT_HEADER); /* Copy CMS */ memcpy(out_tag, in_tag, cmslength); in_tag = (char*)in_tag + cmslength; out_tag = (char*)out_tag + cmslength; /* Convert taggant footer */ TAGGANT_FOOTER_to_little_endian((PTAGGANT_FOOTER)in_tag, (PTAGGANT_FOOTER)out_tag); } void TAGGANT2_to_little_endian(PVOID in_tag, PVOID out_tag) { UNSIGNED32 cmslength = ((PTAGGANT_HEADER)in_tag)->CMSLength; /* Convert taggant footer */ TAGGANT_FOOTER2_to_little_endian((PTAGGANT_FOOTER2)in_tag, (PTAGGANT_FOOTER2)out_tag); in_tag = (char*)in_tag + sizeof(TAGGANT_FOOTER2); out_tag = (char*)out_tag + sizeof(TAGGANT_FOOTER2); /* Copy CMS */ memcpy(out_tag, in_tag, cmslength); in_tag = (char*)in_tag + cmslength; out_tag = (char*)out_tag + cmslength; /* Convert taggant header */ TAGGANT_HEADER2_to_little_endian((PTAGGANT_HEADER2)in_tag, (PTAGGANT_HEADER2)out_tag); } UNSIGNED64 UNSIGNED64_to_big_endian(char* buffer) { int i; UNSIGNED64 res = buffer[7]; for (i = 6; i >= 0; i--) { res = res << 8; res += buffer[i]; } return res; } UNSIGNED32 UNSIGNED32_to_big_endian(char* buffer) { return ((UNSIGNED32)buffer[3] << 0x18) + ((UNSIGNED32)buffer[2] << 0x10) + ((UNSIGNED32)buffer[1] << 8) + buffer[0]; } UNSIGNED16 UNSIGNED16_to_big_endian(char* buffer) { return ((UNSIGNED16)buffer[1] << 8) + buffer[0]; } void PACKERINFO_to_big_endian(PPACKERINFO in_packer_info, PPACKERINFO out_packer_info) { out_packer_info->PackerId = UNSIGNED32_to_big_endian((char*)&in_packer_info->PackerId); out_packer_info->VersionMajor = UNSIGNED16_to_big_endian((char*)&in_packer_info->VersionMajor); out_packer_info->VersionMinor = UNSIGNED16_to_big_endian((char*)&in_packer_info->VersionMinor); out_packer_info->VersionBuild = UNSIGNED16_to_big_endian((char*)&in_packer_info->VersionBuild); out_packer_info->Reserved = UNSIGNED16_to_big_endian((char*)&in_packer_info->Reserved); } void TAGGANTBLOB_HEADER_to_big_endian(PTAGGANTBLOB_HEADER in_tag_blob_header, PTAGGANTBLOB_HEADER out_tag_blob_header) { out_tag_blob_header->Length = UNSIGNED16_to_big_endian((char*)&in_tag_blob_header->Length); out_tag_blob_header->Version = UNSIGNED16_to_big_endian((char*)&in_tag_blob_header->Version); PACKERINFO_to_big_endian(&in_tag_blob_header->PackerInfo, &out_tag_blob_header->PackerInfo); } void HASHBLOB_HEADER_to_big_endian(PHASHBLOB_HEADER in_hash_blob_header, PHASHBLOB_HEADER out_hash_blob_header) { out_hash_blob_header->Length = UNSIGNED16_to_big_endian((char*)&in_hash_blob_header->Length); out_hash_blob_header->Type = UNSIGNED16_to_big_endian((char*)&in_hash_blob_header->Type); out_hash_blob_header->Version = UNSIGNED16_to_big_endian((char*)&in_hash_blob_header->Version); memcpy(&out_hash_blob_header->Hash, &in_hash_blob_header->Hash, sizeof(in_hash_blob_header->Hash)); } void HASHBLOB_DEFAULT_to_big_endian(PHASHBLOB_DEFAULT in_hash_blob_default, PHASHBLOB_DEFAULT out_hash_blob_default) { HASHBLOB_HEADER_to_big_endian(&in_hash_blob_default->Header, &out_hash_blob_default->Header); } void HASHBLOB_EXTENDED_to_big_endian(PHASHBLOB_EXTENDED in_hash_blob_extended, PHASHBLOB_EXTENDED out_hash_blob_extended) { HASHBLOB_HEADER_to_big_endian(&in_hash_blob_extended->Header, &out_hash_blob_extended->Header); out_hash_blob_extended->PhysicalEnd = UNSIGNED64_to_big_endian((char*)&in_hash_blob_extended->PhysicalEnd); } void HASHBLOB_FULLFILE_to_big_endian(PHASHBLOB_FULLFILE in_hash_blob_full_file, PHASHBLOB_FULLFILE out_hash_blob_full_file) { HASHBLOB_DEFAULT_to_big_endian(&in_hash_blob_full_file->DefaultHash, &out_hash_blob_full_file->DefaultHash); HASHBLOB_EXTENDED_to_big_endian(&in_hash_blob_full_file->ExtendedHash, &out_hash_blob_full_file->ExtendedHash); } void HASHBLOB_HASHMAP_DOUBLE_to_big_endian(PHASHBLOB_HASHMAP_DOUBLE in_hash_blob_hash_map_double, PHASHBLOB_HASHMAP_DOUBLE out_hash_blob_hash_map_double) { out_hash_blob_hash_map_double->AbsoluteOffset = UNSIGNED64_to_big_endian((char*)&in_hash_blob_hash_map_double->AbsoluteOffset); out_hash_blob_hash_map_double->Length = UNSIGNED64_to_big_endian((char*)&in_hash_blob_hash_map_double->Length); } void HASHBLOB_HASHMAP_to_big_endian(PHASHBLOB_HASHMAP in_hash_blob_hash_map, PHASHBLOB_HASHMAP out_hash_blob_hash_map) { HASHBLOB_HEADER_to_big_endian(&in_hash_blob_hash_map->Header, &out_hash_blob_hash_map->Header); out_hash_blob_hash_map->Entries = UNSIGNED16_to_big_endian((char*)&in_hash_blob_hash_map->Entries); out_hash_blob_hash_map->DoublesOffset = UNSIGNED16_to_big_endian((char*)&in_hash_blob_hash_map->DoublesOffset); } void HASHBLOB_to_big_endian(PHASHBLOB in_hash_blob, PHASHBLOB out_hash_blob) { HASHBLOB_FULLFILE_to_big_endian(&in_hash_blob->FullFile, &out_hash_blob->FullFile); HASHBLOB_HASHMAP_to_big_endian(&in_hash_blob->Hashmap, &out_hash_blob->Hashmap); } void EXTRABLOB_to_big_endian(PEXTRABLOB in_extra_blob, PEXTRABLOB out_extra_blob) { out_extra_blob->Length = UNSIGNED16_to_big_endian((char*)&in_extra_blob->Length); } void EXTRABLOB2_to_big_endian(PEXTRABLOB2 in_extra_blob, PEXTRABLOB2 out_extra_blob) { out_extra_blob->Length = UNSIGNED16_to_big_endian((char*)&in_extra_blob->Length); } void TAGGANTBLOB_to_big_endian(PTAGGANTBLOB in_tag_blob, PTAGGANTBLOB out_tag_blob) { int i; PHASHBLOB_HASHMAP_DOUBLE hmd; /* Walk through whole structure and convert numbers */ TAGGANTBLOB_HEADER_to_big_endian(&in_tag_blob->Header, &out_tag_blob->Header); HASHBLOB_to_big_endian(&in_tag_blob->Hash, &out_tag_blob->Hash); EXTRABLOB_to_big_endian(&in_tag_blob->Extrablob, &out_tag_blob->Extrablob); /* Convert doubles */ hmd = (PHASHBLOB_HASHMAP_DOUBLE)((char*)out_tag_blob + out_tag_blob->Hash.Hashmap.DoublesOffset); for (i = 0; i < out_tag_blob->Hash.Hashmap.Entries; i++) { HASHBLOB_HASHMAP_DOUBLE_to_big_endian(&hmd[i], &hmd[i]); } } void TAGGANT_HEADER_to_big_endian(PTAGGANT_HEADER in_tag_header, PTAGGANT_HEADER out_tag_header) { out_tag_header->MarkerBegin = UNSIGNED32_to_big_endian((char*)&in_tag_header->MarkerBegin); out_tag_header->TaggantLength = UNSIGNED32_to_big_endian((char*)&in_tag_header->TaggantLength); out_tag_header->CMSLength = UNSIGNED32_to_big_endian((char*)&in_tag_header->CMSLength); out_tag_header->Version = UNSIGNED16_to_big_endian((char*)&in_tag_header->Version); } void TAGGANT_HEADER2_to_big_endian(PTAGGANT_HEADER2 in_tag_header, PTAGGANT_HEADER2 out_tag_header) { out_tag_header->Version = UNSIGNED16_to_big_endian((char*)&in_tag_header->Version); out_tag_header->CMSLength = UNSIGNED32_to_big_endian((char*)&in_tag_header->CMSLength); out_tag_header->TaggantLength = UNSIGNED32_to_big_endian((char*)&in_tag_header->TaggantLength); out_tag_header->MarkerBegin = UNSIGNED32_to_big_endian((char*)&in_tag_header->MarkerBegin); } void TAGGANT_FOOTER_to_big_endian(PTAGGANT_FOOTER in_tag_footer, PTAGGANT_FOOTER out_tag_footer) { EXTRABLOB_to_big_endian(&in_tag_footer->Extrablob, &out_tag_footer->Extrablob); out_tag_footer->MarkerEnd = UNSIGNED32_to_big_endian((char*)&in_tag_footer->MarkerEnd); } void TAGGANT_FOOTER2_to_big_endian(PTAGGANT_FOOTER2 in_tag_footer, PTAGGANT_FOOTER2 out_tag_footer) { out_tag_footer->MarkerEnd = UNSIGNED32_to_big_endian((char*)&in_tag_footer->MarkerEnd); } void TAGGANT_to_big_endian(PVOID in_tag, PVOID out_tag) { UNSIGNED32 cmslength = 0; /* Convert taggant header */ TAGGANT_HEADER_to_big_endian((PTAGGANT_HEADER)in_tag, (PTAGGANT_HEADER)out_tag); cmslength = ((PTAGGANT_HEADER)out_tag)->CMSLength; in_tag = (char*)in_tag + sizeof(TAGGANT_HEADER); out_tag = (char*)out_tag + sizeof(TAGGANT_HEADER); /* Copy CMS */ memcpy(out_tag, in_tag, cmslength); in_tag = (char*)in_tag + cmslength; out_tag = (char*)out_tag + cmslength; /* Convert taggant footer */ TAGGANT_FOOTER_to_big_endian((PTAGGANT_FOOTER)in_tag, (PTAGGANT_FOOTER)out_tag); }<file_sep>/* * fileio.h * * Created on: Nov 7, 2011 * Author: <NAME> */ #ifndef FILEIO_H_ #define FILEIO_H_ #include <iostream> #include <fstream> #include <istream> #include "taggant_types.h" using namespace std; __DECLARATION size_t fileio_fread(ifstream* fin, void* buffer, size_t size); __DECLARATION int fileio_fseek(ifstream* fin, UNSIGNED64 offset, int type); __DECLARATION UNSIGNED64 fileio_ftell(ifstream* fin); UNSIGNED64 fileio_fsize (ifstream* fin); #endif /* FILEIO_H_ */ <file_sep>/* * miscellaneous.h * * Created on: Dec 19, 2011 * Author: Enigma */ #ifndef MISCELLANEOUS_H_ #define MISCELLANEOUS_H_ #include "taggant_types.h" long round_up(long alignment, long size); long round_down(long alignment, long size); long get_min(long v1, long v2); long get_file_size (PTAGGANTCONTEXT pCtx, PFILEOBJECT fp); #endif /* MISCELLANEOUS_H_ */ <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include <iostream> #include <fstream> #include <istream> #include <string> #include "fileio.h" #include "winpe.h" #include "winpe_types.h" #include "miscellaneous.h" using namespace std; int winpe_raw_section_offset(PE_ALL_HEADERS* peh, TAG_IMAGE_SECTION_HEADER* sec) { long section_alignment; // section_alignment = (winpe_is_pe64(peh)) ? peh->oh.pe64.SectionAlignment : peh->oh.pe32.SectionAlignment; if (section_alignment >= 0x1000) { return round_down(0x200, sec->PointerToRawData); } return sec->PointerToRawData; } int winpe_section_size(PE_ALL_HEADERS* peh, TAG_IMAGE_SECTION_HEADER* sec) { long section_alignment; long file_alignment; // section_alignment = (winpe_is_pe64(peh)) ? peh->oh.pe64.SectionAlignment : peh->oh.pe32.SectionAlignment; file_alignment = (winpe_is_pe64(peh)) ? peh->oh.pe64.FileAlignment : peh->oh.pe32.FileAlignment; return (sec->Misc.VirtualSize ? get_min(round_up(section_alignment, sec->Misc.VirtualSize), round_up(file_alignment, sec->SizeOfRawData)) : round_up(file_alignment, sec->SizeOfRawData)); } int winpe_is_pe64(PE_ALL_HEADERS* peh) { if (peh->fh.Machine == IMAGE_FILE_MACHINE_I386) { return 0; } return 1; } int winpe_object_size(ifstream* fp, PE_ALL_HEADERS* peh) { UNSIGNED64 filelength; int res = -1; // check is number of sections greater zero if (peh->fh.NumberOfSections > 0) { long filepos = peh->dh.e_lfanew + sizeof(DWORD) + sizeof(TAG_IMAGE_FILE_HEADER) + peh->fh.SizeOfOptionalHeader; // shift file pointer to the sections array if (fileio_fseek(fp, filepos, SEEK_SET) == 0) { int i; TAG_IMAGE_SECTION_HEADER fs; for (i = 0; i < peh->fh.NumberOfSections; i++) { // read section from the file if (fileio_fread(fp, &fs, sizeof(TAG_IMAGE_SECTION_HEADER)) == sizeof(TAG_IMAGE_SECTION_HEADER)) { if (winpe_raw_section_offset(peh, &fs) != 0) { res = winpe_raw_section_offset(peh, &fs) + winpe_section_size(peh, &fs); } filepos += sizeof(TAG_IMAGE_SECTION_HEADER); if (fileio_fseek(fp, filepos, SEEK_SET) != 0) { res = -1; break; } } else { res = -1; break; } } } } filelength = fileio_fsize(fp); return get_min(res, (int)filelength); } int winpe_va_to_rwa(ifstream* fp, PE_ALL_HEADERS* peh, unsigned long va) { if (peh->fh.NumberOfSections == 0) { return va; } if (winpe_is_pe64(peh)) { if (va < peh->oh.pe32.SizeOfHeaders) { return va; } } else { if (va < peh->oh.pe64.SizeOfHeaders) { return va; } } // check is number of sections greater zero if (peh->fh.NumberOfSections > 0) { long filepos = peh->dh.e_lfanew + sizeof(DWORD) + sizeof(TAG_IMAGE_FILE_HEADER) + peh->fh.SizeOfOptionalHeader; // shift file pointer to the sections array if (fileio_fseek(fp, filepos, SEEK_SET) == 0) { // reading all sections and find rwa address int i; TAG_IMAGE_SECTION_HEADER fs; for (i = 0; i < peh->fh.NumberOfSections; i++) { // read section from the file if (fileio_fread(fp, &fs, sizeof(TAG_IMAGE_SECTION_HEADER)) == sizeof(TAG_IMAGE_SECTION_HEADER)) { // if (va < fs.VirtualAddress) { break; } else if (winpe_raw_section_offset(peh, &fs) != 0) { if (va >= fs.VirtualAddress && va < (fs.VirtualAddress + winpe_section_size(peh, &fs))) { return va - fs.VirtualAddress + winpe_raw_section_offset(peh, &fs); } } filepos += sizeof(TAG_IMAGE_SECTION_HEADER); if (fileio_fseek(fp, filepos, SEEK_SET) != 0) { break; } } else { break; } } } } return -1; } long winpe_entry_point_physical_offset(ifstream* fp, PE_ALL_HEADERS* peh) { if (winpe_is_pe64(peh)) { if (peh->oh.pe64.AddressOfEntryPoint != 0) { return winpe_va_to_rwa(fp, peh, peh->oh.pe64.AddressOfEntryPoint); } } else { if (peh->oh.pe32.AddressOfEntryPoint != 0) { return winpe_va_to_rwa(fp, peh, peh->oh.pe32.AddressOfEntryPoint); } } return -1; } int winpe_is_correct_pe_file(ifstream* fp, PE_ALL_HEADERS* peh) { // remember the size of the file UNSIGNED64 filesize = fileio_fsize(fp); // make sure filesize is greater than size of DOS header if (filesize >= sizeof(TAG_IMAGE_DOS_HEADER)) { // seek file to the file beginning if (fileio_fseek(fp, 0L, SEEK_SET) == 0) { // make sure dos header is read fully if (fileio_fread(fp, &peh->dh, sizeof(TAG_IMAGE_DOS_HEADER)) == sizeof(TAG_IMAGE_DOS_HEADER)) { // check dos header e_magic if (peh->dh.e_magic == IMAGE_DOS_SIGNATURE) { if (filesize >= peh->dh.e_lfanew) { // seek file to the dh.e_magic from beginning if (fileio_fseek(fp, peh->dh.e_lfanew, SEEK_SET) == 0) { // read file signature if (fileio_fread(fp, &peh->signature, sizeof(DWORD)) == sizeof(DWORD)) { if (peh->signature == IMAGE_NT_SIGNATURE) { // read file header if (fileio_fread(fp, &peh->fh, sizeof(TAG_IMAGE_FILE_HEADER)) == sizeof(TAG_IMAGE_FILE_HEADER)) { // As MSDN says, only these types of files can be run in Windows switch (peh->fh.Machine) { case IMAGE_FILE_MACHINE_I386: { // PE32 file, read optional header memset(&peh->oh.pe32, 0, sizeof(TAG_IMAGE_OPTIONAL_HEADER32)); if (fileio_fread(fp, &peh->oh.pe32, sizeof(TAG_IMAGE_OPTIONAL_HEADER32)) == sizeof(TAG_IMAGE_OPTIONAL_HEADER32)) { if (peh->oh.pe32.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) { return 1; } } break; } case IMAGE_FILE_MACHINE_AMD64: { memset(&peh->oh.pe64, 0, sizeof(TAG_IMAGE_OPTIONAL_HEADER64)); if (fileio_fread(fp, &peh->oh.pe64, sizeof(TAG_IMAGE_OPTIONAL_HEADER64)) == sizeof(TAG_IMAGE_OPTIONAL_HEADER64)) { if (peh->oh.pe64.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) { return 1; } } break; } default: { break; } } } } } } } } } } } return 0; } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include "global.h" #include "url.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "callbacks.h" int is_char(int c) { return (!isalpha(c) && '+' != c && '-' != c && '.' != c) ? 0 : 1; } Url* parse_url(const char* urlStr) { Url* url; const char* tempStr; const char* currentStr; char* port; int i, length; url = (Url*)memory_alloc(sizeof(Url)); if (url == NULL) { return NULL; } url->Scheme = NULL; url->Host = NULL; url->Port = 80; currentStr = urlStr; /* Scheme */ tempStr = strchr(currentStr, ':'); if (tempStr == NULL) { goto error; } length = (int)(tempStr - currentStr); for ( i = 0; i < length; i++ ) { if (!is_char(currentStr[i]) ) { goto error; } } url->Scheme = (char*)memory_alloc(length + 1); if (url->Scheme == NULL) { goto error; } strncpy(url->Scheme, currentStr, length); url->Scheme[length] = '\0'; for (i = 0; i < length; i++ ) { url->Scheme[i] = (char)tolower(url->Scheme[i]); } /* Skip ':' */ tempStr++; currentStr = tempStr; /* Check "//" */ if (*currentStr != '/' || *(currentStr + 1) != '/') { goto error; } currentStr += 2; /* Host */ tempStr = currentStr; while (*tempStr != '\0') { if ((*tempStr == ':') || (*tempStr == '/')) { break; } tempStr++; } length = (int)(tempStr - currentStr); if (length <= 0) { goto error; } url->Host = (char*)memory_alloc(length + 1); if (url->Host == NULL) { goto error; } strncpy(url->Host, currentStr, length); url->Host[length] = '\0'; currentStr = tempStr; /* Port */ if (*currentStr == ':' ) { currentStr++; tempStr = currentStr; while ((*tempStr != '\0') && (*tempStr != '/')) { tempStr++; } length = (int)(tempStr - currentStr); if (length <= 0) { goto error; } port = (char*)memory_alloc(length + 1); if (port == NULL) { goto error; } strncpy(port, currentStr, length); port[length] = '\0'; url->Port = atoi(port); if (url->Port <= 0) { url->Port = 80; } memory_free(port); } return url; error: free_url(url); return NULL; } void free_url(Url* url) { /* Free url memory */ if (url == NULL) { return; } if (url->Scheme != NULL) { memory_free(url->Scheme); } if (url->Host != NULL) { memory_free(url->Host); } memory_free(url); } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #include "global.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "js.h" #include "txt.h" #include "taggantlib.h" #include "timestamp.h" #include "callbacks.h" #include "winpe.h" #include "winpe2.h" #include "types.h" #include "taggant.h" #include "taggant2.h" #include "miscellaneous.h" #include "endianness.h" #include <openssl/ts.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/cms.h> #include <openssl/err.h> #include <openssl/x509_vfy.h> /* Current version of the library */ #define TAGGANT_LIBRARY_CURRENTVERSION TAGGANT_LIBRARY_VERSION2 /* global variable determines if the library is initialized */ int lib_initialized = 0; UNSIGNED64 get_lib_version(PTAGGANTOBJ tagobj) { #ifdef SPV_LIBRARY /* return the version of the library that it is set to working for */ return tagobj->uVersion; #endif #ifdef SSV_LIBRARY /* return the version of the library to process the current taggant while enumeration */ return tagobj->tagParent->uVersion; #endif } EXPORT UNSIGNED32 STDCALL TaggantInitializeLibrary(__in_opt TAGGANTFUNCTIONS *pFuncs, __out UNSIGNED64 *puVersion) { /* Get the pointer to callbacks structure */ TAGGANTFUNCTIONS* callbacks = get_callbacks(); /* Initialize structure */ memset(callbacks, 0, sizeof(TAGGANTFUNCTIONS)); if (pFuncs != NULL) { memcpy((char*)callbacks, (char*)pFuncs, get_min((unsigned long)pFuncs->size, sizeof(TAGGANTFUNCTIONS))); } callbacks->size = sizeof(TAGGANTFUNCTIONS); /* If any of memory callbacks are NULL then redirect them to internal callbacks */ if (callbacks->MemoryAllocCallBack == NULL || callbacks->MemoryFreeCallBack == NULL || callbacks->MemoryReallocCallBack == NULL) { callbacks->MemoryAllocCallBack = (void* (__DECLARATION*)(size_t))&internal_alloc; callbacks->MemoryFreeCallBack = (void (__DECLARATION*)(void*))&internal_free; callbacks->MemoryReallocCallBack = (void* (__DECLARATION*)(void*, size_t))&internal_realloc; } CRYPTO_set_mem_functions(memory_alloc, memory_realloc, memory_free); ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); /* Return the maximim version number supported by the library */ *puVersion = TAGGANT_LIBRARY_CURRENTVERSION; lib_initialized = 1; return TNOERR; } EXPORT void STDCALL TaggantFinalizeLibrary(void) { lib_initialized = 0; OBJ_cleanup(); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); ERR_remove_thread_state(NULL); ERR_free_strings(); } #ifdef SPV_LIBRARY EXPORT UNSIGNED32 STDCALL TaggantAddHashRegion(__inout PTAGGANTOBJ pTaggantObj, UNSIGNED64 uOffset, UNSIGNED64 uLength) { UNSIGNED32 res = TNOTIMPLEMENTED; if (!lib_initialized) { return TLIBNOTINIT; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = taggant_add_hash_region(pTaggantObj->tagObj1, uOffset, uLength); break; case TAGGANT_LIBRARY_VERSION2: res = taggant2_add_hash_region(pTaggantObj->tagObj2, uOffset, uLength); break; } return res; } #endif #ifdef SSV_LIBRARY EXPORT void STDCALL TaggantFreeTaggant(__deref PTAGGANT pTaggant) { if (pTaggant) { /* free buffer of taggant v2 */ taggant2_free_taggant(pTaggant->pTag2); /* free buffer of taggant v1 */ taggant_free_taggant(pTaggant->pTag1); /* free buffer of taggant itself */ memory_free(pTaggant); } } EXPORT UNSIGNED32 STDCALL TaggantGetTaggant(__in PTAGGANTCONTEXT pCtx, __in PFILEOBJECT hFile, TAGGANTCONTAINER eContainer, __inout PTAGGANT *pTaggant) { UNSIGNED32 res = TNOERR; PTAGGANT taggant; /* the current file position to check for a next taggant */ UNSIGNED64 fileend; /* end of full file hash, the size of the file without taggants */ UNSIGNED64 ffhend; UNSIGNED64 dsoffset; PE_ALL_HEADERS peh; UNSIGNED32 ds_offset, ds_size; PTAGGANT2 taggant2; int err, stoploop = 0; if (!lib_initialized) { return TLIBNOTINIT; } taggant = *pTaggant; /* create the taggant if it is empty */ if (!taggant) { taggant = (PTAGGANT)memory_alloc(sizeof(TAGGANT)); if (taggant) { memset(taggant, 0, sizeof(TAGGANT)); taggant->uVersion = TAGGANT_LIBRARY_CURRENTVERSION; taggant->tagganttype = eContainer; } else { res = TMEMORY; } } else { /* ignore eContainer if we are looking for next taggant */ eContainer = taggant->tagganttype; } if (res == TNOERR) { if (taggant->uVersion == TAGGANT_LIBRARY_VERSION2) { switch (eContainer) { case TAGGANT_JSFILE: { /* It is a JavaScript file */ if (taggant->pTag2) { fileend = taggant->pTag2->fileend; ffhend = taggant->pTag2->ffhend; /* Free the taggant object */ taggant2_free_taggant(taggant->pTag2); taggant->pTag2 = NULL; } else { fileend = get_file_size(pCtx, hFile); /* exclude digital signature */ if (js_get_ds_offset(pCtx, hFile, &dsoffset)) { fileend = dsoffset; } /* go through all taggants to get the end of full file hash */ ffhend = fileend; while (taggant2_read_textual(pCtx, hFile, ffhend, &taggant2, TAGGANT_JSFILE, JS_COMMENT_BEGIN, (int) strlen(JS_COMMENT_BEGIN), JS_COMMENT_END, (int) strlen(JS_COMMENT_END)) == TNOERR) { ffhend -= strlen(JS_COMMENT_BEGIN) + taggant2->Header.TaggantLength + strlen(JS_COMMENT_END); /* Free the taggant object */ taggant2_free_taggant(taggant2); } } res = taggant2_read_textual(pCtx, hFile, fileend, &taggant->pTag2, TAGGANT_JSFILE, JS_COMMENT_BEGIN, (int) strlen(JS_COMMENT_BEGIN), JS_COMMENT_END, (int) strlen(JS_COMMENT_END)); if (res == TNOERR) { taggant->pTag2->fileend = fileend - (strlen(JS_COMMENT_BEGIN) + taggant->pTag2->Header.TaggantLength + strlen(JS_COMMENT_END)); taggant->pTag2->ffhend = ffhend; } break; } case TAGGANT_PEFILE: { /* Assume it is PE file and make sure it is correct * If taggant2 points to existing object then PE file had been already verified * do not verify it again to save the time */ err = 0; if (taggant->pTag2) { fileend = taggant->pTag2->fileend; ffhend = taggant->pTag2->ffhend; /* Free the taggant object */ taggant2_free_taggant(taggant->pTag2); taggant->pTag2 = NULL; } else { fileend = get_file_size(pCtx, hFile); err = winpe_is_correct_pe_file(pCtx, hFile, &peh) ? 0 : 1; if (!err) { /* exclude digital signature */ if (winpe_is_pe64(&peh)) { ds_offset = (UNSIGNED32)peh.oh.pe64.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; ds_size = (UNSIGNED32)peh.oh.pe64.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; } else { ds_offset = (UNSIGNED32)peh.oh.pe32.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; ds_size = (UNSIGNED32)peh.oh.pe32.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; } if (ds_offset != 0 && ds_size != 0) { if ((ds_offset + ds_size) == fileend) { unsigned char tmpbuff[7]; fileend -= ds_size; /* account for the zero-padding that the digital certificate might have added prior to being attached */ if (file_seek(pCtx, hFile, fileend - sizeof(tmpbuff), SEEK_SET) && file_read_buffer(pCtx, hFile, tmpbuff, sizeof(tmpbuff)) ) { int i; for (i = sizeof(tmpbuff) - 1; i >= 0 && !tmpbuff[i]; i--) { --fileend; } } } } ffhend = fileend; while (taggant2_read_binary(pCtx, hFile, ffhend, &taggant2, TAGGANT_PEFILE) == TNOERR) { ffhend -= taggant2->Header.TaggantLength; /* Free the taggant object */ taggant2_free_taggant(taggant2); } } } if (!err) { res = taggant2_read_binary(pCtx, hFile, fileend, &taggant->pTag2, TAGGANT_PEFILE); if (res == TNOERR) { taggant->pTag2->fileend = fileend - taggant->pTag2->Header.TaggantLength; taggant->pTag2->ffhend = ffhend; } else if (res == TNOTAGGANTS) { /* try to read taggant v1 */ taggant->uVersion = TAGGANT_LIBRARY_VERSION1; } } else { res = TINVALIDPEFILE; } break; } case TAGGANT_TXTFILE: { /* It is a text file */ if (taggant->pTag2) { fileend = taggant->pTag2->fileend; ffhend = taggant->pTag2->ffhend; /* Free the taggant object */ taggant2_free_taggant(taggant->pTag2); taggant->pTag2 = NULL; } else { fileend = get_file_size(pCtx, hFile); /* go through all taggants to get the end of full file hash */ ffhend = fileend; while (taggant2_read_textual(pCtx, hFile, ffhend, &taggant2, TAGGANT_TXTFILE, NULL, 0, NULL, 0) == TNOERR) { ffhend -= taggant2->Header.TaggantLength; /* Free the taggant object */ taggant2_free_taggant(taggant2); } } res = taggant2_read_textual(pCtx, hFile, fileend, &taggant->pTag2, TAGGANT_TXTFILE, NULL, 0, NULL, 0); if (res == TNOERR) { taggant->pTag2->fileend = fileend - taggant->pTag2->Header.TaggantLength; taggant->pTag2->ffhend = ffhend; } break; } case TAGGANT_BINFILE: { if (taggant->pTag2) { fileend = taggant->pTag2->fileend; ffhend = taggant->pTag2->ffhend; /* Free the taggant object */ taggant2_free_taggant(taggant->pTag2); taggant->pTag2 = NULL; } else { fileend = get_file_size(pCtx, hFile); ffhend = fileend; while (taggant2_read_binary(pCtx, hFile, ffhend, &taggant2, TAGGANT_BINFILE) == TNOERR) { ffhend -= taggant2->Header.TaggantLength; /* Free the taggant object */ taggant2_free_taggant(taggant2); } } res = taggant2_read_binary(pCtx, hFile, fileend, &taggant->pTag2, TAGGANT_BINFILE); if (res == TNOERR) { taggant->pTag2->fileend = fileend - taggant->pTag2->Header.TaggantLength; taggant->pTag2->ffhend = ffhend; } break; } default: { res = TTYPE; break; } } } else if(taggant->uVersion == TAGGANT_LIBRARY_VERSION1 && !stoploop) { /* if we already processed taggant v1 then stop the enumeration */ res = TNOTAGGANTS; stoploop = 1; } if (taggant->uVersion == TAGGANT_LIBRARY_VERSION1 && !stoploop) { if (eContainer == TAGGANT_PEFILE) { res = taggant_read_binary(pCtx, hFile, &taggant->pTag1); } else { res = TTYPE; } } } *pTaggant = taggant; return res; } #endif #ifdef SSV_LIBRARY EXPORT UNSIGNED32 STDCALL TaggantValidateSignature(__in PTAGGANTOBJ pTaggantObj, __in PTAGGANT pTaggant, __in PVOID pRootCert) { UNSIGNED32 res = TNOTIMPLEMENTED; if (!lib_initialized) { return TLIBNOTINIT; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = taggant_validate_signature(pTaggantObj->tagObj1, pTaggant->pTag1, pRootCert); break; case TAGGANT_LIBRARY_VERSION2: res = taggant2_validate_signature(pTaggantObj->tagObj2, pTaggant->pTag2, pRootCert); break; } return res; } #endif #ifdef SPV_LIBRARY EXPORT UNSIGNED32 STDCALL TaggantComputeHashes(__in PTAGGANTCONTEXT pCtx, __inout PTAGGANTOBJ pTaggantObj, __in PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd, UNSIGNED32 uTaggantSize) { PE_ALL_HEADERS peh; UNSIGNED32 res = TINVALIDPEFILE; UNSIGNED64 objectend, fileend = uFileEnd; PTAGGANT1 taggant1 = NULL; PTAGGANT2 taggant2 = NULL; int found = 0; EVP_MD_CTX evp; UNSIGNED8 prevtag; if (!lib_initialized) { return TLIBNOTINIT; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: /* Check if the file is correct win_pe file */ if (winpe_is_correct_pe_file(pCtx, hFile, &peh)) { /* Compute default hash */ res = taggant_compute_default_hash(pCtx, &pTaggantObj->tagObj1->pTagBlob->Hash.FullFile, hFile, &peh, uObjectEnd, fileend, uTaggantSize); if (res == TNOERR && pTaggantObj->tagObj1->pTagBlob->Hash.Hashmap.Entries > 0) { /* Compute hashmap */ res = taggant_compute_hash_map(pCtx, hFile, pTaggantObj->tagObj1->pTagBlob); } } else { res = TINVALIDPEFILE; } break; case TAGGANT_LIBRARY_VERSION2: switch (pTaggantObj->tagObj2->tagganttype) { case TAGGANT_JSFILE: { /* It is a JavaScript file */ if (!fileend) { fileend = get_file_size(pCtx, hFile); } /* Get the file end exclude existing taggants * Walk through all taggants in file and take offset of the file without taggants * Take offset and size of the latest taggant to include it into hash map */ res = TNOERR; found = 0; while (res == TNOERR && taggant2_read_textual(pCtx, hFile, fileend, &taggant2, TAGGANT_JSFILE, JS_COMMENT_BEGIN, (int) strlen(JS_COMMENT_BEGIN), JS_COMMENT_END, (int) strlen(JS_COMMENT_END)) == TNOERR) { fileend -= strlen(JS_COMMENT_BEGIN) + taggant2->Header.TaggantLength + strlen(JS_COMMENT_END); /* Get the offset and size of the first found taggant to add it into hashmap */ if (!found) { /* remember that there is a previous taggant in the file */ prevtag = 1; if ((res = taggant2_put_extrainfo(&pTaggantObj->tagObj2->tagBlob.Extrablob, ETAGPREV, sizeof(prevtag), (char*)&prevtag)) == TNOERR) { /* add a hash region of the previous taggant */ if ((res = taggant2_add_hash_region(pTaggantObj->tagObj2, fileend, strlen(JS_COMMENT_BEGIN) + taggant2->Header.TaggantLength + strlen(JS_COMMENT_END))) == TNOERR) { found++; } } } /* Free the taggant object */ taggant2_free_taggant(taggant2); } if (res == TNOERR) { res = taggant2_compute_hash_raw(pCtx, &pTaggantObj->tagObj2->tagBlob.Hash, hFile, fileend, pTaggantObj->tagObj2->tagBlob.pHashMapDoubles); } break; } case TAGGANT_TXTFILE: { /* It is a text file */ if (!fileend) { fileend = get_file_size(pCtx, hFile); } /* Get the file end exclude existing taggants * Walk through all taggants in file and take offset of the file without taggants * Take offset and size of the latest taggant to include it into hash map */ res = TNOERR; found = 0; while (res == TNOERR && taggant2_read_textual(pCtx, hFile, fileend, &taggant2, TAGGANT_TXTFILE, NULL, 0, NULL, 0) == TNOERR) { fileend -= taggant2->Header.TaggantLength; /* Get the offset and size of the first found taggant to add it into hashmap */ if (!found) { /* remember that there is a previous taggant in the file */ prevtag = 1; if ((res = taggant2_put_extrainfo(&pTaggantObj->tagObj2->tagBlob.Extrablob, ETAGPREV, sizeof(prevtag), (char*)&prevtag)) == TNOERR) { /* add a hash region of the previous taggant */ if ((res = taggant2_add_hash_region(pTaggantObj->tagObj2, fileend, taggant2->Header.TaggantLength)) == TNOERR) { found++; } } } /* Free the taggant object */ taggant2_free_taggant(taggant2); } if (res == TNOERR) { res = taggant2_compute_hash_raw(pCtx, &pTaggantObj->tagObj2->tagBlob.Hash, hFile, fileend, pTaggantObj->tagObj2->tagBlob.pHashMapDoubles); } break; } case TAGGANT_PEFILE: { /* Assume it is PE file and make sure it is correct */ if (winpe_is_correct_pe_file(pCtx, hFile, &peh)) { /* Get the object end of PE file */ objectend = winpe2_object_end(pCtx, hFile, &peh); /* Get the file end excluding existing taggants * Walk through all taggants in file and take offset of the file without taggants * Take offset and size of the latest taggant to include it into hash map */ if (!fileend) { fileend = get_file_size(pCtx, hFile); } res = TNOERR; found = 0; while (res == TNOERR && taggant2_read_binary(pCtx, hFile, fileend, &taggant2, TAGGANT_PEFILE) == TNOERR) { fileend -= taggant2->Header.TaggantLength; /* Get the offset and size of the first found taggant to add it into hashmap */ if (!found) { /* remember that there is a previous taggant in the file */ prevtag = 1; if ((res = taggant2_put_extrainfo(&pTaggantObj->tagObj2->tagBlob.Extrablob, ETAGPREV, sizeof(prevtag), (char*)&prevtag)) == TNOERR) { /* add a hash region of the previous taggant */ if ((res = taggant2_add_hash_region(pTaggantObj->tagObj2, fileend, taggant2->Header.TaggantLength)) == TNOERR) { found++; } } } /* Free the taggant object */ taggant2_free_taggant(taggant2); } if (res == TNOERR) { /* if taggant v2 is not found, try to find taggant v1 to add it to hashmap */ if (!found) { if (taggant_read_binary(pCtx, hFile, &taggant1) == TNOERR) { /* remember that there is a previous taggant in the file */ prevtag = 1; if ((res = taggant2_put_extrainfo(&pTaggantObj->tagObj2->tagBlob.Extrablob, ETAGPREV, sizeof(prevtag), (char*)&prevtag)) == TNOERR) { /* add a hash region of the previous taggant */ if ((res = taggant2_add_hash_region(pTaggantObj->tagObj2, taggant1->offset, (UNSIGNED64)taggant1->Header.TaggantLength)) == TNOERR) { found++; } } /* Free the taggant object */ taggant_free_taggant(taggant1); } } if (res == TNOERR) { /* compute file hashes */ if (fileend >= uObjectEnd) { /* Compute hash */ EVP_MD_CTX_init(&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); /* Compute default hash */ if ((res = taggant2_compute_default_hash_pe(&evp, pCtx, &pTaggantObj->tagObj2->tagBlob.Hash.FullFile.DefaultHash, hFile, &peh, objectend)) == TNOERR) { /* Compute extended hash */ if ((res = taggant2_compute_extended_hash_pe(&evp, pCtx, &pTaggantObj->tagObj2->tagBlob.Hash.FullFile.ExtendedHash, hFile, objectend, fileend)) == TNOERR) { if (pTaggantObj->tagObj2->tagBlob.Hash.Hashmap.Entries > 0) { /* Compute hashmap */ res = taggant2_compute_hash_map(pCtx, hFile, &pTaggantObj->tagObj2->tagBlob.Hash.Hashmap, pTaggantObj->tagObj2->tagBlob.pHashMapDoubles); } } } /* Clean hash context */ EVP_MD_CTX_cleanup(&evp); } else { res = TFILEERROR; } } } } else { res = TINVALIDPEFILE; } break; } case TAGGANT_BINFILE: { /* Get the file end excluding existing taggants * Walk through all taggants in file and take offset of the file without taggants * Take offset and size of the latest taggant to include it into hash map */ if (!fileend) { fileend = get_file_size(pCtx, hFile); } res = TNOERR; found = 0; while (res == TNOERR && taggant2_read_binary(pCtx, hFile, fileend, &taggant2, TAGGANT_BINFILE) == TNOERR) { fileend -= taggant2->Header.TaggantLength; /* Get the offset and size of the first found taggant to add it into hashmap */ if (!found) { /* remember that there is a previous taggant in the file */ prevtag = 1; if ((res = taggant2_put_extrainfo(&pTaggantObj->tagObj2->tagBlob.Extrablob, ETAGPREV, sizeof(prevtag), (char*)&prevtag)) == TNOERR) { /* add a hash region of the previous taggant */ if ((res = taggant2_add_hash_region(pTaggantObj->tagObj2, fileend, taggant2->Header.TaggantLength)) == TNOERR) { found++; } } } /* Free the taggant object */ taggant2_free_taggant(taggant2); } if (res == TNOERR) { res = taggant2_compute_hash_raw(pCtx, &pTaggantObj->tagObj2->tagBlob.Hash, hFile, fileend, pTaggantObj->tagObj2->tagBlob.pHashMapDoubles); } break; } default: { res = TTYPE; } } break; default: res = TNOTIMPLEMENTED; break; } return res; } EXPORT UNSIGNED32 STDCALL TaggantPutInfo(__inout PTAGGANTOBJ pTaggantObj, ENUMTAGINFO eKey, UNSIGNED32 pSize, __in_bcount(pSize) PINFO pInfo) { UNSIGNED32 res = TNOTIMPLEMENTED; if (!lib_initialized) { return TLIBNOTINIT; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = taggant_put_info(pTaggantObj->tagObj1, eKey, pSize, pInfo); break; case TAGGANT_LIBRARY_VERSION2: res = taggant2_put_info(pTaggantObj->tagObj2, eKey, pSize, pInfo); break; } return res; } #endif #ifdef SSV_LIBRARY EXPORT UNSIGNED32 STDCALL TaggantGetInfo(__in PTAGGANTOBJ pTaggantObj, ENUMTAGINFO eKey, __inout UNSIGNED32 *pSize, __out_bcount_full_opt(*pSize) PINFO pInfo) { UNSIGNED32 res = TNOTIMPLEMENTED; if (!lib_initialized) { return TLIBNOTINIT; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = taggant_get_info(pTaggantObj->tagObj1, eKey, pSize, pInfo); break; case TAGGANT_LIBRARY_VERSION2: res = taggant2_get_info(pTaggantObj->tagObj2, eKey, pSize, pInfo); break; } return res; } #endif #ifdef SPV_LIBRARY EXPORT UNSIGNED32 STDCALL TaggantPrepare(__inout PTAGGANTOBJ pTaggantObj, __in const PVOID pLicense, __out_bcount_part(*uTaggantReservedSize, *uTaggantReservedSize) PVOID pTaggantOut, __inout UNSIGNED32 *uTaggantReservedSize) { UNSIGNED32 res = TNOTIMPLEMENTED; if (!lib_initialized) { return TLIBNOTINIT; } if (!pLicense) { return TBADKEY; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = taggant_prepare(pTaggantObj->tagObj1, pLicense, pTaggantOut, uTaggantReservedSize); break; case TAGGANT_LIBRARY_VERSION2: res = taggant2_prepare(pTaggantObj->tagObj2, pLicense, pTaggantObj->tagObj2->tagganttype, pTaggantOut, uTaggantReservedSize); break; } return res; } #endif #ifdef SSV_LIBRARY EXPORT __success(return == TNOERR) UNSIGNED32 STDCALL TaggantGetTimestamp(__in PTAGGANTOBJ pTaggantObj, __out UNSIGNED64 *pTime, __in PVOID pTSRootCert) { UNSIGNED32 res = TNOTIMPLEMENTED; if (!lib_initialized) { return TLIBNOTINIT; } if (!pTSRootCert) { return TBADKEY; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = taggant_get_timestamp(pTaggantObj->tagObj1, pTime, pTSRootCert); break; case TAGGANT_LIBRARY_VERSION2: res = taggant2_get_timestamp(pTaggantObj->tagObj2, pTime, pTSRootCert); break; } return res; } #endif #ifdef SPV_LIBRARY EXPORT UNSIGNED32 STDCALL TaggantPutTimestamp(__inout PTAGGANTOBJ pTaggantObj, __in const char* pTSUrl, UNSIGNED32 uTimeout) { UNSIGNED32 res = TNOTIMPLEMENTED; if (!lib_initialized) { return TLIBNOTINIT; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = taggant_put_timestamp(pTaggantObj->tagObj1, pTSUrl, uTimeout); break; case TAGGANT_LIBRARY_VERSION2: res = taggant2_put_timestamp(pTaggantObj->tagObj2, pTSUrl, uTimeout); break; } return res; } #endif EXPORT PTAGGANTOBJ STDCALL TaggantObjectNew(__in_opt PTAGGANT pTaggant) { PTAGGANTOBJ pTaggantObj; return TaggantObjectNewEx(pTaggant, TAGGANT_LIBRARY_CURRENTVERSION, TAGGANT_PEFILE, &pTaggantObj) == TNOERR ? pTaggantObj : NULL; } EXPORT __success(return == TNOERR) UNSIGNED32 STDCALL TaggantObjectNewEx(__in_opt PTAGGANT pTaggant, UNSIGNED64 uVersion, TAGGANTCONTAINER eTaggantType, __out PTAGGANTOBJ *pTaggantObj) { #ifdef SSV_LIBRARY PTAGGANT taggant = (PTAGGANT)pTaggant; #endif UNSIGNED32 res = TNOERR; PTAGGANTOBJ tagObj; UNSIGNED64 ver = TAGGANT_LIBRARY_CURRENTVERSION; if (!lib_initialized) { return TLIBNOTINIT; } #ifdef SSV_LIBRARY ver = taggant->uVersion; #endif #ifdef SPV_LIBRARY /* accept version number for spv only, for ssv works as latest library version */ ver = uVersion; if (ver == TAGGANT_LIBRARY_VERSION1 && (eTaggantType == TAGGANT_JSFILE || eTaggantType == TAGGANT_TXTFILE || eTaggantType == TAGGANT_BINFILE)) { return TTYPE; } #endif tagObj = memory_alloc(sizeof(TAGGANTOBJ)); if (tagObj) { memset(tagObj, 0, sizeof(TAGGANTOBJ)); if (ver == TAGGANT_LIBRARY_VERSION1) { tagObj->tagObj1 = (PTAGGANTOBJ1)memory_alloc(sizeof(TAGGANTOBJ1)); if (tagObj->tagObj1) { memset(tagObj->tagObj1, 0, sizeof(TAGGANTOBJ1)); /* Allocate intial memory for taggant blob and initialize it */ tagObj->tagObj1->pTagBlob = (PTAGGANTBLOB)memory_alloc(sizeof(TAGGANTBLOB)); if (tagObj->tagObj1->pTagBlob) { memset(tagObj->tagObj1->pTagBlob, 0, sizeof(TAGGANTBLOB)); /* Initialize taggant blob */ tagObj->tagObj1->pTagBlob->Header.Version = TAGGANTBLOB_VERSION1; tagObj->tagObj1->pTagBlob->Header.Length = sizeof(TAGGANTBLOB); /* Set the size of the taggant, required for SSV only */ #ifdef SSV_LIBRARY tagObj->tagObj1->uTaggantSize = taggant->pTag1->Header.TaggantLength; #endif res = TNOERR; } else { memory_free(tagObj->tagObj1); tagObj->tagObj1 = NULL; res = TMEMORY; } } else { res = TMEMORY; } } else if (ver == TAGGANT_LIBRARY_VERSION2) { tagObj->tagObj2 = (PTAGGANTOBJ2)memory_alloc(sizeof(TAGGANTOBJ2)); if (tagObj->tagObj2) { memset(tagObj->tagObj2, 0, sizeof(TAGGANTOBJ2)); /* Initialize taggant blob */ tagObj->tagObj2->tagBlob.Header.Version = TAGGANTBLOB_VERSION2; /* Remember the fileend and taggant type values */ #ifdef SSV_LIBRARY tagObj->tagObj2->fileend = taggant->pTag2->fileend; tagObj->tagObj2->tagganttype = taggant->pTag2->tagganttype; #endif #ifdef SPV_LIBRARY tagObj->tagObj2->tagganttype = eTaggantType; #endif res = TNOERR; } else { res = TMEMORY; } } else { res = TNOTIMPLEMENTED; } } else { res = TMEMORY; } if (res == TNOERR) { #ifdef SSV_LIBRARY tagObj->tagParent = pTaggant; #endif #ifdef SPV_LIBRARY tagObj->uVersion = ver; #endif /* Return TAGGANT object */ *pTaggantObj = (void*)tagObj; } else { memory_free(tagObj); } return res; } EXPORT void STDCALL TaggantObjectFree(__deref PTAGGANTOBJ pTaggantObj) { if (!lib_initialized) { return; } if (pTaggantObj) { if (pTaggantObj->tagObj1) { taggant_free_taggantobj_content(pTaggantObj->tagObj1); /* Free memory of taggant object */ memory_free(pTaggantObj->tagObj1); } if (pTaggantObj->tagObj2) { taggant2_free_taggantobj_content(pTaggantObj->tagObj2); /* Free memory of taggant object */ memory_free(pTaggantObj->tagObj2); } memory_free(pTaggantObj); } return; } EXPORT PTAGGANTCONTEXT STDCALL TaggantContextNew(void) { PTAGGANTCONTEXT pCtx; return TaggantContextNewEx(&pCtx) == TNOERR ? pCtx : NULL; } EXPORT __success(return == TNOERR) UNSIGNED32 STDCALL TaggantContextNewEx(__out PTAGGANTCONTEXT *pCtx) { PTAGGANTCONTEXT ctx = NULL; if (!lib_initialized) { return TLIBNOTINIT; } ctx = (PTAGGANTCONTEXT)memory_alloc(sizeof(TAGGANTCONTEXT)); if (!ctx) { return TMEMORY; } ctx->size = sizeof(TAGGANTCONTEXT); ctx->FileReadCallBack = (size_t (__DECLARATION *)(PFILEOBJECT, void*, size_t))&internal_fread; ctx->FileSeekCallBack = (int (__DECLARATION *)(PFILEOBJECT, UNSIGNED64, int))&internal_fseek; ctx->FileTellCallBack = (UNSIGNED64 (__DECLARATION *)(PFILEOBJECT))&internal_ftell; /* Return TAGGANT context */ *pCtx = ctx; return TNOERR; } EXPORT void STDCALL TaggantContextFree(__deref PTAGGANTCONTEXT pTaggantCtx) { if (!lib_initialized) { return; } if (pTaggantCtx) { /* Free memory of taggant context */ memory_free(pTaggantCtx); } return; } #ifdef SPV_LIBRARY EXPORT __success(return == TNOERR) UNSIGNED32 STDCALL TaggantGetLicenseExpirationDate(__in const PVOID pLicense, __out UNSIGNED64 *pTime) { UNSIGNED32 res = TBADKEY; BIO *licbio = NULL; X509 *liccert = NULL, *licspv = NULL; EVP_PKEY *lickey = NULL; ASN1_TIME *exp_date = NULL; ASN1_GENERALIZEDTIME *gn_time = NULL; int year = 0; int month = 0; int day = 0; int hour = 0; int minute = 0; int second = 0; if (!lib_initialized) { return TLIBNOTINIT; } if (!pLicense) { return TBADKEY; } /* Load user license certificate and private key */ licbio = BIO_new(BIO_s_mem()); if (licbio) { BIO_write(licbio, pLicense, (int)strlen((const char*)pLicense)); /* Load SPV certificate and make sure it is valid */ licspv = PEM_read_bio_X509(licbio, NULL, 0, NULL); if (licspv) { /* Free SPV certificate */ X509_free(licspv); /* Load USER certificate and make sure it is valid */ liccert = PEM_read_bio_X509(licbio, NULL, 0, NULL); if (liccert) { /* Load User private key and make sure it is valid */ lickey = PEM_read_bio_PrivateKey(licbio, NULL, 0, NULL); if (lickey) { /* Free private key */ EVP_PKEY_free(lickey); /* Get expiration date of User certificate */ exp_date = X509_get_notAfter(liccert); if (exp_date) { gn_time = ASN1_TIME_to_generalizedtime(exp_date, NULL); if (gn_time) { if (sscanf((const char*)ASN1_STRING_data((ASN1_STRING*)gn_time), "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second) == 6) { *pTime = time_as_unsigned64(year, month, day, hour, minute, second); res = TNOERR; } ASN1_GENERALIZEDTIME_free(gn_time); } } } X509_free(liccert); } } BIO_free(licbio); } return res; } #endif #ifdef SSV_LIBRARY EXPORT UNSIGNED32 STDCALL TaggantCheckCertificate(__in PVOID pCert) { BIO* certbio = NULL; X509* cert = NULL; UNSIGNED32 res; if (!lib_initialized) { return TLIBNOTINIT; } /* Check if certificate buffer is empty */ if (!pCert) { return TINVALID; } /* Load certificate to bio */ res = TMEMORY; certbio = BIO_new(BIO_s_mem()); if (certbio) { res = TINVALID; BIO_write(certbio, pCert, (int)strlen((const char*)pCert)); /* Load certificate */ cert = PEM_read_bio_X509(certbio, NULL, 0, NULL); if (cert) { /* Certificate is valid */ res = TNOERR; /* Free certificate */ X509_free(cert); } /* Free bio */ BIO_free(certbio); } return res; } #endif #ifdef SSV_LIBRARY EXPORT __success(return > 0) UNSIGNED16 STDCALL TaggantGetHashMapDoubles(__in PTAGGANTOBJ pTaggantObj, __out PHASHBLOB_HASHMAP_DOUBLE *pDoubles) { UNSIGNED16 res = 0; if (lib_initialized) { switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: if (pTaggantObj->tagObj1->pTagBlob->Hash.Hashmap.Entries && ((pTaggantObj->tagObj1->pTagBlob->Hash.Hashmap.DoublesOffset + (pTaggantObj->tagObj1->pTagBlob->Hash.Hashmap.Entries * sizeof(HASHBLOB_HASHMAP_DOUBLE))) <= pTaggantObj->tagObj1->pTagBlob->Header.Length)) { *pDoubles = (PHASHBLOB_HASHMAP_DOUBLE)((char*)pTaggantObj->tagObj1->pTagBlob + pTaggantObj->tagObj1->pTagBlob->Hash.Hashmap.DoublesOffset); res = pTaggantObj->tagObj1->pTagBlob->Hash.Hashmap.Entries; } break; case TAGGANT_LIBRARY_VERSION2: if (pTaggantObj->tagObj2->tagBlob.Hash.Hashmap.Entries && ((pTaggantObj->tagObj2->tagBlob.Hash.Hashmap.DoublesOffset + (pTaggantObj->tagObj2->tagBlob.Hash.Hashmap.Entries * sizeof(HASHBLOB_HASHMAP_DOUBLE))) <= pTaggantObj->tagObj2->tagBlob.Header.Length)) { *pDoubles = pTaggantObj->tagObj2->tagBlob.pHashMapDoubles; res = pTaggantObj->tagObj2->tagBlob.Hash.Hashmap.Entries; } break; } } return res; } #endif EXPORT PPACKERINFO STDCALL TaggantPackerInfo(__in PTAGGANTOBJ pTaggantObj) { PPACKERINFO res = NULL; if (lib_initialized) { switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = &pTaggantObj->tagObj1->pTagBlob->Header.PackerInfo; break; case TAGGANT_LIBRARY_VERSION2: res = &pTaggantObj->tagObj2->tagBlob.Header.PackerInfo; break; } } return res; } #ifdef SSV_LIBRARY EXPORT UNSIGNED32 STDCALL TaggantValidateDefaultHashes(__in PTAGGANTCONTEXT pCtx, __in PTAGGANTOBJ pTaggantObj, __in PFILEOBJECT hFile, UNSIGNED64 uObjectEnd, UNSIGNED64 uFileEnd) { UNSIGNED32 res = TNOTIMPLEMENTED; UNSIGNED64 filend = uFileEnd; if (!lib_initialized) { return TLIBNOTINIT; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = taggant_validate_default_hashes(pCtx, pTaggantObj->tagObj1, hFile, uObjectEnd, uFileEnd); break; case TAGGANT_LIBRARY_VERSION2: if (!filend) { filend = pTaggantObj->tagParent->pTag2->ffhend; } switch (pTaggantObj->tagObj2->tagganttype) { case TAGGANT_JSFILE: { res = taggant2_validate_default_hashes_js(pCtx, pTaggantObj->tagObj2, hFile, filend); break; } case TAGGANT_TXTFILE: { res = taggant2_validate_default_hashes_txt(pCtx, pTaggantObj->tagObj2, hFile, filend); break; } case TAGGANT_PEFILE: { res = taggant2_validate_default_hashes_pe(pCtx, pTaggantObj->tagObj2, hFile, uObjectEnd, filend); break; } case TAGGANT_BINFILE: { res = taggant2_validate_default_hashes_bin(pCtx, pTaggantObj->tagObj2, hFile, filend); break; } default: { res = TTYPE; } } break; } return res; } EXPORT UNSIGNED32 STDCALL TaggantValidateHashMap(__in PTAGGANTCONTEXT pCtx, __in PTAGGANTOBJ pTaggantObj, __in PFILEOBJECT hFile) { UNSIGNED32 res = TNOTIMPLEMENTED; if (!lib_initialized) { return TLIBNOTINIT; } switch (get_lib_version(pTaggantObj)) { case TAGGANT_LIBRARY_VERSION1: res = taggant_validate_hashmap(pCtx, pTaggantObj->tagObj1, hFile); break; case TAGGANT_LIBRARY_VERSION2: res = taggant2_validate_hashmap(pCtx, pTaggantObj->tagObj2, hFile); break; } return res; } #endif <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #ifndef TYPES_HEADER #define TYPES_HEADER #include <openssl/bio.h> #include <openssl/cms.h> #include <openssl/ts.h> #include "taggant_types.h" #ifdef TAGGANT_LIBRARY /* Maximum buffer for conversion of X509 to binary */ #define MAX_INTEGER 0x7FFFFFFF #define HASH_SHA256_DIGEST_SIZE 32 #define HASHBLOB_VERSION1 1 #define TAGGANTBLOB_VERSION1 1 #define HASHBLOB_VERSION2 1 #define TAGGANTBLOB_VERSION2 1 #define TAGGANT_VERSION1 1 #define TAGGANT_VERSION2 2 #define TAGGANT_MARKER_BEGIN 0x47474154 /* 'T'A'G'G' */ #define TAGGANT_MARKER_END 0x53544E41 /* 'A'N'T'S' */ #define HASHMAP_MAXIMUM_ENTRIES 100 /* TODO: Correct this value after testing with real certification system */ typedef enum { TAGGANT_HASBLOB_DEFAULT = 0, TAGGANT_HASBLOB_EXTENDED = 1, TAGGANT_HASBLOB_HASHMAP = 2, } TAGGANTHASHBLOBTYPE; #pragma pack(push,2) typedef struct { UNSIGNED16 Length; /* not implemented in the current specification char Data[0]; */ } EXTRABLOB, *PEXTRABLOB; typedef struct { UNSIGNED16 Length; PVOID Data; } EXTRABLOB2, *PEXTRABLOB2; typedef struct { UNSIGNED16 Length; UNSIGNED16 Type; UNSIGNED16 Version; unsigned char Hash[HASH_SHA256_DIGEST_SIZE]; } HASHBLOB_HEADER, *PHASHBLOB_HEADER; typedef struct { HASHBLOB_HEADER Header; } HASHBLOB_DEFAULT, *PHASHBLOB_DEFAULT; typedef struct { HASHBLOB_HEADER Header; UNSIGNED64 PhysicalEnd; } HASHBLOB_EXTENDED, *PHASHBLOB_EXTENDED; typedef struct { HASHBLOB_HEADER Header; UNSIGNED16 Entries; /* Offset to doubles array from begin of TAGGANTBLOB structure */ UNSIGNED16 DoublesOffset; } HASHBLOB_HASHMAP, *PHASHBLOB_HASHMAP; typedef struct { HASHBLOB_DEFAULT DefaultHash; HASHBLOB_EXTENDED ExtendedHash; } HASHBLOB_FULLFILE, *PHASHBLOB_FULLFILE; typedef struct { HASHBLOB_FULLFILE FullFile; HASHBLOB_HASHMAP Hashmap; } HASHBLOB, *PHASHBLOB; typedef struct { UNSIGNED16 Length; UNSIGNED16 Version; PACKERINFO PackerInfo; } TAGGANTBLOB_HEADER, *PTAGGANTBLOB_HEADER; typedef struct { TAGGANTBLOB_HEADER Header; HASHBLOB Hash; EXTRABLOB Extrablob; /* Array of hash map doubles HASHBLOB_HASHMAP_DOUBLE pHashMapDoubles[1]; */ } TAGGANTBLOB, *PTAGGANTBLOB; typedef struct { TAGGANTBLOB_HEADER Header; HASHBLOB Hash; EXTRABLOB2 Extrablob; /* Array of hash map doubles */ PHASHBLOB_HASHMAP_DOUBLE pHashMapDoubles; } TAGGANTBLOB2, *PTAGGANTBLOB2; typedef struct { UNSIGNED32 MarkerBegin; UNSIGNED32 TaggantLength; UNSIGNED32 CMSLength; UNSIGNED16 Version; } TAGGANT_HEADER, *PTAGGANT_HEADER; typedef struct { UNSIGNED16 Version; UNSIGNED32 CMSLength; UNSIGNED32 TaggantLength; UNSIGNED32 MarkerBegin; } TAGGANT_HEADER2, *PTAGGANT_HEADER2; typedef struct { EXTRABLOB Extrablob; UNSIGNED32 MarkerEnd; } TAGGANT_FOOTER, *PTAGGANT_FOOTER; typedef struct { UNSIGNED32 MarkerEnd; } TAGGANT_FOOTER2, *PTAGGANT_FOOTER2; typedef struct { /* taggant offset from the beginning of the file */ UNSIGNED64 offset; TAGGANT_HEADER Header; PVOID CMSBuffer; TAGGANT_FOOTER Footer; } TAGGANT1, *PTAGGANT1; typedef struct { TAGGANT_HEADER2 Header; PVOID CMSBuffer; UNSIGNED32 CMSBufferSize; TAGGANT_FOOTER2 Footer; /* the current file position to check for a next taggant */ UNSIGNED64 fileend; /* end of full file hash, the size of the file without taggants */ UNSIGNED64 ffhend; /* type of the file currently processed */ TAGGANTCONTAINER tagganttype; } TAGGANT2, *PTAGGANT2; typedef struct { #ifdef SSV_LIBRARY /* for SSV only, contains a taggant version that the library should search */ UNSIGNED64 uVersion; TAGGANTCONTAINER tagganttype; #endif PTAGGANT1 pTag1; PTAGGANT2 pTag2; } TAGGANT, *PTAGGANT; #pragma pack(pop) typedef struct { X509 *root; X509 *spv; X509 *user; CMS_ContentInfo* CMS; TS_RESP* TSResponse; PTAGGANTBLOB pTagBlob; UNSIGNED32 uTaggantSize; } TAGGANTOBJ1, *PTAGGANTOBJ1; typedef struct { X509 *root; X509 *spv; X509 *user; CMS_ContentInfo* CMS; TS_RESP* TSResponse; TAGGANTBLOB2 tagBlob; UNSIGNED64 fileend; TAGGANTCONTAINER tagganttype; } TAGGANTOBJ2, *PTAGGANTOBJ2; typedef struct { #ifdef SSV_LIBRARY PTAGGANT tagParent; #endif #ifdef SPV_LIBRARY /* for SPV only, determines the version of the library that it is working for */ UNSIGNED64 uVersion; #endif PTAGGANTOBJ1 tagObj1; PTAGGANTOBJ2 tagObj2; } TAGGANTOBJ, *PTAGGANTOBJ; #endif /* TAGGANT_LIBRARY */ #endif /* TYPES_HEADER */ <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #ifdef SPV_LIBRARY #include <stdio.h> #include <string.h> #ifdef WIN32 #include <winsock2.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/types.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #endif #ifdef WIN32 # define SOCKET_DESCRIPTOR SOCKET #else # define SOCKET_DESCRIPTOR int # ifndef INVALID_SOCKET # define INVALID_SOCKET (-1) # endif #endif #include "http.h" #include "callbacks.h" #include "miscellaneous.h" const char *HTTP_Header_Location = "Location: "; int safe_send(SOCKET_DESCRIPTOR socketDescriptor, const void *buffer, int length, int flag); void close_socket(SOCKET_DESCRIPTOR socketDescriptor); int http_read(const char *hostName, const void *requestString, int requestLength, int port, int readTimeOut, int contentOnly, void **resultBuffer, int *resultBufferLength) { int responseStatusCode = 0; SOCKET_DESCRIPTOR socketDescriptor; struct hostent *host; struct sockaddr_in serverAddr; char *buffer = NULL; int bytes_read = 0; int count = 0; int readCount = 0; int res; char *r_start, *r_end; #ifdef WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); #endif socketDescriptor = socket(AF_INET, SOCK_STREAM, 0); if (socketDescriptor == INVALID_SOCKET) { #ifdef WIN32 WSACleanup(); #endif return HTTP_SOCKET_ERROR; } host = (struct hostent *) gethostbyname(hostName); if (host == NULL) { res = HTTP_NOLIVEINTERNET_ERROR; goto exit_sopened; } memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = (short)host->h_addrtype; serverAddr.sin_port = htons((unsigned short)port); serverAddr.sin_addr.s_addr = *(unsigned long*)host->h_addr; if (connect(socketDescriptor, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) { res = HTTP_CONNECT_ERROR; goto exit_sopened; } /* Send request */ if (safe_send(socketDescriptor, requestString, requestLength, 0) != requestLength) { res = HTTP_SEND_ERROR; goto exit_sopened; } buffer = (char*)memory_alloc(0); count = 0; for(;;) { fd_set rfds; struct timeval tv; int selectResult; tv.tv_sec = readTimeOut; tv.tv_usec = 0; FD_ZERO(&rfds); FD_SET(socketDescriptor, &rfds); selectResult = select((int)socketDescriptor + 1, &rfds, NULL, NULL, &tv); if ((selectResult == 0) || (selectResult == -1)) { res = HTTP_READTIMEOUT_ERROR; goto exit_sopened; } count++; buffer = (char*)memory_realloc((void*)buffer, HTTP_READ_BUFFER_SIZE * count); if (!buffer) { res = HTTP_RECEIVE_ERROR; goto exit_sopened; } #ifdef WIN32 readCount = recv(socketDescriptor, buffer + bytes_read, HTTP_READ_BUFFER_SIZE, 0); #else readCount = read(socketDescriptor, buffer + bytes_read, HTTP_READ_BUFFER_SIZE); #endif if (readCount == 0) { buffer[bytes_read] = '\0'; break; } if (readCount < 0) { res = HTTP_RECEIVE_ERROR; goto exit_sopened; } bytes_read += readCount; } close_socket(socketDescriptor); if (buffer) { if (sscanf(buffer, "%*s %d", &responseStatusCode) != 1) { res = HTTP_RECEIVE_ERROR; goto exit_buffree; } } switch (responseStatusCode) { case 200: { /* Status is OK */ break; } case 301: case 302: { /* Redirection, extract new location */ if (buffer) { r_start = strstr(buffer, HTTP_Header_Location); if (r_start) { r_start += strlen(HTTP_Header_Location); r_end = strstr(r_start, "\r\n"); if (r_end && r_end > r_start) { *resultBufferLength = r_end - r_start; *resultBuffer = memory_alloc(*resultBufferLength + 1); if (!*resultBuffer) { res = HTTP_RECEIVE_ERROR; goto exit_buffree; } memcpy(*resultBuffer, r_start, *resultBufferLength); /* Put null terminating character */ ((char*)*resultBuffer)[*resultBufferLength] = '\0'; *resultBufferLength += 1; res = HTTP_REDIRECTION; goto exit_buffree; } } } break; } default: { /* No HTTP return code */ res = HTTP_RESPONSESTATUS_ERROR; goto exit_buffree; } } if (contentOnly == 0) { *resultBuffer = buffer; *resultBufferLength = bytes_read; } else { int headerLength; char* temp = strstr(buffer, "\r\n\r\n"); headerLength = (int)(temp - buffer + 4); res = HTTP_CONTENT_ERROR; if (!temp) goto exit_buffree; *resultBuffer = memory_alloc(bytes_read - headerLength); if (!*resultBuffer) goto exit_buffree; *resultBuffer = memcpy(*resultBuffer, temp + 4, bytes_read - headerLength); *resultBufferLength = bytes_read - headerLength; res = HTTP_NOERROR; goto exit_buffree; } res = HTTP_NOERROR; goto exit; exit_sopened: close_socket(socketDescriptor); exit_buffree: if (buffer) { memory_free(buffer); } exit: return res; } int safe_send(SOCKET_DESCRIPTOR socketDescriptor, const void *buffer, int length, int flag) { int sentCount = 0; char *point = (char*)buffer; while(sentCount < length) { int tempResult; #ifdef WIN32 tempResult = send(socketDescriptor, (const char*)point, length - sentCount, flag); if(tempResult == SOCKET_ERROR || tempResult == 0) { return -1; } #else tempResult = write(socketDescriptor, (const void*)point, length - sentCount); if(tempResult <= 0) { return -1; } #endif point += tempResult; sentCount += tempResult; } return sentCount; } void close_socket(SOCKET_DESCRIPTOR socketDescriptor) { #ifdef WIN32 closesocket(socketDescriptor); WSACleanup(); #else close(socketDescriptor); #endif } #endif <file_sep>/* * winpe.c * * Created on: Oct 16, 2011 * Author: Enigma */ #include <iostream> #include <fstream> #include <istream> #include <string> #include "fileio.h" #include "winpe.h" #include "winpe_types.h" #include "miscellaneous.h" using namespace std; int winpe_raw_section_offset(PE_ALL_HEADERS* peh, IMAGE_SECTION_HEADER* sec) { long section_alignment; // section_alignment = (winpe_is_pe64(peh)) ? peh->oh.pe64.SectionAlignment : peh->oh.pe32.SectionAlignment; if (section_alignment >= 0x1000) { return round_down(0x200, sec->PointerToRawData); } return sec->PointerToRawData; } int winpe_section_size(PE_ALL_HEADERS* peh, IMAGE_SECTION_HEADER* sec) { long section_alignment; long file_alignment; // section_alignment = (winpe_is_pe64(peh)) ? peh->oh.pe64.SectionAlignment : peh->oh.pe32.SectionAlignment; file_alignment = (winpe_is_pe64(peh)) ? peh->oh.pe64.FileAlignment : peh->oh.pe32.FileAlignment; return (sec->Misc.VirtualSize ? min(round_up(section_alignment, sec->Misc.VirtualSize), round_up(file_alignment, sec->SizeOfRawData)) : round_up(file_alignment, sec->SizeOfRawData)); } int winpe_is_pe64(PE_ALL_HEADERS* peh) { if (peh->fh.Machine == IMAGE_FILE_MACHINE_I386) { return 0; } return 1; } int winpe_object_size(ifstream* fp, PE_ALL_HEADERS* peh) { UNSIGNED64 filelength; int res = -1; // check is number of sections greater zero if (peh->fh.NumberOfSections > 0) { long filepos = peh->dh.e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + peh->fh.SizeOfOptionalHeader; // shift file pointer to the sections array if (fileio_fseek(fp, filepos, SEEK_SET) == 0) { int i; IMAGE_SECTION_HEADER fs; for (i = 0; i < peh->fh.NumberOfSections; i++) { // read section from the file if (fileio_fread(fp, &fs, sizeof(IMAGE_SECTION_HEADER)) == sizeof(IMAGE_SECTION_HEADER)) { if (winpe_raw_section_offset(peh, &fs) != 0) { res = winpe_raw_section_offset(peh, &fs) + winpe_section_size(peh, &fs); } filepos += sizeof(IMAGE_SECTION_HEADER); if (fileio_fseek(fp, filepos, SEEK_SET) != 0) { res = -1; break; } } else { res = -1; break; } } } } filelength = fileio_fsize(fp); return min(res, (int) filelength); } int winpe_va_to_rwa(ifstream* fp, PE_ALL_HEADERS* peh, unsigned long va) { if (peh->fh.NumberOfSections == 0) { return va; } if (winpe_is_pe64(peh)) { if (va < peh->oh.pe32.SizeOfHeaders) { return va; } } else { if (va < peh->oh.pe64.SizeOfHeaders) { return va; } } // check is number of sections greater zero if (peh->fh.NumberOfSections > 0) { long filepos = peh->dh.e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + peh->fh.SizeOfOptionalHeader; // shift file pointer to the sections array if (fileio_fseek(fp, filepos, SEEK_SET) == 0) { // reading all sections and find rwa address int i; IMAGE_SECTION_HEADER fs; for (i = 0; i < peh->fh.NumberOfSections; i++) { // read section from the file if (fileio_fread(fp, &fs, sizeof(IMAGE_SECTION_HEADER)) == sizeof(IMAGE_SECTION_HEADER)) { // if (va < fs.VirtualAddress) { break; } else if (winpe_raw_section_offset(peh, &fs) != 0) { if (va >= fs.VirtualAddress && va < (fs.VirtualAddress + winpe_section_size(peh, &fs))) { return va - fs.VirtualAddress + winpe_raw_section_offset(peh, &fs); } } filepos += sizeof(IMAGE_SECTION_HEADER); if (fileio_fseek(fp, filepos, SEEK_SET) != 0) { break; } } else { break; } } } } return -1; } long winpe_entry_point_physical_offset(ifstream* fp, PE_ALL_HEADERS* peh) { if (winpe_is_pe64(peh)) { if (peh->oh.pe64.AddressOfEntryPoint != 0) { return winpe_va_to_rwa(fp, peh, peh->oh.pe64.AddressOfEntryPoint); } } else { if (peh->oh.pe32.AddressOfEntryPoint != 0) { return winpe_va_to_rwa(fp, peh, peh->oh.pe32.AddressOfEntryPoint); } } return -1; } int winpe_is_correct_pe_file(ifstream* fp, PE_ALL_HEADERS* peh) { // remember the size of the file UNSIGNED64 filesize = fileio_fsize(fp); // make sure filesize is greater than size of DOS header if (filesize >= sizeof(IMAGE_DOS_HEADER)) { // seek file to the file beginning if (fileio_fseek(fp, 0L, SEEK_SET) == 0) { // make sure dos header is read fully if (fileio_fread(fp, &peh->dh, sizeof(IMAGE_DOS_HEADER)) == sizeof(IMAGE_DOS_HEADER)) { // check dos header e_magic if (peh->dh.e_magic == IMAGE_DOS_SIGNATURE) { if (filesize >= peh->dh.e_lfanew) { // seek file to the dh.e_magic from beginning if (fileio_fseek(fp, peh->dh.e_lfanew, SEEK_SET) == 0) { // read file signature if (fileio_fread(fp, &peh->signature, sizeof(DWORD)) == sizeof(DWORD)) { if (peh->signature == IMAGE_NT_SIGNATURE) { // read file header if (fileio_fread(fp, &peh->fh, sizeof(IMAGE_FILE_HEADER)) == sizeof(IMAGE_FILE_HEADER)) { // As MSDN says, only these types of files can be run in Windows switch (peh->fh.Machine) { case IMAGE_FILE_MACHINE_I386: { // PE32 file, read optional header memset(&peh->oh.pe32, 0, sizeof(IMAGE_OPTIONAL_HEADER32)); if (fileio_fread(fp, &peh->oh.pe32, sizeof(IMAGE_OPTIONAL_HEADER32)) == sizeof(IMAGE_OPTIONAL_HEADER32)) { if (peh->oh.pe32.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) { return 1; } } break; } case IMAGE_FILE_MACHINE_AMD64: { memset(&peh->oh.pe64, 0, sizeof(IMAGE_OPTIONAL_HEADER64)); if (fileio_fread(fp, &peh->oh.pe64, sizeof(IMAGE_OPTIONAL_HEADER64)) == sizeof(IMAGE_OPTIONAL_HEADER64)) { if (peh->oh.pe64.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) { return 1; } } break; } default: { break; } } } } } } } } } } } return 0; } <file_sep>/* ==================================================================== * Copyright (c) 2012 IEEE. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * 4. The name "IEEE" must not be used to endorse or promote products * derived from this software without prior written permission from * the IEEE Standards Association (<EMAIL>). * * 5. Products derived from this software may not contain "IEEE" in * their names without prior written permission from the IEEE Standards * Association (<EMAIL>). * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the IEEE Industry * Connections Security Group (ICSG)". * * THIS SOFTWARE IS PROVIDED "AS IS" AND "WITH ALL FAULTS." IEEE AND ITS * CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND REPRESENTATIONS, * EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION: (A) THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE; * (B) ANY WARRANTY OF NON-INFRINGEMENT; AND (C) ANY WARRANTY WITH RESPECT * TO THE QUALITY, ACCURACY, EFFECTIVENESS, CURRENCY OR COMPLETENESS OF * THE SOFTWARE. * * IN NO EVENT SHALL IEEE OR ITS 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 AND REGARDLESS OF WHETHER SUCH DAMAGE WAS * FORESEEABLE. * * THIS SOFTWARE USES STRONG CRYPTOGRAPHY, WHICH MAY BE SUBJECT TO LAWS * AND REGULATIONS GOVERNING ITS USE, EXPORTATION OR IMPORTATION. YOU ARE * SOLELY RESPONSIBLE FOR COMPLYING WITH ALL APPLICABLE LAWS AND * REGULATIONS, INCLUDING, BUT NOT LIMITED TO, ANY THAT GOVERN YOUR USE, * EXPORTATION OR IMPORTATION OF THIS SOFTWARE. IEEE AND ITS CONTRIBUTORS * DISCLAIM ALL LIABILITY ARISING FROM YOUR USE OF THE SOFTWARE IN * VIOLATION OF ANY APPLICABLE LAWS OR REGULATIONS. * ==================================================================== */ #ifndef WINPE_TYPES_H_ #define WINPE_TYPES_H_ typedef long LONG; typedef unsigned char BYTE,*PBYTE; typedef unsigned short WORD,*PWORD; typedef unsigned long DWORD,*PDWORD; typedef unsigned long long ULONGLONG; #define IMAGE_DOS_SIGNATURE 0x5A4D #define IMAGE_NT_SIGNATURE 0x00004550 #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 #define IMAGE_FILE_MACHINE_I386 0x014c /* Intel 386 or later processors */ #define IMAGE_FILE_MACHINE_IA64 0x0200 /* Intel Itanium processor family */ #define IMAGE_FILE_MACHINE_AMD64 0x8664 /* x64 */ #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b #define IMAGE_SIZEOF_SHORT_NAME 8 #pragma pack(push,1) typedef struct _TAG_IMAGE_DOS_HEADER { WORD e_magic; WORD e_cblp; WORD e_cp; WORD e_crlc; WORD e_cparhdr; WORD e_minalloc; WORD e_maxalloc; WORD e_ss; WORD e_sp; WORD e_csum; WORD e_ip; WORD e_cs; WORD e_lfarlc; WORD e_ovno; WORD e_res[4]; WORD e_oemid; WORD e_oeminfo; WORD e_res2[10]; LONG e_lfanew; } TAG_IMAGE_DOS_HEADER,*PTAG_IMAGE_DOS_HEADER; typedef struct _TAG_IMAGE_FILE_HEADER { WORD Machine; WORD NumberOfSections; DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; WORD Characteristics; } TAG_IMAGE_FILE_HEADER, *TAG_PIMAGE_FILE_HEADER; typedef struct _TAG_IMAGE_DATA_DIRECTORY { DWORD VirtualAddress; DWORD Size; } TAG_IMAGE_DATA_DIRECTORY,*PTAG_IMAGE_DATA_DIRECTORY; typedef struct _TAG_IMAGE_OPTIONAL_HEADER { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; DWORD BaseOfData; DWORD ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; DWORD SizeOfStackReserve; DWORD SizeOfStackCommit; DWORD SizeOfHeapReserve; DWORD SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; TAG_IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } TAG_IMAGE_OPTIONAL_HEADER32,*PTAG_IMAGE_OPTIONAL_HEADER32; typedef struct _TAG_IMAGE_OPTIONAL_HEADER64 { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; ULONGLONG ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; ULONGLONG SizeOfStackReserve; ULONGLONG SizeOfStackCommit; ULONGLONG SizeOfHeapReserve; ULONGLONG SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; TAG_IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } TAG_IMAGE_OPTIONAL_HEADER64,*PTAG_IMAGE_OPTIONAL_HEADER64; typedef struct _TAG_IMAGE_SECTION_HEADER { BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; union { DWORD PhysicalAddress; DWORD VirtualSize; } Misc; DWORD VirtualAddress; DWORD SizeOfRawData; DWORD PointerToRawData; DWORD PointerToRelocations; DWORD PointerToLinenumbers; WORD NumberOfRelocations; WORD NumberOfLinenumbers; DWORD Characteristics; } TAG_IMAGE_SECTION_HEADER,*PTAG_IMAGE_SECTION_HEADER; #pragma pack(pop) #endif /* WINPE_TYPES_H_ */
dd53007118416fe3ae63cf1b96c596a5693dbd50
[ "Markdown", "C", "C++" ]
35
C
obs1dium/IEEE_Taggant_System
60b79c0709c092b796c982d9a2e74f27dca9c5e6
95452ea89a48e6e1c1180b3509b4cedef869e5f1
refs/heads/master
<repo_name>smwillson/mws-restaurant-stage-1<file_sep>/README.md # Mobile Web Specialist Certification Course --- #### _Three Stage Course Material Project - Restaurant Reviews_ ## Project Overview: Stage 1 # How to download/clone the project? In order to clone the project onto your computer via HTTPS URLs (recommended) do the following: 1. Open a new command prompt window 2. Type git clone https://github.com/smwillson/mws-restaurant-stage-1.git at the prompt. More information : https://help.github.com/articles/which-remote-url-should-i-use/ # How to run the application: In order to run the application, navigate to the directory where the project was downloaded to. 1. From inside the directory, launch a local client server using Python from your terminal: #### _Python 2: python -m SimpleHTTPServer 8000_ #### _Python 3: python3 -m http.server 8000_ Find out which version of Python is installed by issuing the command python --version in a terminal window. 2. Visit the site in your browser at http://localhost:8000 The following updates have been made the core functional code provided by Udacity: 1. Added responsiveness. The application has been tested on various mobile devices(in different orientations). 2. Added accessibility. This is to enable disabled users to easily navigate. 3. Caching. Wherever available, the app will cache content. Additionally, I have used pictures taken by myself as content in the project. <file_sep>/js/offline.js var errorPictureArray =[ `../img/errpic1.jpg`, `../img/errpic2.jpg`, `../img/errpic3.jpg`, `../img/errpic4.jpg`, ]; var picNumber = Math.floor(Math.random() * 3); var errorImage = document.createElement('img'); errorImage.src =errorPictureArray[picNumber]; errorImage.setAttribute('alt','Image of my cat Nacho TacoCat showcasing an error when interet is unavailable'); var imgDiv = document.getElementsByClassName('errMsgImg')[0]; imgDiv.append(errorImage); <file_sep>/sw.js /* service worker in depth: https://github.com/GoogleChromeLabs/airhorn/blob/master/app/index.html*/ var RESTAURANTS_CACHE = 'restaurantReviewsCache'; /* * This is the first event in the life cycle of the service worker. This process caches the desired content in the scope * of the service worker. However, the caching is dependent on the availability of the files and the * fulfillment of the promise. If the promise fails, service is unable to install and resources arent cached. * */ self.addEventListener('install', e => { e.waitUntil( caches.open(RESTAURANTS_CACHE).then(cache => { return cache.addAll([ `/`, `/index.html`, `/css/styles.css`, `/js/main.js`, `/js/restaurant_info.js`, `/js/dbhelper.js`, `/offline.html`, `/js/offline.js`, `/data/restaurants.json`, `/img/errpic1.jpg`, `/img/errpic2.jpg`, `/img/errpic3.jpg`, `/img/errpic4.jpg`, ]) .then(() => self.skipWaiting()); }) ); }); self.addEventListener('activate', event => { event.waitUntil(self.clients.claim()); }); /* * *After a service worker is successfully registered and install, we either try to fetch content from cache or the network. *If both of those actions fails, the user is redirected to an offline page which displays some pertinent information. * */ self.addEventListener('fetch', event => { event.respondWith( caches.open(RESTAURANTS_CACHE) .then(cache => cache.match(event.request)) .then(response => { return response || fetch(event.request).catch(err => { return caches.match('/offline.html'); }); }) ); });
763376083d1c48fe5d8f502a7cae3bf3a2ef1b9c
[ "Markdown", "JavaScript" ]
3
Markdown
smwillson/mws-restaurant-stage-1
77af579bafe6c33ca9ee4896d72502f6e6b6f453
a54c6164a79175c393b744b8e39a92e2c78583fc
refs/heads/eco-develop
<repo_name>stephcyrille/fgi-ecosystem<file_sep>/resources/js/frontend/front_office/store.js import {createReducer, createAction } from 'redux-act'; const initialState = { developer: "---" }; const actions = {name: "appCStoreActions"}; const store = createReducer({}, initialState); // stores are called reducers actions.setDeveloperName = createAction('APP_STORE__SET_DEVELOPER_NAME'); store.on(actions.setDeveloperName, (state, value) => ({ ...state, developer: value })); export { store as appCStore, actions as appCStoreActions }; <file_sep>/routes/api.php <?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::post('auth/register', 'API\AuthenticationController@register'); Route::post('auth/login', 'API\AuthenticationController@login'); Route::get('auth/users/all', 'API\UserController@index'); Route::get('profiles/all', 'API\ProfileController@index'); Route::post('profiles/check/email', 'API\ProfileController@check'); // Route::middleware('auth:api')->group( function () { // Route::resource('products', 'API\ProductController'); // }); <file_sep>/resources/js/frontend/front_office/routes/routes.js import React, { Component } from "react"; import { BrowserRouter as Router, Switch, Route, withRouter, Redirect } from "react-router-dom"; //import url import urls from "./urls"; import requireAuth from "../components/Authentication/authComponent" //import components import Home from "../../front_office/components/Home/index.js"; import Login from "../components/Authentication/Login/index" import NotFound from "../components/404/index" @withRouter class Routes extends Component { render() { return ( <Switch> <Route exact path={urls.LOGIN} component={Login} /> <Route exact path={urls.HOME} component={requireAuth(Home)} /> <Route exact path={urls.NOTFOUND} component={NotFound} /> <Redirect to={urls.NOTFOUND} /> </Switch> ); } } export default Routes; <file_sep>/app/Http/Controllers/API/AuthenticationController.php <?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\API\BaseController as BaseController; use Validator; use App\Models\User; use App\Models\Profile; class AuthenticationController extends BaseController { /** * Register api * * @return \Illuminate\Http\Response */ public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => '<PASSWORD>', 'password_confirmation' => '<PASSWORD>|same:password', 'first_name' => 'required', 'last_name' => 'required', 'birthdate' => 'required', ]); if($validator->fails()){ return $this->sendError('Erreur de validation.', $validator->errors()); } $input = [ 'name' => $request->get('name'), 'email' => $request->get('email'), 'password' => $request->get('password'), ]; $input['password'] = <PASSWORD>($input['<PASSWORD>']); $user = User::create($input); $value = [ 'username' => $request->get('name'), 'email' => $request->get('email'), 'first_name' => $request->get('first_name'), 'last_name' => $request->get('last_name'), 'birthdate' => $request->get('birthdate'), 'user_id' => $user->id, ]; $profile = Profile::create($value); $success['token'] = $user->createToken('MyApp')->accessToken; $success['name'] = $user->name; return $this->sendResponse($success, 'Enregistrement de l\'utilisateur réussie.'); } /** * Login api * * @return \Illuminate\Http\Response */ public function login(Request $request) { if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ $user = Auth::user(); $success['token'] = $user->createToken('MyApp')->accessToken; $success['userprofile'] = Profile::where('user_id', $user->id)->first(); return $this->sendResponse($success, 'Connexion de l\'utilisateur réussie.'); } else{ return $this->sendError('Le mot de passe est incorrect.', ['error'=>'Non autorisé']); } } }<file_sep>/resources/js/frontend/front_office/components/Authentication/store.js import { createAction, createReducer } from "redux-act"; const initialState = { token: localStorage.getItem("appToken"), user: localStorage.getItem("user"), // permet au composant login de savoir si l api /rest-auth/user a ete appele is_authentication_checked: false, isAuthenticated: false, }; const actions = { name: "authGuardCStoreActions" }; const store = createReducer({}, initialState); // stores are called reducers // Initializing state actions.initialState = createAction("AUTH_GUARD__INIT") store.on(actions.initialState, (state) => ( { ...state, ...initialState }) ) // Creation actions for Authentication checking actions.setAuthChecked = createAction("AUTH_GUARD__SET_AUTH_CHECKED") store.on(actions.setAuthChecked, (state) => ( { ...state, is_authentication_checked: true }) ) actions.unsetAuthChecked = createAction("AUTH_GUARD__UNSET_AUTH_CHECKED") store.on(actions.unsetAuthChecked, (state) => ( { ...state, is_authentication_checked: false }) ) actions.setIsAuthenticate = createAction("AUTH_GUARD__SET_IS_AUTHENTICATE", {}); store.on(actions.setIsAuthenticate, (state, token) => ({ ...state, token: token, isAuthenticated: true, })); actions.unsetIsAuthenticate = createAction("AUTH_GUARD__UNSET_IS_AUTHENTICATE", {}); store.on(actions.unsetIsAuthenticate, (state, token) => ({ ...state, token: null, isAuthenticated: false, })); export { store as authGuardCStore, actions as authGuardCStoreActions }; <file_sep>/resources/js/frontend/front_office/routes/urls.js // this file contains urls const urls = { HOME: "/", LOGIN: "/login", NOTFOUND: "/404" }; export default urls; <file_sep>/resources/js/frontend/front_office/components/404/index.js import React from "react"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { push } from "react-router-redux"; import './style.local.scss' export default @connect((state, props) => ({})) class NotFound extends React.Component { componentWillMount(){ const title = "Page introuvable | Fac'Social" document.title = title } render(){ return ( <div className="body404"> <h3 className="text-center h3404">404 | Page introuvable</h3> </div> ) } }<file_sep>/resources/js/frontend/config.js const config = { name: "<NAME>" } export default config<file_sep>/resources/js/frontend/front_office/App.js import React, { Component } from "react"; import ReactNotification from "react-notifications-component"; //import libraries import Routes from "./routes/routes"; import { IntlProvider } from "react-intl"; import _ from "underscore"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { initAxios } from "../libs/utils/auth_utils"; initAxios(); export default @connect((state, props) => ({ // lang: state.languageSelectorCStore.language })) class App extends Component { constructor(props) { super(props); //cookie instance this.state = { defaultLanguage: "en", //define the default language frenchLanguage: "fr", // languages: Object.keys(LanguageList), }; this.addNotification = this.addNotification.bind(this); this.notificationDOMRef = React.createRef(); window.addNotification = this.addNotification.bind(this); } addNotification(notificationData) { this.notificationDOMRef.current.addNotification(notificationData); } render() { let lang = 'fr'; return ( <IntlProvider locale={lang} key={lang} //force a full teardown until the underlying React context issue is resolved > <div> <ReactNotification ref={this.notificationDOMRef} /> {/*Check token validity here*/} <Routes /> </div> </IntlProvider> ); } } <file_sep>/resources/js/frontend/front_office/components/Authentication/authComponent.js import React, { Component } from "react"; import { connect } from "react-redux"; import { withRouter } from "react-router-dom"; import * as Cookie from "js-cookie"; import { saveToken, saveUser, isLoggedIn } from "../../../libs/utils/auth_utils"; import { authGuardCStoreActions } from "./store"; export default function requireAuth(Acomponent) { @connect((state, props) => ({ authGuardCStore: state.authGuardCStore })) class AuthenticatedComponent extends Component{ constructor(props){ super(props); this.state = { auth: isLoggedIn() } } componentDidMount(){ this.checkAuth(); } checkAuth(){ const location = this.props.location; const redirect = location.pathname + location.search; if(!this.state.auth){ this.props.history.push(`/login?redirect=${redirect}`); } } render(){ return this.state.auth ? <Acomponent { ...this.props } /> : null; } } return withRouter(AuthenticatedComponent) }<file_sep>/webpack.mix.js const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix.react('resources/js/app.js', 'public/js') .sass('resources/sass/app.scss', 'public/css'); // mix.webpackConfig({ // entry: { // front_office: path.join(__dirname, "resources/js/app.js"), // }, // output:{ // path: path.join(__dirname, "public/js"), // filename: "[name]-[hash].js" // }, // module: { // rules: [ // { // test: /\.jsx?$/, // loader: "babel-loader", // exclude: /node_modules/ // }, // { // test: /\.css$/, // loader: ["style-loader", "css-loader"], // }, // { // test: /\.(scss|sass)$/, // use: [ // { // loader: "style-loader" // }, // { // loader: "css-loader", // options: { // importLoaders: 1, // modules: true, // sourceMap: process.env.NODE_ENV !== "production", // // localIdentName: "[path]___[name]__[local]___[hash:base64:5]" // localIdentName: "[local]___[hash:base64:5]" // } // }, // { // loader: "sass-loader", // options: { // sourceMap: process.env.NODE_ENV !== "production" // } // } // ] // }, // { // test: /\.(png|jpg|gif|svg)$/i, // use: [ // { // loader: "url-loader", // options: { // limit: 8192 // } // } // ] // } // ], // }, // }); <file_sep>/README.md ## FGI ECosystem Application de d'archivage FGI réalisé avec : - [Laravel 6](https://laravel.com/docs). - [Node Js 12.14](https://nodejs.org/en/). - [ReactJs](https://fr.reactjs.org/). ### Prérequis Le travail sur ce projet nécéssite des connaissances de base en developement - HTML, CSS, JS, Bootstraps - PHP - SQL ou ORM - Connaissance de git et CLI git ### Installation Le système nécécite l'installation d'un ensembles de programes et librairies parmis les quelles on aura : PHP v7.3... Laravel 6, Node Js, un SGBD de son choix peut importe (MySQL, Postgres, Maria DB...). Aussi Git pour le versionning et la collaboration sur le projet. ### PHP et SGBD En général, PHP, Maria DB ou MySQL vienent avec WAMP serveur ou XAMP serveur, donc faudrait juste mettre PHP en variable d'environement. ### Laravel 6 Laravel est un Framework PHP qui a besoin de PHP, PHP 7.3.. pour la version 6 que nous allons utiliser dans notre projet. Mais aussi de [Composer](https://getcomposer.org/). Composer est un gestionnaire de dépendance ou de librairies PHP, donc nécéssite l'installation préalable de PHP et l'ajout de ce programme en variable d'environement pour fonctionner. Une fois composer installer vous pouvez passer à la récupération du code source du projet dans le repertoire. ## Mise en place du projet 1. Cloner le projet git clone https://github.com/stephcyrille/fgi-ecosystem.git 2. Téléchargement des dépendances php composer install 3. Téléchargement des dépendances Javascript npm install 4. Lancement de Laravel (BACKEND) php artisant migrate php artisan passport:install php artisan serve 4. Lancement de React (FRONTEND) npm run dev ### Remarque: **Créer votre base de donnée, car les migrations correspondent à la création des tables de la base de données, action qui ne saurait s'exécuter seulement lorsqu'une base de données est présente** Avant de lancer toutes les commandes, ouvrez le fichier .env et configurez le comme suit: <br /> DB_CONNECTION=pgsql // Correspont à mon connecteur de base de données (Dans mon cas c'est Postgres, ceux qui ont MySQL ce sera mysql)<br /> DB_PORT=5432 // Correspond au port du SGBD (Dans mon cas c'est celui de Postgres pour MySql c'est 3306 pour Maria DB c'est 3307)<br /> DB_DATABASE=fgidb // Nom de la Base de données<br /> DB_USERNAME=fgidb // Nom de l'utilisateur de la base de données<br /> DB_PASSWORD=<PASSWORD> // Mot de passe de l'utilisateur de la Base de données <br /> <file_sep>/resources/js/frontend/front_office/components/Authentication/Login/validator.js export const validate = values => { const errors = {}; if (!values.email) { errors.email = "Ce champ est requis"; } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = "Email invalide"; } if (!values.password) { errors.password = "Ce champ est requis"; } else if (values.password.length < 5) { errors.password = "<PASSWORD> pour le mot de passe"; } return errors; }; <file_sep>/resources/js/frontend/front_office/components/Authentication/Login/index.js import React from "react"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { push } from "react-router-redux"; // import url from "../../../front_office/routes/url"; import renderHTML from 'react-render-html'; import { Form, FormGroup } from "reactstrap"; import { reduxForm, Field, propTypes as reduxFormPropTypes } from "redux-form"; import { Steps, Button, message, Spin, Icon, Checkbox } from 'antd'; import { loginCStoreActions } from './store'; import './style.local.scss'; import { saveToken, saveUser } from '../../../../libs/utils/auth_utils'; import config from "../../../../config" const { Step } = Steps; const steps = [ { title: 'Pseudo', }, { title: 'Mot de passe', }, ]; const antIcon = <Icon type="loading" style={{ fontSize: 18, color: "green" }} spin /> // Validation statement const required = value => (value || typeof value === 'number' ? undefined : 'Ce champ est requis'); export const minLength = min => value => value && value.length < min ? `Minimun ${min} caractères requis ou plus` : undefined export const minLength2 = minLength(2) export const minLength6 = minLength(6) const email = value => value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) ? 'Email invalide' : undefined export const passwordMatch = (value, allValues) => value !== allValues.register_password ? 'Les deux mot de passe doivent être identique' : undefined; const renderField = ({ input, placeholder, type, meta: { touched, error, warning } }) => ( <div> <input {...input} placeholder={placeholder} type={type} className="form-control" /> {touched && ( (error && <span style={{ paddingLeft: "0", paddingRight: "1em", color: "red", fontSize: "0.8em", fontStyle: "italic", fontWeight: "bold", display: "block", paddingTop: "8px", textAlign: "left" }} > { error } </span> ) )} </div> ); export default @connect((state, props) => ({ loginCStore: state.loginCStore, })) @reduxForm({ form: "login", enableReinitialize: true }) class Login extends React.Component { componentWillMount(){ const title = `Login | ${config.name}` document.title = title } setRegisterForm(){ this.props.dispatch(loginCStoreActions.setRegisterForm()); // Réinitialise step of form this.props.dispatch(loginCStoreActions.setCurrentValue(0)); // Réinitialize user user values this.props.dispatch(loginCStoreActions.setUserValue(null)); } setLoginForm(){ this.props.dispatch(loginCStoreActions.setLoginForm()); this.props.dispatch(loginCStoreActions.setUnknwoUserMessage(null)); } next(formValues) { const loading = true this.props.dispatch(loginCStoreActions.setBtnLoading(loading)); const email = formValues.email this.props.dispatch(loginCStoreActions.setEmail(email)); // We will use axios there to fetch if user exits window.axios .post("/api/profiles/check/email", { email : email }) .then(response => { console.log('response >> ', response); const loading = false this.props.dispatch(loginCStoreActions.setBtnLoading(loading)); const checked = true this.props.dispatch(loginCStoreActions.setChecked(checked)); const current = this.props.loginCStore.current + 1; this.props.dispatch(loginCStoreActions.setCurrentValue(current)); const user = response.data.data this.props.dispatch(loginCStoreActions.setUserValue(user)); }) .catch(error => { const loading = false this.props.dispatch(loginCStoreActions.setBtnLoading(loading)); const message = error.response.data.message this.props.dispatch(loginCStoreActions.setUnknwoUserMessage(message)); }); } prev() { const current = this.props.loginCStore.current - 1; this.props.dispatch(loginCStoreActions.setCurrentValue(current)); // Réinitialize user user values this.props.dispatch(loginCStoreActions.setUserValue(null)); this.props.dispatch(loginCStoreActions.setUnknwoUserMessage(null)); } _handleLogin(formValues){ const loading = true this.props.dispatch(loginCStoreActions.setLoading(loading)); const { email } = this.props.loginCStore const password = form<PASSWORD> const credentials = { email: email, password: <PASSWORD>, }; window.axios .post("/api/auth/login", credentials) .then(response => { this.props.dispatch(loginCStoreActions.setUnknwoUserMessage(null)); console.log('response >> ', response); const loading = false this.props.dispatch(loginCStoreActions.setLoading(loading)); let data = response.data.data // Save loggedIn user on localStorage saveUser(JSON.stringify(data.userprofile)); // Save token on localStorage saveToken(data.token) let param = new URLSearchParams(this.props.location.search); console.log("param ", param.get('redirect')) if(!param.get('redirect')){ window.location.href = "/"; } else { window.location.href = param.get('redirect'); } }) .catch(error => { const loading = false this.props.dispatch(loginCStoreActions.setLoading(loading)); const message = error.response.data.message this.props.dispatch(loginCStoreActions.setUnknwoUserMessage(message)); }); } _handleRegister(formValues){ console.log('FormValues register >>>', formValues); const loading = true this.props.dispatch(loginCStoreActions.setBtnLoading(loading)); const data = { name: formValues.register_email, email: formValues.register_email, first_name: formValues.first_name, last_name: formValues.last_name, password: <PASSWORD>_password, password_confirmation: formValues.<PASSWORD>_confirmation, birthdate: formValues.birthdate } window.axios .post("/api/auth/register", data) .then(response => { this.props.dispatch(loginCStoreActions.setUnknwoUserMessage(null)); console.log('response >> ', response); const loading = false this.props.dispatch(loginCStoreActions.setBtnLoading(loading)); window.location.href = "/login"; /* if(this.props.location.search){ window.location.href = "/"; } else { let param = new URLSearchParams(this.props.location.search); window.location.href = param.get('redirect'); } */ }) .catch(error => { const loading = false this.props.dispatch(loginCStoreActions.setBtnLoading(loading)); /* const message = error.response.data.message this.props.dispatch(loginCStoreActions.setUnknwoUserMessage(message)); */ }); } _handleEmailChange(val){ this.props.dispatch(loginCStoreActions.setUnknwoUserMessage(null)); } onCheckChange(e){ this.props.dispatch(loginCStoreActions.setCheckBox(e.target.checked)); } render() { const { current, loading, checked, user, login, register, unknowMessage, btnLoading, boxChecked, submitting, pristine } = this.props.loginCStore; return ( <div className="background"> { btnLoading && <div className="cover-spiner"> <div className="whirly-loader" style={{ position: "absolute", left: "48%", top: "40%" }}></div> </div>} <div className="container"> <div className="offset-3 col-md-6"> <div className="btn-content" style={{ padding: "50px 0px 0px 0px" }}> <Button className={ login ? "btn btn-outline-light btn-md connect active" : "btn btn-outline-light btn-md connect"} onClick={() => this.setLoginForm()} > Se connecter </Button> <Button className={ register ? "btn btn-outline-light btn-md connect active" : "btn btn-outline-light btn-md connect" } style={{ paddingLeft: "35px", paddingRight: "35px" }} onClick={() => this.setRegisterForm()} > S'inscrire </Button> </div> </div> <div className="row" style={{ paddingTop: "30px" }}> { login == true && <div id="block1" className="offset-3 col-md-6"> <div id="blockLogin"> <h3 className="text-center connectTitle">Se connecter</h3> <div className="logoFgi"> <img src="/images/fgi.jpg" className="img-fluid" /> </div> <div className="steps-content"> <Form> {/* <label htmlFor="email">Email</label><br /> */} <br /> <Field className="form-control" component={renderField} type="email" label="Entrer votre email" name="email" autoFocus validate={[required, email]} onChange = {e => this._handleEmailChange(e)} placeholder={"Email"} /> {/* <label htmlFor="password">Mot de passe</label><br /> */} <br /> <Field className="form-control" component={renderField} type="password" name="password" label="Votre mot de passe" autoFocus placeholder={"Mot de passe"} validate={[required, minLength6]} /> <p style={{ marginTop: "10px", textAlign: "left" }}> <Checkbox checked={ boxChecked } onChange={ e => this.onCheckChange(e) } > Se souvenir de moi </Checkbox> </p> <br /> <div className="steps-action"> <Button type="primary" disabled={ this.props.submitting || this.props.pristine } onClick = {this.props.handleSubmit(this.next.bind(this))} > Suivant &nbsp; { btnLoading && <Spin indicator={antIcon} /> } </Button> </div> </Form> </div> </div> </div> } { register == true && <div id="block1" className="offset-2 col-md-8"> <div id="blockRegister" className=""> <h3 className="text-center connectTitle">S'inscrire</h3> <div className="registerFormWrapper"> <Form className="row"> <FormGroup className="col-md-4"> <label htmlFor="first_name">Nom</label> <Field className="form-control" component={renderField} type="text" name="first_name" autoFocus validate={[required, minLength2]} placeholder={"Nom de famille"} /> </FormGroup> <FormGroup className="col-md-4"> <label htmlFor="last_name">Prénom</label> <Field className="form-control" component={renderField} type="text" name="last_name" validate={[required, minLength2]} placeholder={"Prénom (s)"} /> </FormGroup> <FormGroup className="col-md-4"> <label htmlFor="last_name">Matricule</label> <Field className="form-control" component={renderField} type="text" name="matricule" validate={[required, minLength2]} placeholder={"20GXXXXX"} /> </FormGroup> <FormGroup className="col-md-4"> <label htmlFor="email">Email</label> <Field className="form-control" component={renderField} type="email" name="register_email" validate={[required, email]} placeholder={"<EMAIL>"} /> </FormGroup> <FormGroup className="col-md-4"> <label htmlFor="register_password">Mot de passe</label> <Field className="form-control" component={renderField} type="password" name="register_password" validate={[required, minLength6]} placeholder={"Mot de passe"} /> </FormGroup> <FormGroup className="col-md-4"> <label htmlFor="password_confirmation">Confirmation mot de passe</label> <Field className="form-control" component={renderField} type="password" name="password_confirmation" validate={[required, passwordMatch]} placeholder={"Ressaisissez le mot de passe"} /> </FormGroup> <FormGroup className="col-md-4"> <label htmlFor="birthdate">Date de naissance</label> <Field className="form-control" component={renderField} type="date" name="birthdate" validate={[required]} /> </FormGroup> </Form> <div className="row"> <div id="block1" className="offset-2 col-md-8" style={{ paddingTop: "20px" }}> <Button type="primary" disabled={ this.props.submitting || this.props.pristine } onClick = {this.props.handleSubmit(this._handleRegister.bind(this))} > Valider </Button> </div> </div> </div> </div> </div> } <div className="col-sm-6"> </div> </div> </div> </div> ) } }<file_sep>/app/Http/Controllers/API/ProfileController.php <?php namespace App\Http\Controllers\Api; use App\Http\Controllers\API\BaseController as BaseController; use Illuminate\Http\Request; use Validator; use App\Models\Profile; class ProfileController extends BaseController { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $profiles = Profile::all(); $nber = Profile::all()->count(); if($nber == 1) { $message = $nber.' utilisateur trouvé.'; } else { $message = $nber.' utilisateurs trouvé.'; } return $this->sendResponse($profiles, $message); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Check the specified resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function check(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email', ]); if($validator->fails()){ return $this->sendError('Erreur de validation.', $validator->errors()); } $email = $request->get('email'); $profile = Profile::where('email', $email)->get(); // test if profile is really found if($profile->first()===null) { // Return a Json response null $message = 'L\'email ne correspond à aucun utilisateur.'; return $this->sendError($message); } else { // Return Json response with userprofile // Only expose on request body email, username and picture path $message = 'Utilisateur trouvé.'; return $this->sendResponse($profile->first(), $message); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/resources/js/frontend/front_office/components/Authentication/Login/store.js import { createAction, createReducer } from "redux-act"; const initialState = { current: 0, loading: false, btnLoading: false, // Email grabbbed on first steph of login form email: null, // This change after email is reconize by the system checked: false, user: null, login: true, register: false, // Message for unknow user unknowMessage: null, boxChecked: false, }; const actions = { name: "loginCStoreActions" }; const store = createReducer({}, initialState); // stores are called reducers // Initializing state actions.initialState = createAction("LOGIN__INIT") store.on(actions.initialState, (state) => ( { ...state, ...initialState }) ) // set current value actions.setCurrentValue = createAction("LOGIN__SET_CURRENT_VALUE") store.on(actions.setCurrentValue, (state, value) => ( { ...state, current: value }) ) // set loading actions.setLoading = createAction("LOGIN__SET_LOADING") store.on(actions.setLoading, (state, value) => ( { ...state, loading: value }) ) actions.setBtnLoading = createAction("LOGIN__SET_BTN_LOADING") store.on(actions.setBtnLoading, (state, value) => ( { ...state, btnLoading: value }) ) // set checked actions.setChecked = createAction("LOGIN__SET_CHECKED") store.on(actions.setChecked, (state, value) => ( { ...state, checked: value }) ) // set user value actions.setUserValue = createAction("LOGIN__SET_USER_VALUE") store.on(actions.setUserValue, (state, value) => ( { ...state, user: value }) ) // set register form actions.setRegisterForm = createAction("LOGIN__SET_REGISTER_FORM") store.on(actions.setRegisterForm, (state) => ( { ...state, login: false, register: true }) ) // set login form actions.setLoginForm = createAction("LOGIN__SET_LOGIN_FORM") store.on(actions.setLoginForm, (state) => ( { ...state, login: true, register: false }) ) // set email value actions.setEmail = createAction("LOGIN__SET_EMAIL") store.on(actions.setEmail, (state, value) => ( { ...state, email: value }) ) // set email value actions.setUnknwoUserMessage = createAction("LOGIN__SET_UNKNOW_USER_MESSAGE") store.on(actions.setUnknwoUserMessage, (state, value) => ( { ...state, unknowMessage: value }) ) // set checked of checkbox actions.setCheckBox = createAction("LOGIN__SET_BTN_CHECKED") store.on(actions.setCheckBox, (state, value) => ( { ...state, boxChecked: value }) ) export { store as loginCStore, actions as loginCStoreActions }; <file_sep>/resources/js/frontend/libs/utils/auth_utils.js const axios = require("axios"); export const saveToken = token => { localStorage.setItem("appToken", token); }; export const getToken = () => { return localStorage.getItem("appToken"); }; export const clearToken = () => { return localStorage.removeItem("appToken"); }; // LOCALSTORAGE FOR MANAGE USER export const saveUser = user => { localStorage.setItem("user", user); }; export const clearUser = () => { return localStorage.removeItem("user"); }; export const getUser = () => { let user = JSON.parse(localStorage.getItem("user")); return user; }; export const initAxios = () => { if (localStorage.hasOwnProperty("appToken")) { window.axios = axios.create({ baseURL: window.location.origin, // timeout: 1000, headers: { "Content-Type": "application/json", Authorization: "Token " + localStorage.getItem("appToken") } }); window.file_axios = axios.create({ baseURL: window.location.origin, // timeout: 1000, headers: { "Content-Type": "multipart/form-data", Authorization: "Token " + localStorage.getItem("appToken") } }); } else { window.axios = axios.create({ baseURL: window.location.origin, headers: { "Content-Type": "application/json" } }); window.file_axios = axios.create({ baseURL: window.location.origin, headers: { "Content-Type": "multipart/form-data" } }); } }; export const isLoggedIn = () => { // We will first check token validity if(getToken()){ return true } else { return false } }
26eba345c99f008a5f4fb35cbf21c9277054eed8
[ "JavaScript", "Markdown", "PHP" ]
17
JavaScript
stephcyrille/fgi-ecosystem
0d5bc40791f3f6bcf5354db9407b56d795bda20d
bb72bac81f93dc06e2b8414f2f48b79fe644c91e
refs/heads/master
<repo_name>jenipharachel/FreeCodeCamp-JavaScript-Course-Challenges<file_sep>/primeSum.js function sumPrimes(num) { var sum =0; for(var i=1; i<=num; i++) { if(isPrime(i) === true) { sum += i; } } function isPrime(val) { //I googled how to check if a number is prime or not if(val <= 1) return false; if(val % 2 == 0 && val > 2) return false; let s=Math.sqrt(val); for(var i=3; i<=s; i++) { if(val % i === 0) return false; } return true; } console.log(sum); return sum; } sumPrimes(10); <file_sep>/romanNumConverter.js function convertToRoman(num) { //num is 3693 var roman = []; var quo = 0; for(var i=0; num > 0; i++) { if(num >= 1 && num < 10) { quo = parseInt(num/1); //3 num = 0; if(quo >= 5) { var diff = quo - 5; if(diff <= 3) { roman.push("V"); for(let k=0; k<diff; k++) { roman.push("I"); } } else { roman.push("IX"); } } else if(quo < 5) { if(quo < 4) { for(let k=0; k<quo; k++) { roman.push("I"); } } else { roman.push("IV"); } } } else if(num >= 10 && num < 100) { quo = parseInt(num/10); //9 console.log(quo) num = num % 10; //3 if(quo >= 5) { var diff = quo - 5; if(diff <= 3) { roman.push("L"); for(let k=0; k<diff; k++) { roman.push("X"); } } else { roman.push("XC"); } } else if(quo < 5) { if(quo < 4) { for(let k=0; k<quo; k++) { roman.push("X"); } } else { roman.push("XL"); } } } else if(num >= 100 && num < 1000) { quo = parseInt(num/100); //6 num = num % 100; //93 if(quo >= 5) { var diff = quo - 5; if(diff <= 3) { roman.push("D"); for(let k=0; k<diff; k++) { roman.push("C"); } } else { roman.push("CM"); } } else if(quo < 5) { if(quo < 4) { for(let k=0; k<quo; k++) { roman.push("C"); } } else { roman.push("CD"); } } } else if(num >= 1000 && num < 5000) { quo = parseInt(num/1000); //quo is 3 num = num % 1000; //rem is 693 for(let j=0; j<quo; j++) { roman.push("M");} } } var res = roman.join(""); console.log(res); return res; } convertToRoman(12); <file_sep>/steamroller.js function steamrollArray(arr) { // I'm a steamroller, baby var newArr = arr.flat(3); return newArr; } steamrollArray([1, [2], [3, [[4]]]]); <file_sep>/numSum.js function sumAll(arr) { var sum = 0; if(arr[0] < arr[1]) { for(var i=arr[0]; i<=arr[1]; i++) { sum = sum + i; } } if(arr[0] > arr[1]) { for(var i=arr[1]; i<=arr[0]; i++) { sum = sum + i; } } return sum; } sumAll([1, 4]); <file_sep>/argumentsOptional.js function addTogether(arg1,arg2) { if(typeof arg1 == "number" && arg2 == null) return function(arg2){ if(typeof arg1 == "number" && typeof arg2 == "number") return arg1+arg2; else return undefined; } else { if(typeof arg1 == "number" && typeof arg2 == "number") return arg1+arg2; else return undefined; } } addTogether(2,3); <file_sep>/spinalTapCase.js function spinalCase(str) { var regExp = /(?=[A-Z])|\s|_|-/ var words = str.split(regExp); var res = words.join("-"); var resStr = res.toLowerCase(); return resStr; } spinalCase('This Is Spinal Tap'); <file_sep>/missingLetters.js function fearNotLetter(str) { var arr = str.split(""); var alphabet = Array.from(Array(26), (e, i) => String.fromCharCode(i + 97)); var testArr = alphabet.slice(alphabet.indexOf(arr[0]),alphabet.indexOf(arr.length - 1)); for(var i=0; i<testArr.length; i++) { if(testArr[i] != arr[i]) { return testArr[i]; } } } fearNotLetter("stvwx"); <file_sep>/pigLatin.js function translatePigLatin(str) { if(str[0].match(/[aeiou]/)) { strRes = str + "way"; } else if(str.search(/[aeiou]/) > 0){ var pos = str.search(/[aeiou]/); var strRes = str.slice(pos); for(var i=0; i<pos; i++) { strRes = strRes + str[i]; } strRes = strRes + "ay"; } else { strRes = str + "ay"; } return strRes; } translatePigLatin("consonant"); <file_sep>/oddFiboNumSum.js function sumFibs(num) { var a = 0; var b = 1; var temp = 0; var arr = []; for(var i=1; b <= num; ++i) { if(b%2 != 0) arr.push(b); temp = a+b; a=b; b=temp; } var sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue) return sum; } sumFibs(4); <file_sep>/README.md # FreeCodeCamp-JavaScript-Course-Challenges In this repository, you can find the code I developed for completing the Algorithm scripting challenges in the JS course provided by FreeCodeCamp <file_sep>/htmlEntityConversion.js function convertHTML(str) { var words = str.split(""); for(var i=0; i<words.length; i++) { switch(words[i]) { case '&': words[i] = "&amp;"; break; case '<': words[i] = "&lt;"; break; case '>': words[i] = "&gt;"; break; case '"': words[i] = "&quot;"; break; case "'": words[i] = "&apos;"; break; } } var newStr = words.join(""); return newStr; } convertHTML("Dolce & Gabbana"); <file_sep>/mapTheDebris.js function orbitalPeriod(arr) { var GM = 398600.4418; var earthRadius = 6367.4447; function findOrbPeriod(avgAlt) { var orbPeriod = Math.round(2*Math.PI*Math.sqrt(Math.pow((earthRadius+avgAlt),3)/GM)); return orbPeriod; } var newArr = []; newArr = arr.map(function(item) { //obj["orbitalPeriod"] = 2*Math.PI*Math.sqrt(Math.pow((earthRadius+obj["avgAlt"]),3)/GM); return {"name": item["name"], "orbitalPeriod": findOrbPeriod(item.avgAlt)}; }); return newArr; } orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]); <file_sep>/searchAndReplace.js function myReplace(str, before, after) { var words = str.split(" "); if(before[0] == before[0].toUpperCase()) { after = after[0].toUpperCase() + after.slice(1); } for(var i=0; i<words.length; i++) { if(words[i] == before) { words[i] = after; } } str = words.join(" "); return str; } myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); <file_sep>/makeAPerson.js var Person = function(firstAndLast) { var word = firstAndLast.split(" "); var firstName = word[0]; var lastName = word[1]; var firstAndLastName = firstName.concat(" ",lastName); this.getFullName = function() { return firstName.concat(" ",lastName); }; this.setFullName = function(firstAndLast) { word = firstAndLast.split(" "); firstName = word[0]; lastName = word[1]; firstAndLastName = firstName.concat(" ",lastName); }; this.getFirstName = function() { return firstName; }; this.setFirstName = function(first) { firstName = first; }; this.getLastName = function() { return lastName; }; this.setLastName = function(last) { lastName = last; }; }; var bob = new Person('<NAME>'); bob.getFullName();
38e4128b885529f922e810bc84d2d0367463a06c
[ "JavaScript", "Markdown" ]
14
JavaScript
jenipharachel/FreeCodeCamp-JavaScript-Course-Challenges
d0c9bc3edc7edca85b3155a755a1ee973e3d350d
de20ce8836cec67c51f2bc8a428e4bfebcdb5fde
refs/heads/main
<repo_name>Blueberryy/SoundCloud-Player<file_sep>/lua/scplayer/cl_player.lua function scb.play_track (info, tag) if !istable(info) then scb.showerror ("#scp_something_went_wrong_no_track_data_try_again") return end local key = "" if tag == "cl" then key = scb.primary_key else key = scb.reserve_key end sound.PlayURL ("http://api.soundcloud.com/tracks/"..info.id .."/stream?client_id="..key, "", function (stream, id, str) if tag == "cl" then if IsValid(scb.sv_stream) then scb.sv_stream:SetVolume(0) end if IsValid(scb.cl_stream) then scb.cl_stream:Stop() end scb.cl_stream = stream if IsValid (scb.cl_stream) then scb.cl_stream:SetVolume (scb.settings.volume/100) end scb.queue_refresh () if scb.settings.plrsize == "default" then scb.player_def (info, scb.cl_stream, tag) else scb.player_lit (info, scb.cl_stream, tag) end scb.finished = false else if IsValid(scb.cl_stream) then scb.cl_stream:Pause() if timer.Exists("scb_queue") then timer.Pause("scb_queue") end end if IsValid(scb.sv_stream) then scb.sv_stream:Stop() end scb.sv_stream = stream if scb.settings.plrsize == "default" then scb.player_def (info, scb.sv_stream, tag) else scb.player_lit (info, scb.sv_stream, tag) end scb.finished = false if IsValid (scb.sv_stream) then scb.sv_stream:SetVolume (scb.settings.volume/100) end end end) end function scb.switch_stream (info, tag) if IsValid (scb.sv_stream) and IsValid (scb.cl_stream) then if tag == "sv" then scb.cl_stream:Pause() if timer.Exists("scb_queue") then timer.Pause("scb_queue") end scb.sv_stream:SetVolume(scb.settings.volume/100) if scb.settings.plrsize == "default" then scb.player_def (info, scb.sv_stream, tag) else scb.player_lit (info, scb.sv_stream, tag) end scb.tag = tag else scb.sv_stream:SetVolume(0) if timer.Exists("scb_queue") then timer.UnPause("scb_queue") end scb.cl_stream:SetVolume(scb.settings.volume/100) scb.cl_stream:Play() if scb.settings.plrsize == "default" then scb.player_def (info, scb.cl_stream, tag) else scb.player_lit (info, scb.cl_stream, tag) end scb.tag = tag end end end function scb.player_switch (tag) if IsValid(PlayerSwitch) and PlayerSwitch:IsVisible() then PlayerSwitch:Remove() end if IsValid (PlayerFrame) then if IsValid (scb.sv_stream) and scb.sv_stream:GetState() == 1 and IsValid (scb.cl_stream) and istable (scb.queue[1]) then PlayerSwitch = vgui.Create ("DButton", PlayerFrame) PlayerSwitch:SetPos (60, 0) PlayerSwitch:SetSize (30,30) PlayerSwitch:SetText ("") PlayerSwitch.Paint = function (self, w, h) if PlayerSwitch:IsHovered() then surface.SetDrawColor (CLightGray) surface.DrawOutlinedRect (2, 2, 26, 26) end draw.RoundedBox (0,10,10,10,3,CWhite) draw.RoundedBox (0,10,17,10,3,CWhite) draw.NoTexture() surface.SetDrawColor (CWhite) surface.DrawPoly ({ {x = 5, y = 13} , {x = 10, y = 7} , {x = 10, y = 13} }) surface.DrawPoly ({ {x = 20, y = 17} , {x = 25, y = 17} , {x = 20, y = 23} }) end PlayerSwitch.DoClick = function () if tag == "sv" then scb.switch_stream (scb.queue[1], "cl") else scb.switch_stream (scb.sv_queue[1], "sv") end end end end end function scb.player_def (info, stream, tag) if IsValid (PlayerFrame) then PlayerFrame:Remove () end scb.tag = tag timer.Stop ("CurTrackTime") PlayerFrame = vgui.Create( "DFrame" ) PlayerFrame:SetSize ( 300, 330 ) PlayerFrame:SetPos (scb.pos[1], scb.pos[2]) PlayerFrame:SetTitle ("") PlayerFrame:SetVisible (true) PlayerFrame:ShowCloseButton (false) PlayerFrame:SetDraggable (true) PlayerFrame:ParentToHUD () PlayerFrame.Paint = function (self,w,h) if !GetConVar("cl_drawhud"):GetBool() or (IsValid (LocalPlayer():GetActiveWeapon()) and LocalPlayer():GetActiveWeapon():GetClass() == "gmod_camera") then self:SetAlpha (0) else self:SetAlpha (255) end draw.RoundedBox (0,0,0,w,30,CDarkGray) end PlayerFrame.OnCursorExited = function () scb.pos[1] = select(1, PlayerFrame:GetPos()) scb.pos[2] = select(2, PlayerFrame:GetPos()) end PlayerClose = vgui.Create ("DButton", PlayerFrame) PlayerClose:SetPos (270, 0) PlayerClose:SetSize (30,30) PlayerClose:SetText ("r") PlayerClose:SetFont ("Marlett") PlayerClose:SetColor (CWhite) PlayerClose.DoClick = function () PlayerFrame:Remove() if IsValid(scb.cl_stream) then scb.cl_stream:Stop() end if IsValid(scb.sv_stream) then scb.sv_stream:SetVolume(0) end if timer.Exists ("CurTrackTime") then timer.Stop ("CurTrackTime") end if timer.Exists ("scb_queue") then timer.Stop ("scb_queue") end end PlayerClose.Paint = function (self, w, h) if PlayerClose:IsHovered() then surface.SetDrawColor (CLightGray) surface.DrawOutlinedRect (2, 2, 26, 26) end draw.RoundedBox (0,0,0,w,h,CNil) end PlayerClose.Think = function () if IsValid(stream) and stream:GetState() != 1 then if !scb.finished then stream:Play() else if tag == "cl" and !istable(scb.queue[2]) and IsValid(scb.sv_stream) and scb.sv_stream:GetState() == 1 then scb.switch_stream (scb.sv_queue[1], "sv") elseif tag == "sv" and IsValid(scb.cl_stream) and istable(scb.queue[1]) and !istable(scb.sv_queue[2]) then scb.switch_stream (scb.queue[1], "cl") else print( "wtf" ) PlayerFrame:Remove() end end end end scb.player_switch (tag) PlayerTag = vgui.Create ("DLabel", PlayerFrame) PlayerTag:SetPos (10,0) PlayerTag:SetSize (50,30) PlayerTag:SetFont ("SCRoboto18") PlayerTag:SetColor (CWhite) if tag == "cl" then PlayerTag:SetText ("#scp_tag_local") else PlayerTag:SetText ("#scp_tag_server") end http.Fetch (info.artwork_url, function ( body, len, headers, code ) if string.match (body, "cannot find original") then if info.user.avatar_url == nil then info.artwork_url_edited = defart300 else info.artwork_url_edited = string.Replace(info.user.avatar_url, "large", "t300x300") end ArtPIC:OpenURL(info.artwork_url_edited) end end) scb.player_volume (stream, plrsize) VCFrame:SetVisible (false) scb.player_visualization (stream, false) if scb.settings.visualizer == 1 then scb.player_visualization (stream, true) end PlayerVisualizer = vgui.Create ("DButton", PlayerFrame) PlayerVisualizer:SetPos (170, 0) PlayerVisualizer:SetSize (30,30) PlayerVisualizer:SetText ("") PlayerVisualizer.DoClick = function () if VisPanel:IsVisible () then scb.player_visualization (stream, false) scb.settings.visualizer = 0 scb.changesettings () else scb.player_visualization (stream, true) scb.settings.visualizer = 1 scb.changesettings () end end PlayerVisualizer.Paint = function (self, w, h) if PlayerVisualizer:IsHovered() then surface.SetDrawColor (CLightGray) surface.DrawOutlinedRect (2, 2, 26, 26) end draw.RoundedBox (0,9,13,2,9,CWhite) draw.RoundedBox (0,14,10,2,12,CWhite) draw.RoundedBox (0,19,16,2,6,CWhite) end PlayerQueue = vgui.Create ("DButton", PlayerFrame) PlayerQueue:SetPos (140, 0) PlayerQueue:SetSize (30,30) PlayerQueue:SetText ("") PlayerQueue.DoClick = function () if IsValid (QueueF) then QueueF:Remove () else scb.player_queue (tag) end end PlayerQueue.Paint = function (self, w, h) if PlayerQueue:IsHovered() then surface.SetDrawColor (CLightGray) surface.DrawOutlinedRect (2, 2, 26, 26) end draw.RoundedBox (0,6,9,2,2,CWhite) draw.RoundedBox (0,6,14,2,2,CWhite) draw.RoundedBox (0,6,19,2,2,CWhite) draw.RoundedBox (0,11,9,12,2,CWhite) draw.RoundedBox (0,11,14,12,2,CWhite) draw.RoundedBox (0,11,19,12,2,CWhite) end PlayerVolume = vgui.Create ("DButton", PlayerFrame) PlayerVolume:SetPos (210, 0) PlayerVolume:SetSize (30,30) PlayerVolume:SetText ("y") PlayerVolume:SetFont ("Marlett") PlayerVolume:SetColor (CWhite) PlayerVolume.DoClick = function () if IsValid(VCFrame) then if VCFrame:IsVisible () then VCFrame:SetVisible (false) else scb.player_volume (stream) end else scb.player_volume (stream) end end PlayerVolume.Paint = function (self, w, h) if PlayerVolume:IsHovered() then surface.SetDrawColor (CLightGray) surface.DrawOutlinedRect (2, 2, 26, 26) end draw.RoundedBox (0,0,0,w,h,CNil) end PlayerResize = vgui.Create ("DButton", PlayerFrame) PlayerResize:SetPos (240, 0) PlayerResize:SetSize (30,30) PlayerResize:SetText ("0") PlayerResize:SetFont ("Marlett") PlayerResize:SetColor (CWhite) PlayerResize.DoClick = function () scb.settings.plrsize = "little" scb.changesettings () scb.player_lit (info, stream, tag) end PlayerResize.Paint = function (self, w, h) if PlayerResize:IsHovered() then surface.SetDrawColor (CLightGray) surface.DrawOutlinedRect (2, 2, 26, 26) end draw.RoundedBox (0,0,0,w,h,CNil) end ArtPIC = vgui.Create ("HTML", PlayerFrame) ArtPIC:SetPos (0,30) ArtPIC:SetSize (320,320) if info.artwork_url == nil then if info.user.avatar_url == nil then info.artwork_url_edited = defart300 else info.artwork_url_edited = string.Replace(info.user.avatar_url, "large", "t300x300") end else info.artwork_url_edited = string.Replace(info.artwork_url, "large", "t300x300") end ArtPIC:OpenURL(info.artwork_url_edited) InvisFrame = vgui.Create( "DPanel" , PlayerFrame) InvisFrame:SetSize (300, 300 ) InvisFrame:SetPos (0,30) ArtistLBL = vgui.Create ("DLabel", InvisFrame) ArtistLBL:SetPos (17,5) ArtistLBL:SetSize (280,20) ArtistLBL:SetFont ("SCInterstate18") ArtistLBL:SetColor (CBWhite) ArtistLBL:SetText (info.user.username) local ti = {} ti.src = string.Explode (" ", info.title) ti.lbl1 = "" ti.lbl2 = "" ti.lbl3 = "" for i = 1, #ti.src do if scb.gettextlen (ti.lbl1.." "..ti.src[i], "SCInterstate24") <= 280 then ti.lbl1 = ti.lbl1.." "..ti.src[i] else for i1 = i, #ti.src do if scb.gettextlen (ti.lbl2.." "..ti.src[i1], "SCInterstate24") <= 280 then ti.lbl2 = ti.lbl2.." "..ti.src[i1] else for i2 = i1, #ti.src do ti.lbl3 = ti.lbl3.." "..ti.src[i2] end break end end break end end TrackLBL = vgui.Create ("DLabel", InvisFrame) TrackLBL:SetPos (11,35) TrackLBL:SetSize (280,72) TrackLBL:SetFont ("SCInterstate24") TrackLBL:SetColor (CBWhite) TrackLBL:SetText (ti.lbl1.."\n"..ti.lbl2.."\n"..ti.lbl3) TrackLBL:SetMouseInputEnabled (true) TrackLBL.DoClick = function () gui.OpenURL (info.permalink_url) end TrackLBL.Paint = function (self) if self:IsHovered() then self:SetColor (CLightGray) else self:SetColor (CBWhite) end end CurPosLBL = vgui.Create ("DLabel", InvisFrame) CurPosLBL:SetPos (27,250) CurPosLBL:SetSize (50,14) CurPosLBL:SetFont ("SCRoboto14") CurPosLBL:SetColor (CRed) CurPosLBL:SetText ("0:00") curlen = 0 if IsValid (stream) then curlen = math.floor (stream:GetTime ()) end timer.Create ("CurTrackTime", 1, math.floor (info.duration/1000)-curlen, function () if IsValid (stream) and IsValid(CurPosLBL) then if curlen <= math.ceil (info.duration/1000) then curlen = curlen + 1 end local curhr = math.floor (curlen/3600) local curmin = math.floor (curlen/60-curhr*60) local cursec = math.floor (curlen-curhr*3600-curmin*60) if cursec < 10 then cursec = tostring ("0"..cursec) end if curhr == 0 then CurPosLBL:SetText (curmin..":"..cursec) else if curmin < 10 then curmin = tostring ("0"..curmin) end CurPosLBL:SetText (curhr..":"..curmin..":"..cursec) end if curlen >= math.floor (info.duration/1000) then scb.finished = true else scb.finished = false end end end) MaxPosLBL = vgui.Create ("DLabel", InvisFrame) MaxPosLBL:SetPos (250,250) MaxPosLBL:SetSize (50,14) MaxPosLBL:SetFont ("SCRoboto14") MaxPosLBL:SetColor (CBWhite) MaxPosLBL:SetText ("00:00") local maxlen = (math.floor(info.duration/1000)) local maxhr = math.floor (maxlen/3600) local maxmin = math.floor (maxlen/60-maxhr*60) local maxsec = math.floor (maxlen-maxhr*3600-maxmin*60) if maxhr > 0 then MaxPosLBL:SetPos (235,250) end if maxmin > 9 then MaxPosLBL:SetPos (240,250) end if maxsec < 10 then maxsec = tostring ("0"..maxsec) end if maxhr == 0 then MaxPosLBL:SetText (maxmin..":"..maxsec) else if maxmin < 10 then maxmin = tostring ("0"..maxmin) end MaxPosLBL:SetText (maxhr..":"..maxmin..":"..maxsec) end LenBar = vgui.Create ("DPanel", InvisFrame) LenBar:SetSize (265, 3) LenBar:SetPos (17, 270) LenBar.Paint = function (self,w,h) if IsValid (stream) then draw.RoundedBox (0,0,0,w,h,CWhite) draw.RoundedBox (0,0,0,math.floor((stream:GetTime()*1000/info.duration)*265+1),h,CRed) end end InvisFrame.Paint = function (self,w,h) draw.RoundedBox (0,10,5,ArtistLBL:GetTextSize()+14,22,CVTBlack) draw.RoundedBox (0,10,33,scb.gettextlen (ti.lbl1, "SCInterstate24")+8,26,CVTBlack) if ti.lbl2 != "" then draw.RoundedBox (0,10,59,scb.gettextlen (ti.lbl2, "SCInterstate24")+8,26,CVTBlack) end if ti.lbl3 != "" then draw.RoundedBox (0,10,85,scb.gettextlen (ti.lbl3, "SCInterstate24")+8,26,CVTBlack) end draw.RoundedBox (0,22,248,CurPosLBL:GetTextSize()+10,18,CVTBlack) draw.RoundedBox (0,MaxPosLBL:GetPos()-5,248,MaxPosLBL:GetTextSize()+10,18,CVTBlack) draw.RoundedBox (0,0,240,w,40,CTBlack) end end function scb.player_lit (info, stream, tag) timer.Stop ("CurTrackTime") if IsValid (PlayerFrame) and PlayerFrame != nil then PlayerFrame:Remove () end PlayerFrame = vgui.Create( "DFrame" ) PlayerFrame:SetSize ( 400, 80 ) PlayerFrame:SetPos (scb.pos[1], scb.pos[2]) PlayerFrame:SetTitle ("") PlayerFrame:SetVisible (true) PlayerFrame:ShowCloseButton (false) PlayerFrame:ParentToHUD () PlayerFrame.OnCursorExited = function () scb.pos[1] = select(1, PlayerFrame:GetPos()) scb.pos[2] = select(2, PlayerFrame:GetPos()) end scb.player_volume (stream, plrsize) VCFrame:SetVisible (false) PlayerClose = vgui.Create ("DButton", PlayerFrame) PlayerClose:SetPos (370, 0) PlayerClose:SetSize (30,30) PlayerClose:SetText ("r") PlayerClose:SetFont ("Marlett") PlayerClose:SetColor (CWhite) PlayerClose.Paint = function (self, w, h) if PlayerClose:IsHovered() then surface.SetDrawColor (CLightGray) surface.DrawOutlinedRect (2, 2, 26, 26) end draw.RoundedBox (0,0,0,w,h,CNil) end PlayerClose.DoClick = function () PlayerFrame:SetVisible (false) if IsValid(scb.cl_stream) then scb.cl_stream:Stop() end if IsValid(scb.sv_stream) then scb.sv_stream:SetVolume(0) end if timer.Exists ("CurTrackTime") then timer.Stop ("CurTrackTime") end if timer.Exists ("scb_queue") then timer.Stop ("scb_queue") end end PlayerClose.Think = function () if IsValid(stream) and stream:GetState() != 1 then if !scb.finished then stream:Play() else if tag == "cl" and !istable(scb.queue[2]) and IsValid(scb.sv_stream) and scb.sv_stream:GetState() == 1 then scb.switch_stream (scb.sv_queue[1], "sv") elseif tag == "sv" and IsValid(scb.cl_stream) and !istable(scb.sv_queue[2]) and istable(scb.queue[1]) then scb.switch_stream (scb.sv_queue[1], "cl") else PlayerFrame:Remove() end end end end ArtPIC = vgui.Create ("HTML", PlayerFrame) ArtPIC:SetPos (2,31) ArtPIC:SetSize (70,70) if info.artwork_url == nil then if info.user.avatar_url == nil then info.artwork_url_edited = defart300 else info.artwork_url_edited = string.Replace(info.user.avatar_url, "large", "badge") end else info.artwork_url_edited = string.Replace(info.artwork_url, "large", "badge") end ArtPIC:OpenURL(info.artwork_url_edited) http.Fetch (info.artwork_url, function ( body, len, headers, code ) if string.match (body, "cannot find original") then if info.user.avatar_url == nil then info.new_artwork_url = defart100 else info.new_artwork_url = string.Replace(info.user.avatar_url, "large", "badge") end ArtPIC:OpenURL(info.new_artwork_url) end end) TrackLBL = vgui.Create ("DLabel", PlayerFrame) TrackLBL:SetPos (55,35) TrackLBL:SetSize (345,20) TrackLBL:SetFont ("SCInterstate14") TrackLBL:SetColor (CWhite) TrackLBL:SetText (info.user.username.." - "..info.title) TrackLBL:SetMouseInputEnabled (true) TrackLBL.DoClick = function () gui.OpenURL (info.permalink_url) end TrackLBL.Paint = function () if TrackLBL:IsHovered() then TrackLBL:SetColor (CLightGray) else TrackLBL:SetColor (CBWhite) end end PlayerVolume = vgui.Create ("DButton", PlayerFrame) PlayerVolume:SetPos (310, 0) PlayerVolume:SetSize (30,30) PlayerVolume:SetText ("y") PlayerVolume:SetFont ("Marlett") PlayerVolume:SetColor (CWhite) PlayerVolume.DoClick = function () if IsValid(VCFrame) then if VCFrame:IsVisible () then VCFrame:SetVisible (false) else scb.player_volume (stream, "little") end else scb.player_volume (stream, "little") end end PlayerVolume.Paint = function (self, w, h) if PlayerVolume:IsHovered() then surface.SetDrawColor (CLightGray) surface.DrawOutlinedRect (2, 2, 26, 26) end draw.RoundedBox (0,0,0,w,h,CNil) end PlayerResize = vgui.Create ("DButton", PlayerFrame) PlayerResize:SetPos (340, 0) PlayerResize:SetSize (30,30) PlayerResize:SetText ("1") PlayerResize:SetFont ("Marlett") PlayerResize:SetColor (CWhite) PlayerResize.DoClick = function () scb.settings.plrsize = "default" scb.changesettings () scb.player_def (info, stream, tag) end PlayerResize.Paint = function (self, w, h) if PlayerResize:IsHovered() then surface.SetDrawColor (CLightGray) surface.DrawOutlinedRect (2, 2, 26, 26) end draw.RoundedBox (0,0,0,w,h,CNil) end CurPosLBL = vgui.Create ("DLabel", PlayerFrame) CurPosLBL:SetPos (63,62) CurPosLBL:SetSize (50,14) CurPosLBL:SetFont ("SCRoboto14") CurPosLBL:SetColor (CRed) CurPosLBL:SetText ("0:00") MaxPosLBL = vgui.Create ("DLabel", PlayerFrame) MaxPosLBL:SetPos (365,62) MaxPosLBL:SetSize (50,14) MaxPosLBL:SetFont ("SCRoboto14") MaxPosLBL:SetColor (CBWhite) MaxPosLBL:SetText ("00:00") local maxlen = (math.floor(info.duration/1000)) local maxhr = math.floor (maxlen/3600) local maxmin = math.floor (maxlen/60-maxhr*60) local maxsec = math.floor (maxlen-maxhr*3600-maxmin*60) if maxhr > 0 then MaxPosLBL:SetPos (355,62) end if maxmin > 9 then MaxPosLBL:SetPos (360,62) end if maxsec < 10 then maxsec = tostring ("0"..maxsec) end if maxhr == 0 then MaxPosLBL:SetText (maxmin..":"..maxsec) else if maxmin < 10 then maxmin = tostring ("0"..maxmin) end MaxPosLBL:SetText (maxhr..":"..maxmin..":"..maxsec) end LenBar = vgui.Create ("DPanel", PlayerFrame) LenBar:SetSize (245, 3) LenBar:SetPos (97, 70) LenBar.Paint = function (self,w,h) if IsValid(stream) and stream:IsValid () then draw.RoundedBox (0,0,0,w,h,CWhite) draw.RoundedBox (0,0,0,math.floor((stream:GetTime()*1000/info.duration)*245+1),h,CRed) end end curlen = 0 if stream != nil and stream:IsValid () then curlen = stream:GetTime () end timer.Create ("CurTrackTime", 1, math.floor (info.duration/1000)-curlen, function () if IsValid (stream) then if curlen <= math.ceil (info.duration/1000) then curlen = curlen + 1 end local curhr = math.floor (curlen/3600) local curmin = math.floor (curlen/60-curhr*60) local cursec = math.floor (curlen-curhr*3600-curmin*60) if cursec < 10 then cursec = tostring ("0"..cursec) end if curhr == 0 then CurPosLBL:SetText (curmin..":"..cursec) else if curmin < 10 then curmin = tostring ("0"..curmin) end CurPosLBL:SetText (curhr..":"..curmin..":"..cursec) end if curlen >= math.floor (info.duration/1000 - 1) then scb.finished = true else scb.finished = false end end end) PlayerFrame.Paint = function (self,w,h) if !GetConVar("cl_drawhud"):GetBool() or (IsValid (LocalPlayer():GetActiveWeapon()) and LocalPlayer():GetActiveWeapon():GetClass() == "gmod_camera") then self:SetAlpha (0) else self:SetAlpha (255) end draw.RoundedBox (0,0,30,w,130,CWhite) draw.RoundedBox (0,0,0,w,30,CDarkGray) draw.RoundedBox (0,52,33,TrackLBL:GetTextSize()+8,24,CVTBlack) draw.RoundedBox (0,59,60,CurPosLBL:GetTextSize()+8,18,CVTBlack) draw.RoundedBox (0,MaxPosLBL:GetPos()-5,60,MaxPosLBL:GetTextSize()+10,18,CVTBlack) draw.RoundedBox (0,52,60,w-54,18,CTBlack) end end function scb.player_volume (stream, plrsize) if IsValid (VCFrame) and VCFrame != nil then VCFrame:Remove () end VCFrame = vgui.Create ("DPanel", PlayerFrame) VCFrame:SetPos (210,30) VCFrame:SetSize (30, 150) VCFrame.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CDarkGray) end VlmLine = vgui.Create ("DPanel", VCFrame) VlmLine:SetPos (13, 15) VlmLine:SetSize (4, 100) VlmLine.Paint = function (self,w,h) draw.RoundedBox (0,0,100-scb.settings.volume,w,scb.settings.volume,CRed) end VlmLBL = vgui.Create ("DLabel", VCFrame) VlmLBL:SetPos (0, 130) VlmLBL:SetSize (28,20) VlmLBL:SetContentAlignment (5) VlmLBL:SetFont ("SCRoboto14") VlmLBL:SetColor (CBWhite) VlmLBL:SetText (scb.settings.volume) VlmGrip = vgui.Create ("DButton", VCFrame) VlmGrip:SetPos (7, 7) VlmGrip:SetSize (16,116) VlmGrip:SetText ("") VlmGrip.Paint = function (self,w,h) draw.RoundedBox (8,0,100-scb.settings.volume,16,16,CLightGray) end VlmGrip.DoClick = function () scb.settings.volume = (100-select(2,VCFrame:CursorPos ())+15) scb.settings.volume = math.Round(scb.settings.volume) if scb.settings.volume < 0 then scb.settings.volume = 0 end if scb.settings.volume > 100 then scb.settings.volume = 100 end stream:SetVolume (scb.settings.volume/100) VlmLBL:SetText (scb.settings.volume) scb.changesettings () end VlmGrip.OnCursorMoved = function () if VlmGrip:IsDown () then scb.settings.volume = (100-select(2,VCFrame:CursorPos ())+15) if scb.settings.volume < 0 then scb.settings.volume = 0 end if scb.settings.volume > 100 then scb.settings.volume = 100 end stream:SetVolume (scb.settings.volume/100) VlmLBL:SetText (scb.settings.volume) scb.changesettings () end end VCFrame.Think = function () if !PlayerVolume:IsHovered() and !VCFrame:IsHovered() and !VlmLine:IsHovered() and !VlmGrip:IsHovered() then VCFrame:Remove () end end if plrsize == "little" then VCFrame:SetPos (248, 30) VCFrame:SetSize (150, 30) VCFrame.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CGray) end VlmLine:SetPos (15, 13) VlmLine:SetSize (100, 4) VlmLine.Paint = function (self,w,h) draw.RoundedBox (0,0,0,scb.settings.volume,h,CRed) end VlmLBL:SetPos (120, 5) VlmGrip:SetSize (116,16) VlmGrip.Paint = function (self,w,h) draw.RoundedBox (8,scb.settings.volume, 0, 16, 16,CLightGray) end VlmGrip.DoClick = function () scb.settings.volume = VCFrame:CursorPos ()-15 scb.settings.volume = math.Round(scb.settings.volume) if scb.settings.volume < 0 then scb.settings.volume = 0 end if scb.settings.volume > 100 then scb.settings.volume = 100 end stream:SetVolume (scb.settings.volume/100) VlmLBL:SetText (scb.settings.volume) scb.changesettings () end VlmGrip.OnCursorMoved = function () if VlmGrip:IsDown () then scb.settings.volume = VCFrame:CursorPos ()-15 if scb.settings.volume < 0 then scb.settings.volume = 0 end if scb.settings.volume > 100 then scb.settings.volume = 100 end stream:SetVolume (scb.settings.volume/100) VlmLBL:SetText (scb.settings.volume) scb.changesettings () end end end end function scb.player_visualization (stream, act) vis_rawmagnitudes = {} vis_magnitudes = {} for i = 1, 26 do vis_magnitudes[i] = 0 end vis_table = {} vis_color = CNil if act == true then if IsValid(PlayerFrame) then PlayerFrame:SizeTo (300, 430, 0.5) end if IsValid(VisPanel) then VisPanel:SetVisible ( act ) end end VisPanel = vgui.Create ("DPanel", PlayerFrame) VisPanel:SetSize ( 280, 100 ) VisPanel:SetPos (10,330) VisPanel.Paint = function (self,w,h) if IsValid(stream) then draw.RoundedBox (0,0,0,w,h,CBlack) stream:FFT (vis_rawmagnitudes, FFT_2048) if vis_rawmagnitudes[32] == nil then return end for i = 1, 26 do for ii = 1, 32 do vis_rawmagnitudes[i] = math.max (vis_rawmagnitudes[i*32], vis_rawmagnitudes[i*32+ii]) end vis_rawmagnitudes[i] = math.pow (vis_rawmagnitudes[i], 1/3)*40 if vis_rawmagnitudes[i] > vis_magnitudes[i] then vis_magnitudes [i] = vis_rawmagnitudes[i] else vis_magnitudes [i] = vis_magnitudes[i] - 0.2 end vis_table[i] = math.abs (math.Round (vis_magnitudes[i])) + 1 for i3 = 1, vis_table[i] do if i3 > 18 then vis_color = CNil elseif i3 > 14 then vis_color = CRed elseif i3 > 8 then vis_color = CYellow else vis_color = CGreen end draw.RoundedBox (0, i*10, 95-i3*5, 6, 4, vis_color) end end end end if act == false then VisPanel:SetVisible (false) if IsValid(PlayerFrame) then PlayerFrame:SizeTo (300, 330, 0.5) end end end function scb.player_queue (tag) if IsValid (QueueF) then QueueF:Remove () end QueueF = vgui.Create( "DPanel", PlayerFrame ) QueueF:SetPos (0,30) QueueF:SetSize (300, 0) QueueF:SizeTo (300, 220, 0.2) QueueF.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CDarkGray) end QTracksSP = vgui.Create ("DScrollPanel", QueueF) QTracksSP:SetPos (0,0) QTracksSP:SetSize (300, 220) scb.paintscrollbar (QTracksSP) qtrck = {} qtrckdel = {} qtrckmove = {} qtrckavatar = {} qtrcklbl = {} if tag == "cl" then qtrcks = scb.queue for i = 1, #qtrcks do if qtrcks[i] != nil then qtrck[i] = vgui.Create ("DPanel", QTracksSP) qtrck[i]:SetPos (0,i*20-20) qtrck[i]:SetSize (300,20) qtrck[i].Paint = function (self,w,h) if i == 1 then draw.RoundedBox (0,0,0,w,h,CGray) else draw.RoundedBox (0,0,0,w,h,CDarkGray) end end ilbl = vgui.Create ("DLabel", qtrck[i]) ilbl:SetSize (20,20) ilbl:SetPos (0,0) ilbl:SetContentAlignment(5) ilbl:SetFont ("SCRoboto18") ilbl:SetColor (CBWhite) ilbl:SetText (i) http.Fetch (qtrcks[i].artwork_url, function ( body, len, headers, code ) if string.match (body, "cannot find original") then if qtrcks[i].user.avatar_url == nil then qtrcks[i].new_artwork_url_temp = defart100 else qtrcks[i].new_artwork_url_temp = string.Replace(qtrcks[i].user.avatar_url, "large", "tiny") end qtrckavatar[i]:OpenURL(qtrcks[i].new_artwork_url_temp) end end) qtrckavatar[i] = vgui.Create ("HTML", qtrck[i]) qtrckavatar[i]:SetPos(21,1) qtrckavatar[i]:SetSize(25,200) if qtrcks[i].artwork_url == nil then if qtrcks[i].user.avatar_url == nil then qtrckavatar[i]:OpenURL (defart47) else qtrcks[i].artwork_url = qtrcks[i].user.avatar_url end end qtrckavatar[i]:OpenURL(string.Replace (qtrcks[i].artwork_url, "large", "tiny")) qtrcklbl[i] = vgui.Create ("DLabel", qtrck[i]) qtrcklbl[i]:SetColor (CBWhite) qtrcklbl[i]:SetSize (190,18) qtrcklbl[i]:SetFont ("SCInterstate18") qtrcklbl[i]:SetPos (50,1) qtrcklbl[i]:SetText (qtrcks[i].title) qtrckdel[i] = vgui.Create ("DButton", qtrck[i]) qtrckdel[i]:SetPos (260, 1) qtrckdel[i]:SetSize (18,18) qtrckdel[i]:SetText ("X") qtrckdel[i]:SetFont ("SCRoboto20") qtrckdel[i]:SetColor (CWhite) qtrckdel[i].Paint = function (self, w, h) end if i != 1 then qtrckdel[i].DoClick = function () table.remove (scb.queue, i) scb.player_queue ("cl") end else qtrckdel[i].DoClick = function () if istable(scb.queue[2]) then scb.play_track (scb.queue[2], "cl") table.remove (scb.queue, 1) scb.queue_refresh () else if IsValid(scb.sv_stream) and scb.sv_stream:GetState() == 1 then table.remove (scb.queue, 1) scb.switch_stream (scb.sv_queue[1], "sv") else scb.cl_stream:Stop() PlayerFrame:Remove() end end end end if i != 1 then qtrckmove[i] = vgui.Create ("DButton", qtrck[i]) qtrckmove[i]:SetPos (240, 0) qtrckmove[i]:SetSize (18,18) qtrckmove[i]:SetText ("5") qtrckmove[i]:SetFont ("Marlett") qtrckmove[i]:SetColor (CWhite) qtrckmove[i].Paint = function (self, w, h) end if i == 2 then qtrckmove[i].DoClick = function () if istable(scb.queue[2]) then scb.play_track (scb.queue[2], "cl") table.remove (scb.queue, 1) scb.queue_refresh () else scb.cl_stream:Stop() PlayerFrame:Remove() end end else qtrckmove[i].DoClick = function () table.insert (scb.queue, 2, scb.queue[i]) table.remove (scb.queue, i+1) scb.player_queue ("cl") end end end end end else qtrcks = scb.sv_queue for i = 1, #qtrcks do if qtrcks[i] != nil then qtrck[i] = vgui.Create ("DPanel", QTracksSP) qtrck[i]:SetPos (0,i*20-20) qtrck[i]:SetSize (300,20) qtrck[i].Paint = function (self,w,h) if i == 1 then draw.RoundedBox (0,0,0,w,h,CGray) else draw.RoundedBox (0,0,0,w,h,CDarkGray) end end ilbl = vgui.Create ("DLabel", qtrck[i]) ilbl:SetSize (20,20) ilbl:SetPos (0,0) ilbl:SetContentAlignment(5) ilbl:SetFont ("SCRoboto18") ilbl:SetColor (CBWhite) ilbl:SetText (i) http.Fetch (qtrcks[i].artwork_url, function ( body, len, headers, code ) if string.match (body, "cannot find original") then if qtrcks[i].user.avatar_url == nil then qtrcks[i].new_artwork_url_temp = defart100 else qtrcks[i].new_artwork_url_temp = string.Replace(qtrcks[i].user.avatar_url, "large", "tiny") end qtrckavatar[i]:OpenURL(qtrcks[i].new_artwork_url_temp) end end) qtrckavatar[i] = vgui.Create ("HTML", qtrck[i]) qtrckavatar[i]:SetPos(21,1) qtrckavatar[i]:SetSize(25,200) if qtrcks[i].artwork_url == nil then if qtrcks[i].user.avatar_url == nil then qtrckavatar[i]:OpenURL (defart47) else qtrcks[i].artwork_url = qtrcks[i].user.avatar_url end end qtrckavatar[i]:OpenURL(string.Replace (qtrcks[i].artwork_url, "large", "tiny")) qtrcklbl[i] = vgui.Create ("DLabel", qtrck[i]) qtrcklbl[i]:SetColor (CBWhite) qtrcklbl[i]:SetSize (190,18) qtrcklbl[i]:SetFont ("SCInterstate18") qtrcklbl[i]:SetPos (50,1) qtrcklbl[i]:SetText (qtrcks[i].title) if LocalPlayer():IsSuperAdmin() then qtrckdel[i] = vgui.Create ("DButton", qtrck[i]) qtrckdel[i]:SetPos (260, 0) qtrckdel[i]:SetSize (20,16) qtrckdel[i]:SetText ("x") qtrckdel[i]:SetFont ("SCRoboto20") qtrckdel[i]:SetColor (CWhite) qtrckdel[i].Paint = function (self, w, h) end qtrckdel[i].DoClick = function () net.Start ("scb_queue_remove") net.WriteTable ({i}) net.SendToServer() end if i > 2 then qtrckmove[i] = vgui.Create ("DButton", qtrck[i]) qtrckmove[i]:SetPos (240, 0) qtrckmove[i]:SetSize (18,18) qtrckmove[i]:SetText ("5") qtrckmove[i]:SetFont ("Marlett") qtrckmove[i]:SetColor (CWhite) qtrckmove[i].Paint = function (self, w, h) end qtrckmove[i].DoClick = function () net.Start ("scb_queue_move") net.WriteTable ({i}) net.SendToServer () end end end end end end end net.Receive ("scb_broadcastplay", function () info = net.ReadTable() if scb.tag == "cl" and IsValid (scb.cl_stream) and scb.cl_stream:GetState() == 1 then scb.chooser (info) sound.PlayURL ("http://api.soundcloud.com/tracks/"..info.id .."/stream?client_id="..scb.reserve_key, "", function (stream) if IsValid(scb.sv_stream) then scb.sv_stream:Stop() end scb.sv_stream = stream scb.sv_stream:SetVolume(0) end) else scb.play_track (info, "sv") end scb.player_switch (tag) end) net.Receive ("scb_send_queue", function () scb.sv_queue = net.ReadTable() if scb.settings.plrsize == "default" and IsValid(QueueF) and QueueF:IsVisible() then scb.player_queue ("sv") end end) hook.Add("OnContextMenuOpen","makesense",function () if IsValid (PlayerFrame) then PlayerFrame:MakePopup(true) end end) hook.Add("OnContextMenuClose","makenosense",function () if IsValid (PlayerFrame) then PlayerFrame:SetMouseInputEnabled(false) PlayerFrame:SetKeyboardInputEnabled(false) end end)<file_sep>/resource/localization/en/soundcloudplayer.properties scp_title=SCPlayer scp_browser_title=SoundCloud Browser scp_load=Load scp_search= Search scp_enter_something_to_search=Enter something to search! scp_you_cannot_search_a_link=You cannot search a link :/ scp_admin=Admin scp_admin_mode_deactivated=Admin mode deactivated! scp_admin_mode_activated=Admin mode activated! scp_provide_a_soundcloud_link=Provide a SoundCloud link! scp_the_link_is_not_supported=The link is not supported! scp_the_track_cant_be_streamed=The track can't be streamed! scp_this_link_type_is_not_supported=This link type is not supported! scp_the_link_or_track_is_not_supported=The link/track is not supported! scp_the_link_is_not_supported=The link is not supported! scp_category_tracks=Tracks scp_category_playlists=Playlists scp_category_users=Users scp_add_to_playlist=Add to playlist scp_play=Play scp_add_to_queue=Add to queue scp_convert_to_local_playlist=Convert to local playlist scp_playlist_was_successfully_created=Playlist was successfully created! scp_playlist_already_exists=Playlist already exists! scp_select_name_contents_from_soundcloud_player_playlists=SELECT Name, Contents FROM soundcloud_player_playlists scp_create_playlist=Create Playlist scp_you_cannot_create_playlist_with_this_name=You cannot create playlist with this name! scp_loading=Loading scp_error_reload_playlist=Error - try to reload the playlist! scp_are_you_sure=Are you sure? scp_no=No scp_yes=Yes scp_playlist_was_successfully_deleted=Playlist was successfully deleted! scp_rename_playlist=Rename Playlist scp_you_cannot_name_playlist_like_that=You cannot name playlist like that :p scp_playlist_was_successfully_renamed=Playlist was successfully renamed! scp_done=Done! scp_this_is_not_a_number=This isn't a number! scp_something_went_wrong_no_track_data_try_again=Something went wrong (no track data). Try again! scp_tag_local=Local scp_tag_server=Server<file_sep>/lua/autorun/scb_autorun.lua AddCSLuaFile () AddCSLuaFile ("scplayer/cl_misc.lua") AddCSLuaFile ("scplayer/cl_browser.lua") AddCSLuaFile ("scplayer/cl_player.lua") AddCSLuaFile ("scplayer/cl_playlists.lua") AddCSLuaFile ("scplayer/cl_queue.lua") scb = {} scb.reserve_key = ("<KEY>") -- sorry :c scb.primary_key = ("<KEY>") if SERVER then scb.queue = {} resource.AddSingleFile("resource/fonts/GLInterstate-Regular.TTF") resource.AddSingleFile("materials/scplayer/sc_logo.png") resource.AddSingleFile("materials/scplayer/scplayer_logo.png") include ("scplayer/sv_scplayer.lua") concommand.Add ("scplayer_reset", function () scb.queue = {} end) else scb.settings = {} scb.queue = {} scb.sv_queue = {} scb.tag = "cl" scb.finished = true scb.pos = {100, 30} if !file.Exists ("soundcloudplayer", "DATA") then file.CreateDir("soundcloudplayer") file.Write ("soundcloudplayer/settings.txt" , util.TableToJSON ( {admin = 0, volume = 100, visualizer = 0, plrsize = "default"} ) ) end scb.settings = util.JSONToTable ( file.Read ("soundcloudplayer/settings.txt")) include ("scplayer/cl_queue.lua") include ("scplayer/cl_misc.lua") include ("scplayer/cl_browser.lua") include ("scplayer/cl_player.lua") include ("scplayer/cl_playlists.lua") list.Set("DesktopWindows", "scplayer", { title="#scp_title", icon="scplayer/scplayer_logo.png", onewindow= true, init=function(icon, window) window:Remove() RunConsoleCommand("scplayer") end }) concommand.Add ("scplayer_reset", function () scb.queue = {} scb.sv_queue = {} scb.cl_stream = nil scb.sv_stream = nil end) end<file_sep>/lua/scplayer/cl_browser.lua if game.SinglePlayer() then scb.settings.admin = 0 end function scb.openframe () if !LocalPlayer():IsSuperAdmin() and scb.settings.admin == 1 then scb.settings.admin = 0 end if IsValid (BrowserFrame) and BrowserFrame != nil then return end if IsValid (PlayerFrame) and PlayerFrame != nil then PlayerFrame:MakePopup () end BrowserFrame = vgui.Create ("DFrame") BrowserFrame:SetSize(500,400) BrowserFrame:Center() BrowserFrame:SetTitle("#scp_browser_title") BrowserFrame:SetVisible(true) BrowserFrame:SetDraggable (false) BrowserFrame:ShowCloseButton (false) BrowserFrame:MakePopup() BrowserFrame:ParentToHUD () BrowserFrame.Paint = function (self,w,h) draw.RoundedBox (0,0,0,500,24,CDarkGray) draw.RoundedBox (0,0,60,500,140,CLightGray) draw.RoundedBox (0,0,24,500,36,CWhite) draw.RoundedBox (0,0,60,500,h-60,CNil) draw.RoundedBox (0,499,0,1,h,CBlack) surface.SetDrawColor(CBlack) surface.DrawOutlinedRect( 0, 0, w, h) surface.SetDrawColor(CDarkGray) surface.DrawOutlinedRect( 89, 30, 341, 24) end CloseButton = vgui.Create ("DButton", BrowserFrame) CloseButton:SetPos (476, 0) CloseButton:SetSize (20,24) CloseButton:SetText ("r") CloseButton:SetFont ("Marlett") CloseButton:SetColor (CWhite) CloseButton.DoClick = function () BrowserFrame:Remove () if IsValid (PlayerFrame) then PlayerFrame:SetMouseInputEnabled(false) PlayerFrame:SetKeyboardInputEnabled(false) end end CloseButton.Paint = function (self, w, h) draw.RoundedBox (0,0,0,w,h,CNil) end LinkInput = vgui.Create ("DTextEntry", BrowserFrame) LinkInput:SetPos (90,31) LinkInput:SetSize (340,22) LinkInput:SetFont ("SCRoboto18") LinkInput.OnEnter = function () if string.match (LinkInput:GetText(), "soundcloud.com") then scb.checklink (LinkInput:GetText()) elseif LinkInput:GetText() == "" then scb.showerror ("#scp_enter_something_to_search") else scb.search (LinkInput:GetText(), "tracks") end end LoadButton = vgui.Create ("DButton", BrowserFrame) LoadButton:SetPos (430, 30) LoadButton:SetSize (60,24) LoadButton:SetText ("#scp_load") LoadButton:SetFont ("SCRoboto18") LoadButton:SetColor (CWhite) LoadButton.Paint = function (self,w,h) draw.RoundedBoxEx (8,0,0,w,h,CDarkGray,false,true,false,true) end LoadButton.DoClick = function () scb.checklink (LinkInput:GetText ()) end SearchButton = vgui.Create ("DButton", BrowserFrame) SearchButton:SetPos (10, 30) SearchButton:SetSize (80,24) SearchButton:SetText ("#scp_search") SearchButton:SetFont ("SCRoboto18") SearchButton:SetColor (CWhite) SearchButton.Paint = function (self,w,h) draw.RoundedBoxEx (8,0,0,w,h,CDarkGray,true,false,true,false) end SearchButton.DoClick = function () if LinkInput:GetText() == "" then scb.showerror ("#scp_enter_something_to_search") elseif !string.match(LinkInput:GetText (),"soundcloud.com") then scb.search (LinkInput:GetText (), "tracks") else scb.showerror ("#scp_you_cannot_search_a_link") end end if LocalPlayer():IsSuperAdmin() and !game.SinglePlayer() then AdminButton = vgui.Create ("DButton", BrowserFrame) AdminButton:SetPos (400, 0) AdminButton:SetSize (60,24) AdminButton:SetText ("#scp_admin") AdminButton:SetFont ("SCRoboto18") AdminButton.Paint = function (self, w, h) draw.RoundedBox (0,0,0,w,h,CNil) end if scb.settings.admin == 0 then AdminButton:SetColor (CLightGray) else AdminButton:SetColor (CRed) end AdminButton.DoClick = function () if scb.settings.admin == 1 then AdminButton:SetColor (CLightGray) scb.settings.admin = 0 scb.showerror ("#scp_admin_mode_deactivated") else AdminButton:SetColor (CRed) scb.settings.admin = 1 scb.showerror ("#scp_admin_mode_activated") end scb.changesettings () end end scb.playlists_frame () scb.playlists_load () end --Search & Load Functions-- function scb.checklink (data) if !string.match (data, "soundcloud.com") then scb.showerror ("#scp_provide_a_soundcloud_link") else http.Fetch ("http://api.soundcloud.com/resolve.json?url="..data.."&client_id="..scb.primary_key, function ( body, len, headers, code ) body = util.JSONToTable(body) if isstring(body) or istable(body) and body != nil then if body.errors != nil then scb.showerror ("#scp_the_link_is_not_supported") else if body.kind == "user" then scb.load_user (body) elseif body.streamable == nil or body.streamable == false then scb.showerror ("#scp_the_track_cant_be_streamed") elseif body.kind == "track" then scb.load_track (body) elseif body.kind == "playlist" then scb.load_playlist (body) else scb.showerror ("#scp_this_link_type_is_not_supported") end end else scb.showerror ("#scp_the_link_or_track_is_not_supported") end end, function () scb.showerror ("#scp_the_link_is_not_supported") end) end end function scb.search (text, tupe) tupe = tupe or "track" local texttable = {} for i = 1, string.len (text) do texttable[i] = string.format("%X",(string.byte( text, i, i ))) end local ltext = "%"..string.Implode ("%", texttable) http.Fetch ("http://api.soundcloud.com/"..tupe..".json?client_id="..scb.primary_key.."&q="..ltext.."&linked_partitioning=1&limit=30", function ( body, len, headers, code ) scb.search_results (util.JSONToTable(body), tupe, text) end) end function scb.search_next (data, tupe, text) http.Fetch (data, function ( body, len, headers, code ) scb.search_results (util.JSONToTable(body), tupe, text) end) end function scb.search_results (data, tupe, text) scb.headercloser () if IsValid (SearchOptionsFrame) and SearchOptionsFrame != nil then SearchOptionsFrame:SetVisible (false) end SearchOptionsFrame = vgui.Create ("DPanel", BrowserFrame) SearchOptionsFrame:SetSize(300,40) SearchOptionsFrame:SetPos(500,0) SearchOptionsFrame:SetVisible(true) SearchOptionsFrame.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,1,CBlack) end TracksCat = vgui.Create ("DButton", SearchOptionsFrame) if tupe == "tracks" then catstate = true else catstate = false end scb.searchcats (TracksCat, "#scp_category_tracks", 1, catstate, "search") TracksCat.DoClick = function () scb.search (text, "tracks") end PlaylistsCat = vgui.Create ("DButton", SearchOptionsFrame) if tupe == "playlists" then catstate = true else catstate = false end scb.searchcats (PlaylistsCat, "#scp_category_playlists", 2, catstate, "search") PlaylistsCat.DoClick = function () scb.search (text, "playlists") end UsersCat = vgui.Create ("DButton", SearchOptionsFrame) if tupe == "users" then catstate = true else catstate = false end scb.searchcats (UsersCat, "#scp_category_users", 3, catstate, "search") UsersCat.DoClick = function () scb.search (text, "users") end scb.createitemlist (data, tupe, "search", text) end function scb.headercloser () BrowserFrame:SizeTo (800,400,0.5) BrowserFrame:MoveTo ((ScrW()-800)/2,(ScrH()-400)/2,0.5) if IsValid (SearchOptionsFrame) and SearchOptionsFrame != nil then SearchOptionsFrame:SetVisible (false) end if IsValid (PlaylistPreview) and PlaylistPreview != nil then PlaylistPreview:SetVisible (false) end if IsValid (UserPreview) and UserPreview != nil then UserPreview:SetVisible (false) end if IsValid (ItemList) and ItemList != nil then ItemList:SetVisible (false) end end function scb.load_track (info) scb.gl_info = info if IsValid (ItemPreview) and ItemPreview != nil then ItemPreview:Remove ()end ItemPreview = vgui.Create ("DPanel", BrowserFrame) ItemPreview:SetSize (0,140) ItemPreview:SizeTo (499,140,0.3) ItemPreview:SetPos (0,60) ItemPreview:SetVisible (true) SCImage = vgui.Create("DImage", ItemPreview) SCImage:SetSize (104, 32) SCImage:SetPos (394, 48) SCImage:SetImage ("scplayer/sc_logo.png") http.Fetch (info.artwork_url, function ( body, len, headers, code ) if string.match (body, "cannot find original") then if info.user.avatar_url == nil then info.new_artwork_url = defart100 else info.new_artwork_url = info.user.avatar_url end TrackPic:OpenURL(info.new_artwork_url) end end) AddToPlst = vgui.Create ("DPanel", ItemPreview) AddToPlst:SetPos (50, 101) AddToPlst:SetSize (150,0) AddToPlst:SizeTo (150,40,0.2,0.3) AddToPlst.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w-1,h,CDarkGray) draw.RoundedBox (0,w-1,0,1,h,CBlack) end AddToPlst.OnCursorEntered = function () ItemPreview:MoveToFront() AddToPlst:MoveToFront() AddToPlst:SizeTo (150, 120, 0.1) ItemPreview:SizeTo (499, 220, 0.1) end AddToPlst.Think = function () if (AddToPlst:CursorPos () > 160 or select (2, AddToPlst:CursorPos ()) > 120 or AddToPlst:CursorPos () < 0 or select (2, AddToPlst:CursorPos ()) < 0) and ItemPreview:GetTall () > 140 then AddToPlst:SizeTo (150, 40, 0.1) ItemPreview:SizeTo (499, 140, 0.1) end end ATPlbl = vgui.Create ("DLabel", AddToPlst) ATPlbl:SetSize (150, 40) ATPlbl:SetContentAlignment (5) ATPlbl:SetText ("#scp_add_to_playlist") ATPlbl:SetFont ("SCRoboto24") ATPlbl:SetColor (CWhite) ATPlst = vgui.Create ("DScrollPanel", AddToPlst) ATPlst:SetSize (150, 80) ATPlst:SetPos (0,39) ATPlst.Paint = function (self, w, h) draw.RoundedBox (0,0,0,w,h,CNil) end scb.paintscrollbar (ATPlst) if istable (cl_playlists) then for i = 1, #cl_playlists do local plst = vgui.Create ("DButton", ATPlst) plst:SetPos (2, (i-1)*20) plst:SetSize (146, 20) plst:SetText (" "..cl_playlists[i].Name) plst:SetFont ("SCRoboto16") plst:SetContentAlignment(4) plst:SetColor (CWhite) plst.Paint = function (self, w, h) draw.RoundedBox (0,0,0,w,h-2, CGray) end plst.DoClick = function () scb.playlist_addtrack (cl_playlists[i].Name, info.id) scb.playlist_show (cl_playlists[i].Name) end end end PlayBtn = vgui.Create ("DButton", ItemPreview) PlayBtn:SetPos (200, 101) PlayBtn:SetSize (100,0) PlayBtn:SizeTo (100,39,0.2,0.4) PlayBtn:SetText ("#scp_play") PlayBtn:SetFont ("SCRoboto24") PlayBtn:SetColor (CWhite) PlayBtn.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CDarkGray) draw.RoundedBox (0,w-1,0,1,h,CBlack) end PlayBtn.DoClick = function () if scb.settings.admin == 0 then scb.queue[1] = info if IsValid (scb.cl_stream) then scb.cl_stream:Stop() end scb.play_track (scb.queue[1], "cl") scb.queue_refresh () else net.Start ("scb_adminplay") net.WriteTable (info) net.SendToServer() end end AddToQueueBtn = vgui.Create ("DButton", ItemPreview) AddToQueueBtn:SetPos (300, 101) AddToQueueBtn:SetSize (150,0) AddToQueueBtn:SizeTo (150,39,0.2,0.5) AddToQueueBtn:SetText ("#scp_add_to_queue") AddToQueueBtn:SetFont ("SCRoboto24") AddToQueueBtn:SetColor (CWhite) AddToQueueBtn.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CDarkGray) end AddToQueueBtn.DoClick = function () if scb.settings.admin == 0 then scb.queue_addtrack (info) else net.Start ("scb_adminqueue") net.WriteTable (info) net.SendToServer() end scb.notify ("player") end TrackPic = vgui.Create ("HTML", ItemPreview) TrackPic:SetPos (1,1) TrackPic:SetSize (120,120) if info.artwork_url == nil then if info.user.avatar_url == nil then info.artwork_url = defart100 else info.artwork_url = info.user.avatar_url end end TrackPic:OpenURL(info.artwork_url) TrackArtist = vgui.Create ("DLabel", ItemPreview) TrackArtist:SetPos (112,5) TrackArtist:SetSize (scb.gettextlen (info.user.username, "SCInterstate18"),20) TrackArtist:SetFont ("SCInterstate18") TrackArtist:SetColor (CBWhite) TrackArtist:SetText (info.user.username) TrackArtist:SetMouseInputEnabled(true) TrackArtist.DoClick = function () scb.headercloser () http.Fetch ("http://api.soundcloud.com/resolve.json?url="..info.user.permalink_url.."&client_id="..scb.primary_key, function ( body, len, headers, code ) scb.load_user (util.JSONToTable(body)) end) end TrackArtist.Paint = function () if TrackArtist:IsHovered() then TrackArtist:SetColor (CLightGray) else TrackArtist:SetColor (CBWhite) end end TrackTitle = vgui.Create ("DLabel", ItemPreview) TrackTitle:SetPos (112,31) TrackTitle:SetSize (scb.gettextlen (info.title, "SCInterstate24"),24) TrackTitle:SetFont ("SCInterstate24") TrackTitle:SetColor (CBWhite) TrackTitle:SetText (info.title) TrackTitle:SetMouseInputEnabled (true) TrackTitle.DoClick = function () gui.OpenURL (info.permalink_url) end TrackTitle.Paint = function () if TrackTitle:IsHovered() then TrackTitle:SetColor (CLightGray) else TrackTitle:SetColor (CBWhite) end end TrackCreated = vgui.Create ("DLabel", ItemPreview) TrackCreated:SetPos (420,83) TrackCreated:SetSize (80,14) TrackCreated:SetFont ("SCRoboto16") TrackCreated:SetColor (CGray) local date = string.Explode("/", string.Explode (" ", info.created_at)[1]) date [1], date [3] = date [3], date [1] TrackCreated:SetText (string.Implode(".", date)) TrackLen = vgui.Create ("DLabel", ItemPreview) TrackLen:SetPos (110,83) TrackLen:SetSize (390,14) TrackLen:SetFont ("SCRoboto16") TrackLen:SetColor (CGray) local trcklen = (math.floor(tonumber(info.duration)/1000)) local trckhr = math.floor (trcklen/3600) local trckmin = math.floor (trcklen/60-trckhr*60) local trcksec = math.floor (trcklen-trckhr*3600-trckmin*60) if trcksec < 10 then trcksec = tostring ("0"..trcksec) end if trckhr == 0 then TrackLen:SetText (trckmin..":"..trcksec) else if trckmin < 10 then trckmin = tostring ("0"..trckmin) end TrackLen:SetText (trckhr..":"..trckmin..":"..trcksec) end TrackPlays = vgui.Create ("DLabel", ItemPreview) TrackPlays:SetPos (200, 83) TrackPlays:SetSize (50, 14) TrackPlays:SetFont ("SCRoboto16") TrackPlays:SetColor (CGray) info.playback_count = tonumber(info.playback_count) pc_mil = math.floor(info.playback_count/1000000) pc_huntho = (math.floor(info.playback_count/10000)-pc_mil*100) if pc_huntho <10 then pc_huntho = "0"..pc_huntho end if pc_huntho/10 == math.floor(pc_huntho/10) then pc_huntho = pc_huntho/10 end pc_mil = pc_mil.."."..pc_huntho.."M" pc_tho = math.floor(info.playback_count/1000) if (math.floor(info.playback_count/100)-pc_tho*10) == 0 then pc_tho = pc_tho.."K" else pc_tho = pc_tho.."."..(math.floor(info.playback_count/100)-pc_tho*10).."K" end pc_hun = info.playback_count - math.floor(info.playback_count/1000)*1000 if pc_hun <10 then pc_hun = "00"..pc_hun elseif pc_hun <100 then pc_hun = "0"..pc_hun end if info.playback_count >= 1000000 then info.smartplays = pc_mil elseif info.playback_count >= 100000 then info.smartplays = math.floor(info.playback_count/1000).."K" elseif info.playback_count >= 10000 then info.smartplays = pc_tho elseif info.playback_count >= 1000 then info.smartplays = math.floor(info.playback_count/1000)..","..pc_hun else info.smartplays = info.playback_count end TrackPlays:SetText (info.smartplays) ItemPreview.Paint = function (self,w,h) draw.RoundedBox (0,105,5,TrackArtist:GetTextSize()+14,22,CTBlack) draw.RoundedBox (0,105,30,TrackTitle:GetTextSize()+14,28,CTBlack) draw.RoundedBox (0,0,0,w,1,CBlack) draw.RoundedBox (0,1,80,w-2,21,CWhite) surface.SetDrawColor (CGray) draw.NoTexture () surface.DrawPoly(scb.littleplays) end end function scb.load_user (info, tupe) tupe = tupe or "tracks" scb.headercloser () UserPreview = vgui.Create ("DPanel", BrowserFrame) UserPreview:SetSize(300,100) UserPreview:SetPos(500,0) UserPreview:SetVisible(true) UserPic = vgui.Create ("HTML", UserPreview) UserPic:SetPos (0,1) UserPic:SetSize (120,120) if info.avatar_url == nil then info.avatar_url = defart100 end UserPic:OpenURL(info.avatar_url) UserName = vgui.Create ("DLabel", UserPreview) UserName:SetPos (112,11) UserName:SetSize (190,24) UserName:SetFont ("SCInterstate24") UserName:SetColor (CBWhite) UserName:SetText (info.username) UserName:SetMouseInputEnabled(true) UserName.DoClick = function () gui.OpenURL (info.permalink_url) end UserPreview.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h-20,CLightGray) draw.RoundedBox (0,105,5,UserName:GetTextSize()+14,38,CTBlack) draw.RoundedBox (0,0,0,w,1,CBlack) draw.RoundedBox (0,0,101,w,1,CBlack) end http.Fetch ("http://api.soundcloud.com/users/"..info.id.."/"..tupe.."?client_id="..scb.primary_key, function ( body, len, headers, code ) scb.createitemlist (util.JSONToTable(body), "tracks", "usertracks") end) TracksCat = vgui.Create ("DButton", UserPreview) if tupe == "tracks" then catstate = true else catstate = false end scb.searchcats (TracksCat, "#scp_category_tracks", 2, catstate, "usertracks") TracksCat.DoClick = function () tupe = "tracks" scb.load_user (info, tupe) end PlaylistsCat = vgui.Create ("DButton", UserPreview) if tupe == "playlists" then catstate = true else catstate = false end scb.searchcats (PlaylistsCat, "#scp_category_playlists", 3, catstate, "userplsts") PlaylistsCat.DoClick = function () tupe = "playlists" scb.load_user (info, tupe) end end function scb.load_playlist (info) scb.headercloser () PlaylistPreview = vgui.Create ("DPanel", BrowserFrame) PlaylistPreview:SetSize(300,100) PlaylistPreview:SetPos(500,0) PlaylistPreview:SetVisible(true) PlaylistPic = vgui.Create ("HTML", PlaylistPreview) PlaylistPic:SetPos (0,1) PlaylistPic:SetSize (120,120) if info.artwork_url == nil then if info.user.avatar_url == nil then info.user.avatar_url = defart47 else info.artwork_url = info.user.avatar_url end end PlaylistPic:OpenURL(info.artwork_url) PlaylistAuthor = vgui.Create ("DLabel", PlaylistPreview) PlaylistAuthor:SetPos (112,12) PlaylistAuthor:SetSize (190,18) PlaylistAuthor:SetFont ("SCInterstate18") PlaylistAuthor:SetColor (CBWhite) PlaylistAuthor:SetText (info.user.username) PlaylistAuthor:SetMouseInputEnabled(true) PlaylistAuthor.DoClick = function () gui.OpenURL (info.user.permalink_url) end PlaylistTitle = vgui.Create ("DLabel", PlaylistPreview) PlaylistTitle:SetPos (112,37) PlaylistTitle:SetSize (190,24) PlaylistTitle:SetFont ("SCInterstate24") PlaylistTitle:SetColor (CBWhite) PlaylistTitle:SetText (info.title) PlaylistTitle:SetMouseInputEnabled(true) PlaylistTitle.DoClick = function () gui.OpenURL (info.permalink_url) end PlaylistPreview.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w-1,h,CLightGray) draw.RoundedBox (0,105,10,PlaylistAuthor:GetTextSize()+14,22,CTBlack) draw.RoundedBox (0,105,36,PlaylistTitle:GetTextSize()+14,28,CTBlack) draw.RoundedBox (0,0,0,w,1,CBlack) draw.RoundedBox (0,0,101,w,1,CBlack) end scb.createitemlist (info.tracks, "tracks", "plsttracks") ConvertBtn = vgui.Create ("DButton", PlaylistPreview) ConvertBtn:SetPos (100,80) ConvertBtn:SetSize (199,20) ConvertBtn:SetText ("#scp_convert_to_local_playlist") ConvertBtn:SetColor (CDarkGray) ConvertBtn:SetFont ("SCRoboto18") ConvertBtn.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CWhite) end ConvertBtn.DoClick = function () if sql.Query ("SELECT Contents FROM soundcloud_player_playlists WHERE Name = '"..info.title.."'") == nil then sql.Query ("INSERT INTO soundcloud_player_playlists (Name, Contents) VALUES ('"..info.title.."', '')") scb.showerror ("#scp_playlist_was_successfully_created") for i = 1, #info.tracks do scb.playlist_addtrack (info.title, info.tracks[i].id) end scb.playlists_load () else scb.showerror ("#scp_playlist_already_exists") end end end concommand.Add ("scplayer", scb.openframe)<file_sep>/lua/scplayer/cl_misc.lua --White CBWhite = Color(255,255,255,255) CWhite = Color(220,220,220,255) CTWhite = Color(220,220,220,100) --Gray CGray = Color(100,100,100,255) CTGray = Color(100,100,100,240) CDarkGray = Color(50,50,50,255) CLightGray = Color(150,150,150,255) --Black CBlack = Color (0,0,0,255) CLTBlack = Color (0,0,0,220) CTBlack = Color (0,0,0,230) CVTBlack = Color (0,0,0,240) --Red CRed = Color (255,100,70,255) --Yellow CYellow = Color (255,255,100,255) --Green CGreen = Color (100,255,100,255) --Invis CNil = Color(0,0,0,0) scb.littleplays = { { x = 184, y = 84}, { x = 196, y = 90}, { x = 184, y = 96} } scb.largeplays = { { x = 6, y = 6}, { x = 26, y = 15}, { x = 6, y = 24} } scb.back1 = { { x = 4, y = 15}, { x = 14, y = 5}, { x = 18, y = 5}, { x = 8, y = 15} } scb.back2 = { { x = 4, y = 15}, { x = 8, y = 15}, { x = 18, y = 25}, { x = 14, y = 25} } scb.del1 = { { x = 6, y = 8}, { x = 8, y = 6}, { x = 24, y = 22}, { x = 22, y = 24} } scb.del2 = { { x = 22, y = 6}, { x = 24, y = 8}, { x = 8, y = 24}, { x = 6, y = 22} } scb.ren = { { x = 22, y = 6}, { x = 24, y = 8}, { x = 8, y = 22} } defart300 = "https://i.imgsafe.org/5563ec5ff5.png" defart100 = "https://i.imgsafe.org/4322fc01e9.jpg" defart47 = "https://i.imgsafe.org/4322f58d51.jpg" defart299 = "https://i.imgsafe.org/a12f1eec62.png" surface.CreateFont("SCRoboto14",{ font = "Roboto", size = 14, weight = 300 }) surface.CreateFont("SCRoboto16",{ font = "Roboto", size = 16, weight = 700, extended = true }) surface.CreateFont("SCRoboto18",{ font = "Roboto", size = 18, weight = 700, extended = true }) surface.CreateFont("SCRoboto20",{ font = "Roboto", size = 20, weight = 300, extended = true }) surface.CreateFont("SCRoboto24",{ font = "Roboto", size = 24, weight = 500, extended = true }) surface.CreateFont("SCInterstate14",{ font = "GLInterstateRegular", size = 14, weight = 500, extended = true }) surface.CreateFont("SCInterstate14B",{ font = "GLInterstateRegular", size = 14, weight = 1000, extended = true }) surface.CreateFont("SCInterstate18",{ font = "GLInterstateRegular", size = 16, weight = 500, extended = true }) surface.CreateFont("SCInterstate24",{ font = "GLInterstateRegular", size = 23, weight = 500, extended = true }) function scb.showerror (text) local textlen = scb.gettextlen(text, "SCRoboto24") if IsValid(Notifier) and Notifier != nil then Notifier:SetVisible (false) end Notifier = vgui.Create ("DPanel") Notifier:SetSize (textlen + 100, 55) Notifier:Center () Notifier:MakePopup () Notifier.Paint = function (self, w, h) draw.RoundedBox (0,0,0,w,h,CWhite) surface.SetDrawColor(CBlack) surface.DrawOutlinedRect( 0, 0, w, h) end NLabel = vgui.Create ("DLabel", Notifier) NLabel:SetPos (50, 0) NLabel:SetSize (textlen, 30) NLabel:SetColor (CBlack) NLabel:SetFont ("SCRoboto24") NLabel:SetText (text) NButton = vgui.Create ("DButton", Notifier) NButton:SetPos ((textlen+50)/2, 30) NButton:SetSize (50, 20) NButton:SetColor (CBlack) NButton:SetText ("OK") NButton.Paint = function (self,w,h) surface.SetDrawColor(CBlack) surface.DrawOutlinedRect( 0, 0, w, h) end NButton.DoClick = function () Notifier:SetVisible (false) end end function scb.notify (frame) if frame == "player" then if IsValid(PlayerFrame) and scb.settings.plrsize == "default" then if IsValid (notifier) then notifier:Remove () end notifier = vgui.Create ("DPanel", PlayerFrame) notifier:SetPos (105, 30) notifier:SetSize (100, 0) notifier:SizeTo (100, 30, 0.3) notifier.Paint = function (self, w, h) draw.RoundedBox (8,0,10,w,20,CDarkGray) surface.SetDrawColor (CDarkGray) draw.NoTexture () surface.DrawPoly({{x=40, y=10}, {x=50, y=0}, {x=60, y=10}}) end notifierl = vgui.Create ("DLabel", notifier) notifierl:SetPos (0, 10) notifierl:SetSize (100, 20) notifierl:SetFont("SCRoboto20") notifierl:SetColor(CWhite) notifierl:SetText("Added") notifierl:SetContentAlignment(5) timer.Simple (2, function () if IsValid (notifier) then notifier:SizeTo (100, 0, 0.3) timer.Simple (0.3, function () if IsValid (notifier) then notifier:Remove () end end) end end) end end end function scb.chooser (info) if IsValid (PlayerFrame) and PlayerFrame:IsVisible() then if IsValid (s_chooserf) then s_chooserf:Remove () timer.Destroy ("scb_chooser") end if scb.settings.plrsize == "default" then s_chooserf = vgui.Create ("DPanel", InvisFrame) s_chooserf:SetPos (0, 0) s_chooserf:SetSize (300,300) s_chooserf.Paint = function (self, w, h) draw.RoundedBox(0 ,0 ,0 ,w, h, CVTBlack) end s_chooserl = vgui.Create ("DLabel", s_chooserf) s_chooserl:SetPos (0, 70) s_chooserl:SetSize (300, 30) s_chooserl:SetFont("SCRoboto24") s_chooserl:SetColor(CWhite) s_chooserl:SetText("Server has started a stream.") s_chooserl:SetContentAlignment(5) s_chooserl = vgui.Create ("DLabel", s_chooserf) s_chooserl:SetPos (0, 95) s_chooserl:SetSize (300, 30) s_chooserl:SetFont("SCRoboto24") s_chooserl:SetColor(CWhite) s_chooserl:SetText("Do you want to switch to it?") s_chooserl:SetContentAlignment(5) s_chooserl1 = vgui.Create ("DLabel", s_chooserf) s_chooserl1:SetPos (0, 120) s_chooserl1:SetSize (300, 30) s_chooserl1:SetFont("SCRoboto24") s_chooserl1:SetColor(CWhite) s_chooserl1:SetText("9") s_chooserl1:SetContentAlignment(5) s_choosery = vgui.Create ("DButton", s_chooserf) s_choosery:SetPos (80, 150) s_choosery:SetSize (60, 30) s_choosery:SetColor (CWhite) s_choosery:SetFont("SCRoboto24") s_choosery:SetText ("Yes") s_choosery.Paint = function (self,w,h) surface.SetDrawColor(CWhite) surface.DrawOutlinedRect( 0, 0, w, h) end s_choosery.DoClick = function () scb.switch_stream (info, "sv") timer.Stop ("scb_chooser") s_chooserf:Remove() end s_choosern = vgui.Create ("DButton", s_chooserf) s_choosern:SetPos (160, 150) s_choosern:SetSize (60, 30) s_choosern:SetColor (CWhite) s_choosern:SetFont("SCRoboto24") s_choosern:SetText ("No") s_choosern.Paint = function (self,w,h) surface.SetDrawColor(CWhite) surface.DrawOutlinedRect( 0, 0, w, h) end s_choosern.DoClick = function () timer.Stop ("scb_chooser") s_chooserf:Remove() end timer_elap = 9 timer.Create ("scb_chooser",1 ,10 , function () timer_elap = timer_elap-1 if IsValid (s_chooserl1) then s_chooserl1:SetText(timer_elap) end if timer_elap == 0 then if IsValid(scb.cl_stream) then scb.switch_stream (info, "sv") else scb.sv_stream:SetVolume(scb.settings.volume/100) end s_chooserf:Remove() end end) else s_chooserf = vgui.Create ("DPanel", PlayerFrame) s_chooserf:SetPos (0, 30) s_chooserf:SetSize (400, 50) s_chooserf.Paint = function (self, w, h) draw.RoundedBox(0 ,0 ,0 ,w, h, CVTBlack) end s_chooserl = vgui.Create ("DLabel", s_chooserf) s_chooserl:SetPos (0, 10) s_chooserl:SetSize (250, 30) s_chooserl:SetFont("SCRoboto24") s_chooserl:SetColor(CWhite) s_chooserl:SetText("Switch to the server? 10") s_chooserl:SetContentAlignment(5) s_choosery = vgui.Create ("DButton", s_chooserf) s_choosery:SetPos (250, 10) s_choosery:SetSize (60, 30) s_choosery:SetColor (CWhite) s_choosery:SetFont("SCRoboto24") s_choosery:SetText ("Yes") s_choosery.Paint = function (self,w,h) surface.SetDrawColor(CWhite) surface.DrawOutlinedRect( 0, 0, w, h) end s_choosery.DoClick = function () scb.switch_stream (info, "sv") s_chooserf:Remove() end s_choosern = vgui.Create ("DButton", s_chooserf) s_choosern:SetPos (320, 10) s_choosern:SetSize (60, 30) s_choosern:SetColor (CWhite) s_choosern:SetFont("SCRoboto24") s_choosern:SetText ("No") s_choosern.Paint = function (self,w,h) surface.SetDrawColor(CWhite) surface.DrawOutlinedRect( 0, 0, w, h) end s_choosern.DoClick = function () timer.Stop ("scb_chooser") s_chooserf:Remove() end timer_elap = 9 timer.Create ("scb_chooser",1 ,10 , function () timer_elap = timer_elap-1 if IsValid (s_chooserl) then s_chooserl:SetText("Switch to the server? "..timer_elap) end if timer_elap == 0 then scb.switch_stream (info, "sv") s_chooserf:Remove() end end) end else scb.play_track (info, "sv") end end function scb.gettextlen (text, font) surface.SetFont(font) surface.GetTextSize(text) return surface.GetTextSize(text) end function scb.searchcats (panel, title, num, state, tupe) if tupe == "search" then panel:SetPos ((num-1)*100, 0) else panel:SetPos ((num-1)*100, 60) end panel:SetSize (100,40) panel:SetText (title) panel:SetColor (CGray) panel:SetFont ("SCRoboto24") panel.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CWhite) if panel:IsHovered() then draw.RoundedBox (0,0,35,w,5,CLightGray) end if state then draw.RoundedBox (0,0,35,w,5,CDarkGray) end end end function scb.createitemlist (data, tupe, tupe2, text) if IsValid (ItemList) and ItemList != nil then ItemList:SetVisible (false) end ItemList = vgui.Create ("DScrollPanel", BrowserFrame) if tupe2 == "search" then ItemList:SetSize(300,0) ItemList:SizeTo(299,359,0.5) ItemList:SetPos(500,40) else ItemList:SetSize(300,299) ItemList:SetPos(500,100) end ItemList:SetVisible(true) ItemList.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CWhite) end scb.paintscrollbar (ItemList) Item = {} ItemArt = {} AuthorName = {} ItemName = {} ItemSelect = {} if istable(data.collection) and #data.collection == 0 then templabel = vgui.Create ("DLabel", ItemList) templabel:SetPos (0, 150) templabel:SetSize (300, 50) templabel:SetColor (CBlack) templabel:SetFont ("SCRoboto24") templabel:SetText ("Seems like nothing is here!") templabel:SetContentAlignment(5) end itemtb = data.collection or data for i = 1, #itemtb do if itemtb[i] != nil then Item[i] = vgui.Create ("DPanel", ItemList) Item[i]:SetPos (0,i*50-50) Item[i]:SetSize (300,49) http.Fetch (itemtb[i].artwork_url, function ( body, len, headers, code ) if string.match (body, "cannot find original") then if tupe == "tracks" or tupe == "playlists" then if itemtb[i].user.avatar_url == nil then ItemArt[i]:OpenURL (defart47) else itemtb[i].artwork_url = itemtb[i].user.avatar_url end ItemArt[i]:OpenURL(string.Replace (itemtb[i].artwork_url, "large", "badge")) elseif tupe == "users" then if data.collection.avatar_url == nil then data.collection.avatar_url = defart47 end ItemArt[i]:OpenURL(string.Replace (itemtb[i].avatar_url, "large", "badge")) end end end) ItemArt[i] = vgui.Create ("HTML", Item[i]) ItemArt[i]:SetPos(1,1) ItemArt[i]:SetSize(55,200) if tupe == "tracks" or tupe == "playlists" then if itemtb[i].artwork_url == nil then if itemtb[i].user.avatar_url == nil then ItemArt[i]:OpenURL (defart47) else itemtb[i].artwork_url = itemtb[i].user.avatar_url end end ItemArt[i]:OpenURL(string.Replace (itemtb[i].artwork_url, "large", "badge")) elseif tupe == "users" then if data.collection.avatar_url == nil then data.collection.avatar_url = defart47 end ItemArt[i]:OpenURL(string.Replace (itemtb[i].avatar_url, "large", "badge")) end if istable (itemtb[i].user) and itemtb[i].user.username != nil then AuthorName[i] = vgui.Create ("DLabel", Item[i]) AuthorName[i]:SetPos (60,6) AuthorName[i]:SetSize (240,14) AuthorName[i]:SetFont ("SCInterstate14") AuthorName[i]:SetColor (CBWhite) AuthorName[i]:SetText (itemtb[i].user.username) end ItemName[i] = vgui.Create ("DLabel", Item[i]) ItemName[i]:SetColor (CBWhite) if isstring (itemtb[i].title) and itemtb[i].title !=nil then ItemName[i]:SetSize (230,18) ItemName[i]:SetFont ("SCInterstate18") ItemName[i]:SetPos (60,26) ItemName[i]:SetText (itemtb[i].title) elseif isstring (itemtb[i].username) and itemtb[i].username !=nil then ItemName[i]:SetSize (230,24) ItemName[i]:SetFont ("SCInterstate18") ItemName[i]:SetText (itemtb[i].username) ItemName[i]:SetPos (60,6) end Item[i].Paint = function (self,w,h) if i/2 == math.floor(i/2) then draw.RoundedBox (0,50,0,w,h,CGray) else draw.RoundedBox (0,50,0,w,h,CLightGray) end if tupe == "tracks" or tupe == "playlists" then draw.RoundedBox (0,55,4, AuthorName[i]:GetTextSize() + 8,18,CVTBlack) draw.RoundedBox (0,55,25, ItemName[i]:GetTextSize() + 10,21,CVTBlack) elseif tupe == "users" then draw.RoundedBox (0,55,2, ItemName[i]:GetTextSize() + 10,32,CVTBlack) end end ItemSelect[i] = vgui.Create ("DButton", Item[i]) ItemSelect[i]:SetPos (0, 0) ItemSelect[i]:SetSize (280,50) ItemSelect[i]:SetText ("") ItemSelect[i].Paint = function () end ItemSelect[i].DoClick = function () scb.checklink (itemtb[i].permalink_url) end end end if isstring(data.next_href) then NextPage = vgui.Create ("DButton", ItemList) NextPage:SetPos (0, #itemtb*50) NextPage:SetSize (300,30) NextPage:SetFont ("SCRoboto20") NextPage:SetColor (CBlack) NextPage:SetText ("Next page") NextPage.Paint = function (self, w, h) draw.RoundedBox (0,0,0,w,h,CTWhite) end NextPage.DoClick = function () scb.search_next (data.next_href, tupe, text) end end end function scb.paintscrollbar (panel, col1, col2) col1 = col1 or CLightGray col2 = col2 or CDarkGray local sbar = panel:GetVBar() function sbar:Paint( w, h ) draw.RoundedBox( 0, 0, 0, w, h, col1 ) end function sbar.btnUp:Paint( w, h ) draw.RoundedBox( 4, 4, 4, w-8, h-8, col2 ) end function sbar.btnDown:Paint( w, h ) draw.RoundedBox( 4, 4, 4, w-8, h-8, col2 ) end function sbar.btnGrip:Paint( w, h ) draw.RoundedBox( 4, 4, 0, w-8, h, col2 ) end end function scb.changesettings () file.Write ("soundcloudplayer/settings.txt" , util.TableToJSON ( scb.settings ) ) end<file_sep>/lua/scplayer/cl_queue.lua function scb.queue_addtrack (info) scb.queue[#scb.queue+1] = info if #scb.queue == 1 then scb.play_track (scb.queue[1], "cl") end scb.queue_refresh () end function scb.queue_refresh () if IsValid (scb.cl_stream) then curtime = math.floor (scb.cl_stream:GetTime()) else curtime = 0 end timer.Create ("scb_queue", scb.queue[1].duration/1000 - curtime, 1, function () if istable(scb.queue[2]) then scb.play_track (scb.queue[2], "cl") end table.remove (scb.queue, 1) end) end<file_sep>/README.md # SoundCloud-Player SoundCloud Player addon with gmod localization feature. Originally made by https://steamcommunity.com/id/nikwin174 <file_sep>/lua/scplayer/sv_scplayer.lua util.AddNetworkString("scb_adminplay") util.AddNetworkString("scb_adminqueue") util.AddNetworkString("scb_adminplaylist") util.AddNetworkString("scb_queue_remove") util.AddNetworkString("scb_queue_move") util.AddNetworkString("scb_send_queue") util.AddNetworkString("scb_broadcastplay") function scb.queue_playtrack (info) curtimell = 0 timer.Create ("scb_curtime", 1, math.floor(info.duration/1000) , function () curtimell = curtimell + 1 end) scb.queue_refresh () net.Start ("scb_broadcastplay") net.WriteTable (info) net.Broadcast () end function scb.queue_refresh () if istable(scb.queue[2]) then timer.Create ("scb_queue", timer.RepsLeft("scb_curtime"), 1, function () if istable(scb.queue[2]) then scb.queue_playtrack (scb.queue[2]) end table.remove (scb.queue, 1) scb.queue_send () end) end scb.queue_send () end function scb.queue_addtrack (info, pos) pos = pos or "1" if pos == "1" then scb.queue[1] = info scb.queue_playtrack (info) else scb.queue[#scb.queue+1] = info end scb.queue_refresh () end function scb.queue_send () templst = {} for i = 1, #scb.queue do if istable (scb.queue[i]) then templst[i] = {} templst[i].user = {} templst[i].id = scb.queue[i].id templst[i].title = scb.queue[i].title templst[i].duration = scb.queue[i].duration templst[i].permalink_url = scb.queue[i].permalink_url templst[i].artwork_url = scb.queue[i].artwork_url templst[i].user.avatar_url = scb.queue[i].user.avatar_url templst[i].user.username = scb.queue[i].user.username end end net.Start ("scb_send_queue") net.WriteTable (templst) net.Broadcast () end net.Receive ("scb_adminplay", function (len, ply) if ply:IsSuperAdmin() then scb.queue_addtrack (net.ReadTable()) end end) net.Receive ("scb_adminqueue", function (len, ply) if ply:IsSuperAdmin() then scb.queue_addtrack (net.ReadTable(), "last") end end) net.Receive ("scb_adminplaylist", function (len, ply) if ply:IsSuperAdmin() then l1, l2, l3 = false, false, false scb.queue = {} if timer.Exists ("scb_queue") then timer.Stop ("scb_queue") end tempplst = net.ReadTable() if #tempplst == 0 then return elseif #tempplst == 1 then http.Fetch ("http://api.soundcloud.com/tracks/"..tempplst[1].."?client_id="..scb.primary_key, function ( body, len, headers, code ) scb.queue[1] = util.JSONToTable(body) scb.queue_playtrack (scb.queue[1]) end) else for i = 1, #tempplst do http.Fetch ("http://api.soundcloud.com/tracks/"..tempplst[i].."?client_id="..scb.primary_key, function ( body, len, headers, code ) scb.queue[i] = util.JSONToTable(body) scb.queue_send () if i == 1 then l1 = true end if i == 2 then l2 = true end if l1 and l2 and !l3 then l3 = true scb.queue_playtrack (scb.queue[1]) end end) end end end end) net.Receive ("scb_queue_remove", function (len, ply) if ply:IsSuperAdmin() then local pos = net.ReadTable()[1] table.remove (scb.queue, pos) if pos == 1 then if istable (scb.queue[1]) then scb.queue_playtrack (scb.queue[1]) end end scb.queue_refresh () end end) net.Receive ("scb_queue_move", function (len, ply) if ply:IsSuperAdmin() then local pos = net.ReadTable()[1] table.insert (scb.queue, 2, scb.queue[pos]) table.remove (scb.queue, pos+1) scb.queue_refresh () end end)<file_sep>/lua/scplayer/cl_playlists.lua sql.Query ("CREATE TABLE IF NOT EXISTS soundcloud_player_playlists (Name TEXT, Contents TEXT)") function scb.playlists_frame (tupe) tupe = tupe or "client" PlSframe = vgui.Create ("DPanel", BrowserFrame) PlSframe:SetPos (1,200) PlSframe:SetSize (498,199) PlSframe.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CWhite) end PlSLocal = vgui.Create ("DButton", PlSframe) PlSLocal:SetPos (175,0) PlSLocal:SetSize (150,30) PlSLocal:SetColor (CDarkGray) PlSLocal:SetFont ("SCRoboto24") PlSLocal:SetText ("#scp_category_playlists") PlSLocal.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CWhite) draw.RoundedBox (0,0,25,w,5,CDarkGray) end PlSLocal.DoClick = function () if IsValid (PlSListTF) and PlSListTF != nil then PlSListTF:SetVisible (false) PlSListTF:Remove () end clPlSListF:SetVisible (true) end clPlSListF = vgui.Create ("DScrollPanel", PlSframe) clPlSListF:SetSize (454,155) clPlSListF:SetPos (40,40) clPlSListF.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CLightGray) end scb.paintscrollbar (clPlSListF) scb.cl_plst_opened = tupe scb.playlists_load (tupe) PlSCreateBtn = vgui.Create ("DButton", PlSframe) PlSCreateBtn:SetPos (5,40) PlSCreateBtn:SetSize (30, 30) PlSCreateBtn:SetText ("") PlSCreateBtn.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CDarkGray) draw.RoundedBox (0,4,13,22,4,CWhite) draw.RoundedBox (0,13,4,4,22,CWhite) end PlSCreateBtn.DoClick = function () scb.playlist_create () end end function scb.playlists_load () cl_playlists = sql.Query ("#scp_select_name_contents_from_soundcloud_player_playlists") if istable (cl_playlists) then for i = 1, #cl_playlists do scb.create_plst_btn (cl_playlists[i].Name, i, util.JSONToTable (cl_playlists[i].Contents), clPlSListF) end end end function scb.create_plst_btn (name, pos, contents, parent) PlsButton = vgui.Create ("DButton", parent) PlsButton:SetSize (454,22) PlsButton:SetPos (0,(pos-1)*22) PlsButton:SetText (" "..name) PlsButton:SetFont ("SCRoboto18") PlsButton:SetContentAlignment(4) PlsButton:SetColor (CWhite) PlsButton:SetVisible (true) PlsButton.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h-2, CGray) end PlsButton.DoClick = function () scb.playlist_show (name) end end function scb.playlist_create () if IsValid(CrPlstframe) and CrPlstframe != nil then CrPlstframe:Remove() end CrPlstframe = vgui.Create ("DFrame") CrPlstframe:SetSize(200,100) CrPlstframe:Center() CrPlstframe:SetTitle("#scp_create_playlist") CrPlstframe:SetVisible(true) CrPlstframe:SetDraggable (false) CrPlstframe:ShowCloseButton (true) CrPlstframe:MakePopup() CrPlstframe.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CGray) surface.SetDrawColor(CBlack) surface.DrawOutlinedRect( 0, 0, w, h) end NameEntry = vgui.Create ("DTextEntry", CrPlstframe) NameEntry:SetPos (10,30) NameEntry:SetFont ("SCRoboto18") NameEntry:SetTextColor (CDarkGray) NameEntry:SetSize (180,20) NameEntry.OnEnter = function () if NameEntry:GetValue() == "" then scb.showerror ("#scp_you_cannot_create_playlist_with_this_name") else if sql.Query ("SELECT Contents FROM soundcloud_player_playlists WHERE Name = '"..NameEntry:GetValue().."'") == nil then sql.Query ("INSERT INTO soundcloud_player_playlists (Name, Contents) VALUES ('"..NameEntry:GetValue().."', '')") scb.playlists_load () scb.showerror ("#scp_playlist_was_successfully_created") if IsValid (ItemPreview) then scb.load_track (scb.gl_info) end else scb.showerror ("#scp_playlist_already_exists") end CrPlstframe:SetVisible (false) end end CreateBtn = vgui.Create ("DButton", CrPlstframe) CreateBtn:SetSize (180,30) CreateBtn:SetPos (10,60) CreateBtn:SetFont ("SCRoboto24") CreateBtn:SetColor (CGray) CreateBtn:SetText ("#scp_create_playlist") CreateBtn.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CWhite) end CreateBtn.DoClick = function () if NameEntry:GetValue() == "" then scb.showerror ("#scp_you_cannot_create_playlist_with_this_name") else if sql.Query ("SELECT Contents FROM soundcloud_player_playlists WHERE Name = '"..NameEntry:GetValue().."'") == nil then sql.Query ("INSERT INTO soundcloud_player_playlists (Name, Contents) VALUES ('"..NameEntry:GetValue().."', '')") scb.playlists_load () scb.showerror ("#scp_playlist_was_successfully_created") if IsValid (ItemPreview) then scb.load_track (scb.gl_info) end else scb.showerror ("#scp_playlist_already_exists") end CrPlstframe:SetVisible (false) end end end function scb.playlist_show (name) if IsValid(PlSListTF) and PlSListTF != nil then PlSListTF:Remove() end PlSListTF = vgui.Create ("DPanel", PlSframe) PlSListTF:SetSize (494,155) PlSListTF:SetPos (0,40) PlSListTF:SetVisible (true) PlSListTF.Paint = function (self,w,h) draw.RoundedBox (0,40,0,w-40,h,CWhite) draw.RoundedBox (0,40,0,w-40,30,CGray) end Namelbl = vgui.Create ("DLabel", PlSListTF) Namelbl:SetPos (40, 0) Namelbl:SetSize (400, 30) Namelbl:SetColor (CWhite) Namelbl:SetFont ("SCRoboto24") Namelbl:SetText (" "..name) BackBut = vgui.Create ("DButton", PlSListTF) BackBut:SetPos (5,0) BackBut:SetSize (30,30) BackBut:SetText ("") BackBut:SetVisible (true) BackBut.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CDarkGray) draw.RoundedBox (0,6,13,20,4,CWhite) surface.SetDrawColor (CWhite) draw.NoTexture () surface.DrawPoly(scb.back1) surface.DrawPoly(scb.back2) end BackBut.DoClick = function () scb.playlists_frame (scb.cl_plst_opened) if IsValid(PlSListTF) and PlSListTF != nil then PlSListTF:SetVisible(false) end if IsValid(TrckListF) and TrckListF != nil then TrckListF:Remove() end end DeleteBut = vgui.Create ("DButton", PlSListTF) DeleteBut:SetPos (5,35) DeleteBut:SetSize (30,30) DeleteBut:SetText ("") DeleteBut:SetVisible (true) DeleteBut.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CDarkGray) surface.SetDrawColor (CWhite) draw.NoTexture () surface.DrawPoly(scb.del1) surface.DrawPoly(scb.del2) end DeleteBut.DoClick = function () scb.playlist_delete (name) end RenameBut = vgui.Create ("DButton", PlSListTF) RenameBut:SetPos (5,70) RenameBut:SetSize (30,30) RenameBut:SetText ("") RenameBut:SetVisible (true) RenameBut.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CDarkGray) draw.RoundedBox (0,6,22,18,1,CWhite) surface.SetDrawColor (CWhite) draw.NoTexture () surface.DrawPoly(scb.ren) end RenameBut.DoClick = function () scb.playlist_rename (name) end TrckListF = vgui.Create ("DScrollPanel", PlSListTF) TrckListF:SetPos (40,35) TrckListF:SetSize (454,120) TrckListF.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CLightGray) end scb.paintscrollbar (TrckListF, CWhite, CLightGray) tempplst = util.JSONToTable (sql.Query ("SELECT Contents FROM soundcloud_player_playlists WHERE Name = '"..name.."'")[1].Contents) PlayAllBut = vgui.Create ("DButton", PlSListTF) PlayAllBut:SetPos (5,105) PlayAllBut:SetSize (30,30) PlayAllBut:SetText ("") PlayAllBut:SetVisible (true) PlayAllBut.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CDarkGray) surface.SetDrawColor (CWhite) draw.NoTexture () surface.DrawPoly(scb.largeplays) end PlayAllBut.DoClick = function () if #tempplst == 0 then return end if scb.settings.admin == 0 then scb.queue = {} l1, l2, l3 = false, false, false for i = 1, #tempplst do http.Fetch ("http://api.soundcloud.com/tracks/"..tempplst[i].."?client_id="..scb.primary_key, function ( body, len, headers, code ) scb.queue[i] = util.JSONToTable(body) if i == 1 then l1 = true end if i == 2 then l2 = true end if l1 and l2 and !l3 then l3 = true scb.play_track (scb.queue[1], "cl") scb.queue_refresh () end end) end else net.Start ("scb_adminplaylist") net.WriteTable (tempplst) net.SendToServer () end end if istable (tempplst) then tltrcks = 0 tpnl = vgui.Create ("Panel", PlSListTF) tpnl:SetSize (494,155) tpnl:SetPos (0,0) tpnl:SetVisible (true) tpnl.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CTWhite) surface.SetDrawColor (CBlack) surface.DrawOutlinedRect (134, 89, 222, 12) draw.RoundedBox (0,135, 90, (tltrcks/#tempplst)*220, 10, CDarkGray) end tlbl = vgui.Create ("DLabel", tpnl) tlbl:SetSize (400, 24) tlbl:SetPos (40, 30) tlbl:SetColor (CDarkGray) tlbl:SetContentAlignment(5) tlbl:SetFont ("SCRoboto24") tnlbl = vgui.Create ("DLabel", tpnl) tnlbl:SetSize (400, 24) tnlbl:SetPos (40, 60) tnlbl:SetColor (CDarkGray) tnlbl:SetContentAlignment(5) tnlbl:SetFont ("SCRoboto24") tpnl.Think = function () tlbl:SetText ("#scp_loading") tnlbl:SetText (tltrcks.."/"..#tempplst) if tltrcks == #tempplst then tpnl:Remove() end end end TrckLine = {} TrckText = {} StrtButton = {} DelButton = {} MoveButton = {} trckinfo = {} if istable (tempplst) then for i = 1, #tempplst do if TrckListF:IsVisible () then http.Fetch ("http://api.soundcloud.com/tracks/"..tempplst[i].."?client_id="..scb.primary_key, function ( body, len, headers, code ) trckinfo[i] = util.JSONToTable(body) TrckLine[i] = vgui.Create ("DPanel", TrckListF) TrckLine[i]:SetPos (0,i*20-18) TrckLine[i]:SetSize (454,18) DelButton[i] = vgui.Create ("DButton", TrckLine[i]) DelButton[i]:SetPos (418, 0) DelButton[i]:SetSize (18,18) DelButton[i]:SetText ("r") DelButton[i]:SetFont ("Marlett") DelButton[i]:SetColor (CWhite) DelButton[i].Paint = function (self, w, h) end DelButton[i].DoClick = function () scb.playlist_deletetrack (name, i) end TrckText[i] = vgui.Create ("DLabel", TrckLine[i]) TrckText[i]:SetPos (5, 0) TrckText[i]:SetSize (400, 18) TrckText[i]:SetColor (CDarkGray) TrckText[i]:SetFont ("SCInterstate14B") if istable(trckinfo[i]) and istable(trckinfo[i].user) then TrckText[i]:SetText (i.." | "..trckinfo[i].user.username.." - "..trckinfo[i].title) StrtButton[i] = vgui.Create ("DButton", TrckLine[i]) StrtButton[i]:SetSize (425,18) StrtButton[i]:SetText ("") StrtButton[i].Paint = function () end StrtButton[i].DoClick = function () scb.load_track (trckinfo[i]) end MoveButton[i] = vgui.Create ("DButton", TrckLine[i]) MoveButton[i]:SetPos (400, 0) MoveButton[i]:SetSize (18,18) MoveButton[i]:SetText ("v") MoveButton[i]:SetFont ("Marlett") MoveButton[i]:SetColor (CWhite) MoveButton[i].Paint = function (self, w, h) end MoveButton[i].DoClick = function () if IsValid(numentry) and numentry != nil then numentry:Remove() else scb.playlist_movetrack (name, i) end end else TrckText[i]:SetText ("#scp_error_reload_playlist") end tltrcks = tltrcks + 1 TrckLine[i].Paint = function (self,w,h) if ( IsValid (StrtButton[i]) and StrtButton[i]:IsHovered() ) or DelButton[i]:IsHovered() or ( IsValid (MoveButton[i]) and MoveButton[i]:IsHovered() ) then draw.RoundedBox (0,2,0,w-4,h,CLightGray) else draw.RoundedBox (0,2,0,w-4,h,CWhite) end end end) end end end end function scb.playlist_delete (name) if IsValid(DlPlstframe) and DlPlstframe != nil then DlPlstframe:SetVisible(false) end DlPlstframe = vgui.Create ("DFrame") DlPlstframe:SetSize(150,70) DlPlstframe:Center() DlPlstframe:SetTitle("") DlPlstframe:SetVisible(true) DlPlstframe:SetDraggable (false) DlPlstframe:ShowCloseButton (false) DlPlstframe:MakePopup() DlPlstframe.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CGray) surface.SetDrawColor(CBlack) surface.DrawOutlinedRect( 0, 0, w, h) end DlLbl = vgui.Create ("DLabel", DlPlstframe) DlLbl:SetPos (0,0) DlLbl:SetSize (150,30) DlLbl:SetColor (CWhite) DlLbl:SetContentAlignment(5) DlLbl:SetFont ("SCRoboto24") DlLbl:SetText ("#scp_are_you_sure") Btn = vgui.Create ("DButton", DlPlstframe) Btn:SetSize (50,25) Btn:SetPos (85,35) Btn:SetFont ("SCRoboto24") Btn:SetColor (CGray) Btn:SetText ("#scp_no") Btn.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CWhite) end Btn.DoClick = function () DlPlstframe:SetVisible (false) end Btn = vgui.Create ("DButton", DlPlstframe) Btn:SetSize (50,25) Btn:SetPos (15,35) Btn:SetFont ("SCRoboto24") Btn:SetColor (CGray) Btn:SetText ("#scp_yes") Btn.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CWhite) end Btn.DoClick = function () sql.Query ("DELETE FROM soundcloud_player_playlists WHERE Name = '"..name.."'") timer.Simple (0.5, function () if IsValid (ItemPreview) then scb.load_track (scb.gl_info) end end) DlPlstframe:SetVisible (false) scb.showerror ("#scp_playlist_was_successfully_deleted") scb.playlists_frame (scb.cl_plst_opened) end end function scb.playlist_rename (name) if IsValid(RnmPlstframe) and RnmPlstframe != nil then RnmPlstframe:SetVisible(false) end RnmPlstframe = vgui.Create ("DFrame") RnmPlstframe:SetSize(300,100) RnmPlstframe:Center() RnmPlstframe:SetTitle("#scp_rename_playlist") RnmPlstframe:SetVisible(true) RnmPlstframe:SetDraggable (false) RnmPlstframe:ShowCloseButton (true) RnmPlstframe:MakePopup() RnmPlstframe.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CGray) surface.SetDrawColor(CBlack) surface.DrawOutlinedRect( 0, 0, w, h) end NameEntry = vgui.Create ("DTextEntry", RnmPlstframe) NameEntry:SetPos (10,30) NameEntry:SetSize (280,20) NameEntry:SetText (name) NameEntry:SetFont ("SCRoboto18") NameEntry.OnEnter = function () if NameEntry:GetValue() == "" then scb.showerror ("#scp_you_cannot_create_playlist_with_this_name") else if sql.Query ("SELECT Contents FROM soundcloud_player_playlists WHERE Name = '"..NameEntry:GetValue().."'") == nil then sql.Query ("INSERT INTO soundcloud_player_playlists (Name, Contents) VALUES ('"..NameEntry:GetValue().."', '')") scb.playlists_load () scb.showerror ("#scp_playlist_was_successfully_created") if IsValid (ItemPreview) then scb.load_track (scb.gl_info) end else scb.showerror ("#scp_playlist_already_exists") end CrPlstframe:SetVisible (false) end end RnmBtn = vgui.Create ("DButton", RnmPlstframe) RnmBtn:SetSize (280,30) RnmBtn:SetPos (10,60) RnmBtn:SetFont ("SCRoboto24") RnmBtn:SetColor (CGray) RnmBtn:SetText ("#scp_rename_playlist") RnmBtn.Paint = function (self,w,h) draw.RoundedBox (0,0,0,w,h,CWhite) end RnmBtn.DoClick = function () if NameEntry:GetValue() == nil then scb.showerror ("#scp_you_cannot_name_playlist_like_that") else if sql.Query ("SELECT Contents FROM soundcloud_player_playlists WHERE Name = '"..NameEntry:GetValue().."'") == nil then sql.Query ("UPDATE soundcloud_player_playlists SET Name = '"..NameEntry:GetValue().."' WHERE Name = '"..name.."'") scb.showerror ("#scp_playlist_was_successfully_renamed") Namelbl:SetText (" "..NameEntry:GetValue()) RnmPlstframe:SetVisible (false) else scb.showerror ("#scp_playlist_already_exists") end end end end function scb.playlist_addtrack (name, id) local tplst = util.JSONToTable (sql.Query ("SELECT Contents FROM soundcloud_player_playlists WHERE Name = '"..name.."'")[1].Contents) if tplst == nil then tplst = {} tplst[1] = id else tplst [#tplst+1] = id end sql.Query ("UPDATE soundcloud_player_playlists SET Contents = '"..util.TableToJSON (tplst).."' WHERE Name = '"..name.."'") scb.showerror ("#scp_done") end function scb.playlist_deletetrack (name, key) local tplst = util.JSONToTable (sql.Query ("SELECT Contents FROM soundcloud_player_playlists WHERE Name = '"..name.."'")[1].Contents) table.remove (tplst, key) sql.Query ("UPDATE soundcloud_player_playlists SET Contents = '"..util.TableToJSON (tplst).."' WHERE Name = '"..name.."'") scb.playlist_show (name) end function scb.playlist_movetrack (name, key1) if IsValid(numentry) and numentry != nil then numentry:Remove() end local tplst = util.JSONToTable (sql.Query ("SELECT Contents FROM soundcloud_player_playlists WHERE Name = '"..name.."'")[1].Contents) numentry = vgui.Create ("DTextEntry", TrckListF) numentry:SetPos (0,key1*20-18) numentry:SetSize (22,18) numentry:SetFont ("SCRoboto16") numentry.OnEnter = function () if !isnumber (tonumber (numentry:GetText())) then scb.showerror ("#scp_this_is_not_a_number") else if tonumber (numentry:GetText()) > #tplst then key2 = #tplst elseif tonumber (numentry:GetText()) < 1 then key2 = 1 else key2 = tonumber (numentry:GetText()) end local cont = tplst[key1] table.remove (tplst, key1) table.insert (tplst, key2, cont) sql.Query ("UPDATE soundcloud_player_playlists SET Contents = '"..util.TableToJSON (tplst).."' WHERE Name = '"..name.."'") scb.playlist_show (name) end end end
7d57c6fbcc07289414af8b9f3951e5d4abc6431a
[ "Markdown", "INI", "Lua" ]
9
Lua
Blueberryy/SoundCloud-Player
9d8fbccb54b95034aa71ba34fdaef303cc0da95a
33d0bc5907dd23c7f73fb7f9dcb55c09c7886053
refs/heads/master
<file_sep>const state={ sliders:[],//首页的轮播 detail_sliders:[],//详情的轮播 hots:[],//首页热单品 disabled:false,//无限滚动指令 shops:[],//首页热店铺, loading:false,//loading组件 nothing:false,//nothing组件 products:[],//我的商品 my_loading:false, my_nothing:false, busy:false,//my的无限滚动指令 list_loading:false, list_nothing:false, list_busy:false,//list的无限滚动指令 list_products:[],//list的商品 icons:[],//收藏图标的样式 } export default state <file_sep>const types={ GET_SLIDERS:'GET_SLIDERS', GET_DETAIL_SLIDERS:'GET_DETAIL_SLIDERS', GET_HOT_PRODUCT:'GET_HOT_PRODUCT', GET_HOT_SHOPS:'GET_HOT_SHOPS', GET_PRODUCT:'GET_PRODUCT', GET_LIST_PRODUCT:'GET_LIST_PRODUCT' } export default types <file_sep># douban 这是一个仿别人的项目,主要用了vue2 + vue-router2 + vuex + axios + el-ui,之前没写过移动端的,就仿了一下,算是一个完整的demo, 除了数据是原作者的,其他都是自己编写的,vue之前用过但是其他的没怎么用过,就像仿个项目试试,包括一些vue的插件,总体来说还是挺好的。 ### 项目地址: (`git clone`) ```shell git clone https://github.com/myLB/douban.git ``` ### 安装 ``` npm install ``` ### 运行 ``` npm run dev ``` ### 技术栈 * vue2 * vue-router2 * vuex * vue-cli * es6/es7 * axios * vue-infinite-scroll * vue-lazyload ### 项目结构 <pre> . ├── README.md ├── build // 构建服务和webpack配置 ├── config // 项目不同环境的配置 ├── index.html // 项目入口文件 ├── package.json // 项目配置文件 ├── test // 没用到 ├── src │   ├── assets // css js 和图片资源 │   ├── components // 各种组件 │   ├── mock // 模拟数据 │   ├── pages // 各页面 │   ├── router // 存放路由的文件夹 │   ├── store // 状态管理store │ ├── App.Vue // 模板文件入口 │   └── main.js // Webpack 预编译入口 │ </pre> <file_sep>import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', component:resolve => require(['../pages/home/home.vue'],resolve), children:[ { path:'', component:resolve => require(['../pages/home/mall.vue'],resolve) }, { path:'classify', name:'classify', component:resolve => require(['../pages/classify/classify.vue'],resolve) }, { path:'cart', name:'cart', component:resolve => require(['../pages/cart/cart.vue'],resolve) }, { path:'my', name:'my', component:resolve => require(['../pages/my/my.vue'],resolve) } ] }, { path:'/login', name:'login', component:resolve => require(['../pages/login/login.vue'],resolve) }, { path:'/details/:id', name:'details', component:resolve => require(['../pages/details/details.vue'],resolve) }, { path:'/list/:id', name:'list', component:resolve => require(['../pages/list/list.vue'],resolve) } ] }) <file_sep>/** * Created by Administrator on 2017/4/10 0010. */
daa6a4938c0b2b984eeecf5107ac35aa77f870a0
[ "JavaScript", "Markdown" ]
5
JavaScript
myLB/douban
4f84d6845a93de36da4eaaf3fda82400f09fd1b4
7768a940dcc3ed4d01ea673e0fd0f4aa2c90c6c7
refs/heads/master
<file_sep>#!/usr/bin/python import time from dotstar import Adafruit_DotStar import random numpixels = 144 # Number of LEDs in strip stepRange = 256 # length of program iteration LEDcolors={'red':0x00FF00, 'green':0xFF0000, 'blue':0x0000FF, 'yellow':0xAAFF00,'pink':0x00FFBB,'white':0xFFFFFF} Wheelcolors={'red':0,'orange':20,'yellow':50,'lime':60,'green':80,'teal':120,'blue':150,'violet':180,'pink':220,'hot pink':250} strip = Adafruit_DotStar(numpixels, 12000000) strip.begin() # Initialize pins for output strip.setBrightness(34) # Limit brightness to ~1/4 duty cycle def Wheel(WheelPos): WheelPos = 255 - WheelPos; if WheelPos < 85: return strip.Color(0,255 - WheelPos * 3, WheelPos * 3) if WheelPos < 170: WheelPos -= 85 return strip.Color(WheelPos * 3, 0, 255 - WheelPos * 3) WheelPos -= 170 return strip.Color(255 - WheelPos * 3, WheelPos * 3, 0) def show(): strip.show() def setAllRGB(r,g,b): for i in range(0,numpixels): strip.setPixelColor(i,r,g,b) def setAll(color): for i in range(0,numpixels): strip.setPixelColor(i,color) def off(): for i in range(0,numpixels): strip.setPixelColor(i,0) strip.show() strip.show() def rainbow(j): for i in range(0,numpixels): strip.setPixelColor(i,Wheel(((i*256//numpixels)+j)&255)) def rainbow_split(j): for i in range(0,numpixels/2): strip.setPixelColor(numpixels/2-1-i, Wheel(((i*256//numpixels)+j)&255)) for k in range(numpixels/2,numpixels): strip.setPixelColor(k, Wheel((((k-numpixels/2)*256//numpixels)+j)&255)) def regular_dots(interval,color): for dot in range(0,numpixels,interval): strip.setPixelColor(dot,color) def moving_dots(interval,color,j): move = j%interval for dot in range(0,numpixels,interval): strip.setPixelColor(dot+move,color) def bottle(position,color,width=3): for pix in range(position-width//2,position+width//2+1): strip.setPixelColor(pix,color) def cylon(step,stepRange,length,color): fraction = (numpixels + length) // (stepRange/2) # set a fraction to scale the lights if step <= stepRange // 2: #let the first half go forward head = step * fraction #scale the starting pixel for pix in range(head-length,head+1): #turn on the range of lights strip.setPixelColor(pix,color) strip.setPixelColor(head-length,0) #turn off the end if step > stepRange // 2: #let the second half go backward head = numpixels - (step * fraction)%(stepRange//2) for pix in range(head-length,head): #turn on the pixels strip.setPixelColor(pix,color) strip.setPixelColor(head,0) #turn off the end #def brightAndDim(step,stepRange): # totRange = stepRange*10 # if step #try: # while True: ## inc = 0 # for step in range(0,stepRange): # rainbow_split(step) # regular_dots(10,Wheel(step)) # regular_dots(20,LEDcolors['blue']) # moving_dots(13,0,step) ## brightAndDim(step + inc*stepRange,stepRange) # show() # time.sleep(.005) ## inc + 1 ## if inc > 9: ## inc = 0 #except: # off() try: while True: for step in range(0,255):#stepRange): rainbow(step) bottle(30,Wheel(Wheelcolors['teal'])) bottle(45,Wheel(Wheelcolors['lime']),4) bottle(70,Wheel(Wheelcolors['red']),7) bottle(36,Wheel(Wheelcolors['teal'])) show() time.sleep(.0075) except: off() #try: # while True: # for col in LEDcolors: # setAll(LEDcolors[col]) # show() # time.sleep(.2) # off() # time.sleep(.1) # # for col in Wheelcolors: # setAll(Wheel(Wheelcolors[col])) # show() # time.sleep(.2) # off() # time.sleep(.1) #except: # off() #
f77ef3247bf9cb2226f8643fafe148c1212beef9
[ "Python" ]
1
Python
IAmBecomeJeff/BarLights
23548a1239c4093427ed0459abea86efc51366b1
bc6c653f3e061fec0bf575f38e0c9bb9e2c11124
refs/heads/master
<repo_name>Ciki/bitfinex-auto-lend<file_sep>/config.local.template.php <?php /** * @internal Called from config.php only * @param array $config * @return array */ function appendLocalConfig(array $config) { $config['api_key'] = '<your api key>'; $config['api_secret'] = '<your secret key>'; return $config; } <file_sep>/config.php <?php // * If there are e.g. total of 12000 swaps at 1%/day and 22000 // swaps at 1.001%/day the script chooses the lower rate, because // we don't want to go beyond the rate of 20000 swaps. include __DIR__ . '/config.local.php'; function getConfig($currency = 'usd') { $config = [ 'usd' => [ 'currency' => 'USD', // Currency to lend 'period' => 2, // Number of days to lend 'minimum_balance' => 50, // Minimum balance to be able to lend (bitfinex constant) 'remove_after' => 50, // Minutes after unexecuted offer gets cancelled 'max_total_swaps' => 20000, // Max number of total swaps to check for a closest rate * ], 'ltc' => [ 'currency' => 'LTC', 'period' => 2, 'minimum_balance' => 8, 'remove_after' => 50, 'max_total_swaps' => 2000, ], 'btc' => [ 'currency' => 'BTC', 'period' => 2, 'minimum_balance' => 0.1, 'remove_after' => 50, 'max_total_swaps' => 50, ], ]; $config = appendLocalConfig($config[$currency]); return $config; } <file_sep>/balances.php <?php require_once(__DIR__ . '/config.php'); require_once(__DIR__ . '/functions.php'); require_once(__DIR__ . '/bitfinex.php'); $config = getConfig(); $bfx = new Bitfinex($config['api_key'], $config['api_secret']); $current_offers = $bfx->get_offers(); $balances = $bfx->get_balances(); $available_balance = 0; $currency = @$_GET['currency'] ? htmlspecialchars($_GET['currency']) : ''; $wallet = @$_GET['wallet'] ? htmlspecialchars($_GET['wallet']) : ''; $limit = @$_GET['limit'] ? (int) htmlspecialchars($_GET['limit']) : 10; $currency_symbol = $currency == 'usd' ? '$' : '&#x0E3F;'; if ($currency && $wallet) { foreach ($balances as $item) { if ($item['type'] == strtolower($wallet) && $item['currency'] == strtolower($currency)) { $available_balance = floatval($item['available']); break; } } message("Available balance on $wallet wallet is $currency_symbol$available_balance"); $history = $bfx->get_history($currency, $limit, $wallet); foreach ($history as $item) { $amount = round($item['amount'], 4); $description = str_replace('Earned fees from user', "Earned $currency_symbol$amount from user", $item['description']); message("$description on " . date('d.m.Y @ H:i:s', $item['timestamp'])); } } else { $total = array(); if ($currency) { $temp = array(); foreach ($balances as $item) { if ($currency == $item['currency']) { $temp[] = $item; @$total["$currency"] += $item['amount']; } } $balances = $temp; } else { foreach ($balances as $item) { @$total[$item['currency']] += $item['amount']; } } $last_acc = ''; ?> <table border="0" cellpadding="4" cellpadding="4"> <thead> <tr> <th>Account</th> <?php foreach ($total as $key => $val) { ?> <th><?= strtoupper($key) ?></th> <?php } ?> </tr> </thead> <tbody> <?php foreach ($balances as $key => $val) { ?> <?php $type = $val['type']; if ($last_acc != $type) { echo '<tr>'; echo '<td>' . ucfirst($type) . '</td>'; $last_acc = $type; } ?> <td align="right"> <?= $val['currency'] != 'usd' ? $val['amount'] : round($val['amount'], 2) ?> </td> <?php if ($last_acc != $type) { echo '</tr>'; } ?> <?php } ?> </tbody> <tfoot> <tr> <td><b>TOTAL</b></td> <?php foreach ($total as $key => $val) { ?> <td align="right"><b><?= $key != 'usd' ? $val : round($val, 2) ?></b></td> <?php } ?> </tr> </tfoot> </table> <?php } ?> <file_sep>/functions.php <?php function d($array, $label = NULL) { echo $label . '<br>'; echo '<pre>'; print_r($array); echo '</pre>'; } function message($message, $level = 'INFO') { echo "$level: $message<br />"; $log = date('d.m.Y H:i:s') . ': ' . $message . "\r\n"; file_put_contents(__DIR__ . "/$level.log", $log, FILE_APPEND); } function daily_rate($rate) { return round($rate / 365, 4); } <file_sep>/lend.php <?php require_once(__DIR__ . '/config.php'); require_once(__DIR__ . '/functions.php'); require_once(__DIR__ . '/bitfinex.php'); $currency = isset($_GET['currency']) ? htmlspecialchars($_GET['currency']) : 'usd'; $config = getConfig($currency); $bfx = new Bitfinex($config['api_key'], $config['api_secret']); $current_offers = $bfx->get_offers(); // Something is wrong most likely API key if (array_key_exists('message', $current_offers)) { message($current_offers['message'], 'ERROR'); exit(1); } d($current_offers, 'offers'); // Remove offers that weren't executed for too long foreach ($current_offers as $item) { $id = $item['id']; $timestamp = (int) $item['timestamp']; $current_timestamp = time(); $diff_minutes = round(($current_timestamp - $timestamp) / 60); if ($config['remove_after'] <= $diff_minutes) { message("Removing offer # $id after {$config['remove_after']} minutes"); $bfx->cancel_offer($id); } } $balances = $bfx->get_balances(); $available_balance = 0; d($balances, 'balances'); if ($balances) { foreach ($balances as $item) { if ($item['type'] === 'deposit' && $item['currency'] === strtolower($config['currency'])) { $available_balance = floatval($item['available']); $totalBalance = floatval($item['amount']); break; } } } // todo: do not lend all money at once // lend fix amount, vary lending period // https://docs.google.com/document/d/1<KEY>edit#heading=h.c8khatrecsgt $lendingAmount = $config['minimum_balance']; $periodMinutes = $config['period'] * 1440; $numberOfLoansPerPeriod = floor($totalBalance / $lendingAmount); $lendingInterval = ceil($periodMinutes / $numberOfLoansPerPeriod); // in minutes // check time since last loan $lastLoanTimeFilepath = __DIR__ . '/.last_loan_time'; $lastLoanTime = file_exists($lastLoanTimeFilepath) ? file_get_contents($lastLoanTimeFilepath) : 0; $timeSinceLastLoan = time() - $lastLoanTime; //d([$lendingAmount, $lendingInterval, $periodMinutes, $numberOfLoansPerPeriod, $timeSinceLastLoan]);die; if ($timeSinceLastLoan < ($lendingInterval * 60)) { message('waiting for lending interval..last loan offer placed before ' . round($timeSinceLastLoan / 60) . ' minutes'); exit(0); } else { // Is there enough balance to lend? // if ($available_balance >= $config['minimum_balance']) { if ($available_balance >= $lendingAmount) { message("Lending availabe balance of $available_balance"); $lendbook = $bfx->get_lendbook($config['currency']); // d($lendbook, 'lendbook'); $offers = $lendbook['asks']; d($offers, 'offers'); $total_amount = 0; $next_rate = 0; $next_amount = 0; $check_next = FALSE; // Find the right rate foreach ($offers as $item) { // Save next closest item if ($check_next) { $next_rate = $item['rate']; $next_amount = $item['amount']; $check_next = FALSE; } $total_amount += floatval($item['amount']); // Possible the closest rate to what we want to lend if ($total_amount <= $config['max_total_swaps']) { $rate = $item['rate']; $check_next = TRUE; } } // Current rate is too low, move closer to the next rate // ??? // if ($next_amount <= $config['max_total_swaps']) { // $rate = $next_rate - 0.01; // } $daily_rate = daily_rate($rate); $daily_next_rate = daily_rate($next_rate); // if there's a gap between current rate & next rate bigger than one `tick` // make the rate as high as possible below the next_rate if ($daily_next_rate - $daily_rate > 0.0001) { $daily_rate = $daily_next_rate - 0.0001; $rate = $daily_rate * 365; } // d([$daily_rate, $rate, $daily_next_rate, $next_rate], 'rates'); // die; $result = $bfx->new_offer($config['currency'], $lendingAmount, (string) $rate, $config['period'], 'lend'); // Successfully lent if (array_key_exists('id', $result)) { message("$lendingAmount {$config['currency']} lent for {$config['period']} days at daily rate of $daily_rate%. Offer id {$result['id']}."); file_put_contents($lastLoanTimeFilepath, time()); } else { // Something went wrong message($result); } } else { message("Balance of $available_balance {$config['currency']} is not enough to lend."); } }
36859ac060198ce6d194b5ee995dae5d18b0a03e
[ "PHP" ]
5
PHP
Ciki/bitfinex-auto-lend
e0a2452371e226fb9502cc402bc441e49feb4d8c
742a625e4b11ec24bf37146443c36ef3f15e94c5
refs/heads/master
<file_sep> // TYPED // TYPED var typed = new Typed('.typed', { strings: ["Bonjour à toutes et à tous, je me présente je m'appelle Walter. Ayant terminé ma formation de développeur web, désireux de relever de nouveaux challenges, je suis à la recherche d'une expérience qui permettra de mettre en avant ma passion et mes connaissances. Passioné, sérieux et organisé, je reste à votre écoute en vue de concrétiser ensemble vos projets."], typeSpeed: 20, }); // COMPTEUR let compteur = 0; $(window).scroll(function() { const top = $('.counter').offset().top - window.innerHeight; if (compteur == 0 && $(window).scrollTop() > top) { $('.counter-value').each(function() { let $this = $(this), countTo = $this.attr('data-count'); $({ countNum : $this.text() }).animate({ countNum : countTo }, { duration: 10000, easing: 'swing', step: function() { $this.text(Math.floor(this.countNum)); }, complete: function() { $this.text(this.countNum); } }); }); compteur = 1; } }); //AOS AOS.init();
890917c95f4985bf8bbba4198856ea80797c97d8
[ "JavaScript" ]
1
JavaScript
darkvador061/site-vitrine
1754a8324cf327146e49c50e123606d419f48660
491a022c145ce1d121d1bd6381d7ddabcb5fff96
refs/heads/master
<file_sep>package com.wy.manage.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.wy.manage.pojo.Goods; public interface GoodsMapper extends BaseMapper<Goods>{ List<Goods> findGoods(@Param("startIndex")Integer startIndex, @Param("pageSize")Integer pageSize); void insertGoods(Goods goods); void updateGoods(Goods goods); void deleteGoodsById(@Param("Ids")Integer... Ids); } <file_sep>package com.wy.manage.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.wy.manage.pojo.SupperType; import com.wy.manage.service.SuperTypeService; import com.wy.manage.vo.JsonResult; import com.wy.manage.vo.PageObject; @RestController public class SuperTypeController { @Autowired private SuperTypeService superTypeService; @RequestMapping("/good/doFindSuperTypes.do") public JsonResult findSuperType() { PageObject<SupperType> superType = superTypeService.findSuperType(); return new JsonResult(superType); } @RequestMapping("/good/doAddSuperType.do") public JsonResult saveSuperType(String typeName) { superTypeService.saveSuperType(typeName); return new JsonResult("save ok"); } @RequestMapping("/good/doDelSuperType.do") public JsonResult doDelSuperType(Integer... ids) { superTypeService.delSuperTypeById(ids); return new JsonResult("delete ok"); } } <file_sep>package com.wy.manage.pojo; import java.io.Serializable; import java.util.Date; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data @TableName("tb_goods") public class Goods implements Serializable{ /** * */ private static final long serialVersionUID = 7696448066195476149L; @TableId(type=IdType.AUTO) private Integer ID; private Integer typeID; private String goodsName; private String introduce; private Double price; private Double nowPrice; private String picture; private Date INTime; private Integer newGoods; private Integer sale; private Integer hit; private Integer stock; } <file_sep>package com.wy.manage.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class PageController { @RequestMapping("/index") public String index() { return "manage/index"; } @RequestMapping("/doGoodsManage.do") public String doGoodsManage() { return "manage/goods_manager"; } @RequestMapping("/doTopGoods.do") public String doTopGoods() { return "manage/topmanage"; } @RequestMapping("/doMemManage.do") public String doMemManage() { return "manage/membermanage"; } @RequestMapping("/doOrderManage.do") public String doOrderManage() { return "manage/ordermanage"; } @RequestMapping("/doPageUI.do") public String doPageUI() { return "common/page"; } @RequestMapping("/goodsma/doGoodsAdd.do") public String doGoodsAdd() { return "manage/goods_add"; } @RequestMapping("/goodsma/doGoodsModify.do") public String doGoodsModify() { return "manage/goods_modify"; } @RequestMapping("/goodsma/doSuperType.do") public String doSuperType() { return "manage/superType"; } @RequestMapping("/goodsma/doAddSuperType.do") public String doAddSuperType() { return "manage/super_add"; } @RequestMapping("/doLogin.do") public String doLogin() { return "manage/Login_M"; } } <file_sep>package com.wy.manage.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.wy.manage.pojo.Goods; import com.wy.manage.service.GoodsService; import com.wy.manage.vo.JsonResult; import com.wy.manage.vo.PageObject; @RestController public class GoodsController { @Autowired private GoodsService goodsService; @RequestMapping("/goods/doFindPageObjects.do") public JsonResult findGoods(Integer pageCurrent) { PageObject<Goods> goods = goodsService.findGoods(pageCurrent); return new JsonResult(goods); } @RequestMapping("/goods/doSaveObject.do") public JsonResult insertGoods(Goods goods) { goodsService.insertGoods(goods); return new JsonResult("添加成功"); } @RequestMapping("/goods/doUpdateObject.do") public JsonResult updateGoods(Goods goods) { goodsService.updateGoods(goods); return new JsonResult("修改成功"); } @RequestMapping("/goods/doDeleteObjects.do") public JsonResult deleteGoods(@RequestParam("ID")Integer... Ids) { goodsService.deleteGoodsById(Ids); return new JsonResult("删除成功"); } }
c6d3891da2a5cdaefdda94fe2acd04b129c804f0
[ "Java" ]
5
Java
zhuwencai/test
96a2012c4f75411ee800de95af54a59769c4eba9
ed7982ba2b0b3d18cf3bdf4081d643b2de944636
refs/heads/develop
<file_sep>README ====== **Twerp is the telephone hackers toolkit.** Legal Notice: Crank calls are only legal if they are funny in some states. Twerp is also: * A tool that will revolutionize crank calling (only legal from California to the French parts of Canada. Note: IANALBISEEOC (I am not a lawyer but I've seen every episode of Cops). * Your own Phone Company. From the command-line! * A command-line interface for the Twilio API Features: * Buy phone numbers from the command-line in the U.S., toll free and wherever Twilio sells them * Manage Twilio accounts: create new sub-accounts, list, rename accouts * Make phone calls from the command-line * Conrtol call flow from the command-line using stateless TwiML transactions (no web app necessary) * Command-line driven conference calls * Send and receive SMS text messages * Read your Twilio logs from the command-line * Modify the flow of calls or conferences in progress with a curses based comand-line interface * Do lots of stuff without going to your dashboard on the twilio.com website TODO: * Plugin system based on Python entry_points * Plugin to launch Bottle web app and localtunnel.com it! * Plugin for Phox Flask webapp * Create API for using alternate interfaces such as urwid to make complete SMS or phone app GUIs. * Make an entire website about what I could do with Twilio+Twerp. .. contents:: Installation ------------ pip install twerp Configure twerp --------------- ~/.twerprc ACCOUNT_SID=a902830980980980ff987yada AUTH_TOKEN=98798asdfas9df87sadf987yada CALLERID=+12135551212 Usage:: ======= Usage: twerp [options] Options: -h, --help show this help message and exit --version Show twerp version and exit. -v, --verbose Show more output stuff. --debug Show debugging information. -q, --quiet Show less output. Common options: These options can be used for both SMS and voice calls. -c CALLERID, --callerid=CALLERID Phone number you are calling from or texting from. -i, --interactive Go into interactive command-line mode after dialing (voice or conferences). Voice call options: Place phone calls, execute TWIML. -d +12135551212,+14155551212, --dial=+12135551212,+14155551212 List of numbers to dial, comma-separated. -y Say something., --say=Say something. Use with --dial to say something. -u URL of TWIML, --url=URL of TWIML URL of TWIML to pass call with --call -b +12135551212, --buy=+12135551212 Buy a specific phone number listed with -x or -a -a AREA CODE, --area-code=AREA CODE Search for phone number to purchase by area code. Use -b to purchase from these results. -x CONTAINS, --contains=CONTAINS Search for phone number to purchase by numbers or letters it contains. Conference (voice) options: These options can be used for voice conference calls. -f +12135551212,+14155551212, --conference=+12135551212,+14155551212 Start conference with list of numbers to dial, comma- separated. -o ROOM, --room=ROOM Room to join for voice conference. -e, --conferences Show conferences in-progress. -p, --conference-participants Show participants for all conferences in-progress. SMS options: Send and reveive SMS text messages. -m <TXT MSG>, --message=<TXT MSG> Send SMS text message -s +12135551212,+14155551212, --sms=+12135551212,+14155551212 Send SMS text message to list of numbers. -l, --list-sms Show incoming SMS messages. Reporting options: List your Twilio phone numbers and information about each. -n, --notifications Show notifications from Twilio API (error messages and warnings). -r, --numbers Show all my Twilio phone numbers. Use -Nv for detailed info on each number. --sid=SID Show log for given SID Applications: Twilio Application information. --applications Show all my Twilio Applications. Accounts: Twilio account and sub-account management --list-accounts List all Twilio accounts and sub-accounts. --create-sub-account=NAME Create sub-account named 'NAME' --rename-sub-account=NAME Rename account or sub-account using 'NAME' Interactive Mode ================ The Prompt ---------- The prompt will have part of the SID if a call is in progress: twerp (CA3abc...) >> If you hang up a call, for example, there will be no SID, so the prompt will look like this: twerp (...) >> Interactive Mode Commands ------------------------- * list - List all calls in progress, ringing or queued * hangup - Hang up call associated with SID shown in prompt * nuke - Hang up all calls associated with account. ALL OF THEM! * forward <nnnnnnnnnn> - Redirect current call to another phone number * url <URL> - Redirect flow of call to TwiML at a URL * info [<SID>] - Show info for current SID or SID given * sid <SID> - Change the current SID associated with interactive-mode Installation ------------ pip install twerp Development ----------- * We're on Freenode #twerp * We're on Twitter @TwerpForTwilio * We're on Github https://github.com/cakebread/twerp * We're on continuous integration a la Jenkins http://cakebread.info:8080 * Fork it, phone it. See http://blog.cakebread.info/ <file_sep> from httplib2 import ServerNotFoundError from mock import Mock, MagicMock, patch from twerp.twilio_support import RestClient def test_send_sms(): real = RestClient() #Normal call real.send_sms = Mock() real.send_sms(['+13233333333'], 'message', False, '+18183333333') def test_send_sms_server_not_found(): real = RestClient() real.send_sms = Mock(side_effect=ServerNotFoundError('Server not found, dude.')).return_value = 2 <file_sep> __version__ = '0.0.6' __all__ = ["twilio_support", "cli"] <file_sep>from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() NEWS = open(os.path.join(here, 'NEWS.txt')).read() version = '0.0.7' install_requires = ['cliff', 'twilio>=3.3.3', 'ConfigObj', 'clint'] setup(name='twerp', version=version, description="Twilio command-line application for sending SMS text messages and making voice calls.", long_description=README + '\n\n' + NEWS, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Topic :: Communications :: Telephony', 'Topic :: Communications :: Internet Phone', 'Topic :: Communications :: Conferencing' ], keywords='twilio sms telephony', author='<NAME>', author_email='<EMAIL>', url='http://github.com/cakebread/twerp', license='BSD', packages=find_packages('src'), package_dir = {'': 'src'},include_package_data=True, zip_safe=False, install_requires=install_requires, entry_points={ 'console_scripts': ['twerp=twerp.cli:main'] } ) <file_sep># PPylint: disable-msg=W0613,W0612,W0212,W0511,R0912,C0322,W0704 # W0511 = XXX (my own todo's) """ cli.py ====== Desc: Command-line module Author: <NAME> <cakebread a t gmail.com> License : BSD """ __docformat__ = 'restructuredtext' import cmd import sys import optparse import logging from urllib import quote_plus from clint.textui import colored from twerp.__init__ import __version__ as VERSION from twerp.twilio_support import RestClient class Interactive(cmd.Cmd): """Cmmand processor""" def __init__(self, client, sid=None): cmd.Cmd.__init__(self) self.sid = sid self.logger = logging.getLogger("twerp") self.client = client def emptyline(self): return def postloop(self): '''Print a blank line after program exits interactive mode''' print '\n' def cmdloop(self, sid=''): intro = "Type 'help' for twerp commands" self.sid = sid if self.sid is not None: self.prompt = "twerp (%s) >> " % self.sid[0:7] else: self.prompt = "twerp (...) >> " try: return cmd.Cmd.cmdloop(self, sid) except KeyboardInterrupt: sys.exit(0) def do_info(self, sid=None): ''' Display info for current SID ''' if not sid: sid = self.sid if sid: self.client.sid_call(sid) else: self.logger.error("Need an SID") def do_hangup(self, arg=None): ''' Hangs up call associated with current SID shown in prompt. ''' self.client.hangup(self.sid) self.prompt = "twerp (...) >> " def do_nuke(self, arg=None): ''' Hangs up all voice calls in progress for the entire account CAUTION: Read the above carefully. ''' self.client.hangup_all_calls() self.prompt = "twerp (...) >> " def do_list(self, args=None): ''' List all calls in progress for your account ''' self.client.list_calls() def do_sid(self, sid): ''' Change SID for interactive session. New SID shows in prompt. ''' if sid: self.sid = sid self.prompt = colored.red("twerp (%s...) >> " % self.sid[0:7]) else: print >> sys.stderr, "You must specify the SID to use." def do_forward(self, number): ''' Forward call to another phone number. e.g. forward +13235551212 ''' if number: url = '''http://twimlets.com/forward?PhoneNumber=''' text = quote_plus(number) url = '%s%s' % (url, number) print url call = self.client.call_url(self.sid, url) #print >> sys.stderr, call.status def do_url(self, url): ''' Redirect call using TwiML at URL e.g. url http://twimlets.com/some.twml ''' if url: call = self.client.call_url(self.sid, url) #print >> sys.stderr, call.status else: print >> sys.stderr, "You need to specify a valid TWML URL e.g. " print >> sys.stderr, \ "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient" def do_EOF(self, line): '''Exit twerp's interactive mode''' return True class Twerp(object): """ Main class for twerp optparse CLI """ def __init__(self): self.options = None self.client = RestClient() def set_log_level(self): """ Set log level according to command-line options @returns: logger object """ log_format = '%(message)s' logging.basicConfig(level=logging.ERROR, format=log_format) logger = logging.getLogger("twerp") if self.options.debug: logger.setLevel(logging.DEBUG) elif self.options.verbose: logger.setLevel(logging.INFO) return logger def run(self): """ Perform actions based on CLI options @returns: status code """ opt_parser = setup_opt_parser() (self.options, remaining_args) = opt_parser.parse_args() self.logger = self.set_log_level() if self.options.numbers: return self.client.list_numbers(self.options.verbose) elif self.options.dial: if not self.options.url and not self.options.say: self.logger.error("You must specify a --url with TwiML " + "or --say something") return 1 numbers = self.options.dial.split(",") sid = self.client.call_numbers(numbers, self.options.verbose, self.options.callerid, self.options.url, self.options.say) if self.options.interactive: Interactive(self.client).cmdloop(sid) return elif self.options.conference: if not self.options.room: self.logger.error("You must specify a --room to join.") return 1 numbers = self.options.conference.split(",") sid = self.client.create_conference(numbers, self.options.room, self.options.verbose, self.options.callerid) if self.options.interactive: Interactive(self.client).cmdloop(sid) return elif self.options.purchase: return self.client.purchase_number(self.options.purchase) elif self.options.contains and self.options.areacode: return self.client.numbers_contain_areacode( self.options.areacode, self.options.contains) elif self.options.contains: return self.client.numbers_contain(self.options.contains) elif self.options.areacode: return self.client.search_numbers(self.options.areacode) elif self.options.rename_account: self.client.rename_account(self.options.rename_account) elif self.options.list_accounts: self.client.list_accounts() elif self.options.rename_account: self.client.create_subaccount(self.options.create_subaccount) elif self.options.applications: return self.client.list_applications() elif self.options.participants: return self.client.list_conference_participants() elif self.options.conferences: return self.client.list_conferences() elif self.options.listsms: return self.client.list_sms() elif self.options.twerp_version: return self.twerp_version() elif self.options.sid: return self.client.get_sms_sid(self.options.sid) elif self.options.sms_recipients: numbers = self.options.sms_recipients.split(",") return self.client.send_sms(numbers, self.options.sms_message, self.options.verbose) elif self.options.notifications: return self.client.notifications(self.options.verbose) elif self.options.interactive: Interactive(self.client).cmdloop('') return else: opt_parser.print_help() return 1 def twerp_version(self): """ Show twerp's version @returns: None """ print("twerp version %s" % VERSION) def setup_opt_parser(): """ Setup the optparser @returns: opt_parser.OptionParser """ usage = "usage: %prog [options]" opt_parser = optparse.OptionParser(usage=usage) opt_parser.add_option("--version", action="store_true", dest="twerp_version", default=False, help="Show twerp version and exit.") opt_parser.add_option("-v", "--verbose", action='store_true', dest="verbose", default=False, help="Show more output stuff.") opt_parser.add_option("--debug", action='store_true', dest="debug", default=False, help="Show debugging information.") opt_parser.add_option("-q", "--quiet", action='store_true', dest="quiet", default=False, help="Show less output.") #Common group_common = optparse.OptionGroup(opt_parser, "Common options", "These options can be used for both SMS and voice calls.") group_common.add_option("-c", "--callerid", action='store', dest="callerid", default=None, help="Phone number you are calling from or texting from.") group_common.add_option("-i", "--interactive", action='store_true', help="Go into interactive command-line mode after " + "dialing (voice or conferences).", dest="interactive", default=False) #SMS group_sms = optparse.OptionGroup(opt_parser, "SMS options", "Send and reveive SMS text messages.") group_sms.add_option("-m", "--message", action='store', metavar="<TXT MSG>", dest="sms_message", default=False, help="Send SMS text message") group_sms.add_option("-s", "--sms", action='store', dest="sms_recipients", default=False, metavar="+12135551212,+14155551212", help="Send SMS text message to list of numbers.") group_sms.add_option("-l", "--list-sms", action='store_true', dest="listsms", default=False, help="Show incoming SMS messages.") #Calls (voice) group_call = optparse.OptionGroup(opt_parser, "Voice call options", "Place phone calls, execute TWIML.") group_call.add_option("-d", "--dial", action='store', metavar="+12135551212,+14155551212", help="List of numbers to dial, comma-separated.", dest="dial", default=False) group_call.add_option("-y", "--say", action='store', metavar="Say something.", dest="say", default=False, help="Use with --dial to say something.") group_call.add_option("-u", "--url", action='store', metavar="URL of TWIML", dest="url", default=False, help="URL of TWIML to pass call with --call") group_call.add_option("-b", "--buy", action='store', dest="purchase", default=False, metavar="+12135551212", help="Buy a specific phone number listed with -x or -a") group_call.add_option("-a", "--area-code", action='store', dest="areacode", default=False, metavar="AREA CODE", help="Search for phone number to purchase by area code. " + "Use -b to purchase from these results.") group_call.add_option("-x", "--contains", action='store', dest="contains", default=False, help="Search for phone number to purchase by numbers " + "or letters it contains.") #Conferences group_conferences = optparse.OptionGroup(opt_parser, "Conference (voice) options", "These options can be used for voice conference calls.") group_conferences.add_option("-f", "--conference", action='store', metavar="+12135551212,+14155551212", help="Start conference with list of numbers to dial, " + "comma-separated.", dest="conference", default=False) group_conferences.add_option("-o", "--room", action='store', dest="room", default=False, help="Room to join for voice conference.") group_conferences.add_option("-e", "--conferences", action='store_true', dest="conferences", default=False, help="Show conferences in-progress.") group_conferences.add_option("-p", "--conference-participants", action='store_true', dest="participants", default=False, help="Show participants for all conferences in-progress.") #Reports group_reports = optparse.OptionGroup(opt_parser, "Reporting options", "List your Twilio phone numbers and information about each.") group_reports.add_option("-n", "--notifications", action='store_true', dest="notifications", default=False, help="Show notifications " + "from Twilio API (error messages and warnings).") group_reports.add_option("-r", "--numbers", action='store_true', dest="numbers", default=False, help="Show all my Twilio phone " + "numbers. Use -rv for detailed info on each number.") group_reports.add_option("--sid", action='store', dest="sid", default=False, help="Show log for given SID") #Applications group_applications = optparse.OptionGroup(opt_parser, "Applications", "Twilio Application information.") group_applications.add_option("--applications", action='store_true', dest="applications", default=False, help="Show all my Twilio Applications.") #Accounts group_accounts = optparse.OptionGroup(opt_parser, "Accounts options", "Twilio account and sub-account management") group_accounts.add_option("--list-accounts", action='store_true', dest="list_accounts", default=False, help="List all Twilio accounts and sub-accounts.") group_accounts.add_option("--create-sub-account", action='store', dest="create_subaccount", metavar="NAME", default=False, help="Create sub-account named 'NAME'") group_accounts.add_option("--rename-sub-account", action='store', dest="rename_account", metavar="NAME", default=False, help="Rename account or sub-account using 'NAME'") opt_parser.add_option_group(group_common) opt_parser.add_option_group(group_call) opt_parser.add_option_group(group_conferences) opt_parser.add_option_group(group_sms) opt_parser.add_option_group(group_reports) opt_parser.add_option_group(group_applications) opt_parser.add_option_group(group_accounts) return opt_parser def main(): """ Let's do it. """ my_twerp = Twerp() return my_twerp.run() if __name__ == "__main__": sys.exit(main()) <file_sep> Welcome to twerp ================ twerp is a command-line utility for making phone calls, conference calls, and sending and receiving SMS text messages with Twilio's API. It is written in Python. Example Usage ============= $ twerp -N List your Twilio phone numbers $ twerp -Nv List lots of details about each of your Twilio numbers: $ twerp -m 'this is a test' -s +12135551212 Send SMS message to +12135551212 $ twerp -d +12135551212 -y "Hi, how are you? This is twerp. Good bye." Call +12135551212 and have <NAME> say "Hi...", then hang up. $ twerp -d +12135551212 -u http://computer.net/twiml.xml Call +12135551212 and execute the TWIML at given URL $ twerp -i -d +12135551212 -u http://computer.net/twiml.xml Call +12135551212 and execute the TWIML at given URL, then go interactive command-line mode. You can then modify the call live with different verbs such as 'url <URL' to re-route calls. $ twerp -d +12135551212,+13235551212 -u http://twimlets.com/conference?Music=rock Call two numbers and put them in a conference room. First one gets rock music till another caller joins. $ twerp -l List all of your SMS messages (Be careful if you have zillions, filtering coming soon) $ twerp -S nnnnnnnnnnnn Show details of SMS message by SID $ twerp -C List all voice conferences in-progress. $ twerp -P List particpants in each voice conferences in-progress. Articles ======== * http://blog.cakebread.info/2012/01/twerp-twilio-command-line-client-for.html Credits ======== * <NAME> - Author <file_sep> """ twiliolib.py ============ Desc: Send and receive SMS or make calls via Twilio REST API Author: <NAME> <<EMAIL>bread @ gmail*com> License : BSD """ __docformat__ = 'restructuredtext' import os import sys import logging from configobj import ConfigObj from urllib import quote_plus from httplib2 import ServerNotFoundError from twilio.rest import TwilioRestClient from twilio import TwilioRestException from twilio.rest.resources import Call from clint.textui import colored, puts, indent try: import simplejson as json except ImportError: import json twerp_config = os.path.join(os.path.expanduser("~"), '.twerprc') if not os.path.exists(twerp_config): print """Create ~/.twerprc with: AUTH_TOKEN = <PASSWORD> ACCOUNT_SID = iowjroiwjeroij CALLER_ID = +12135551212 """ sys.exit(1) config = ConfigObj(twerp_config) AUTH_TOKEN = config['AUTH_TOKEN'] ACCOUNT_SID = config['ACCOUNT_SID'] CALLER_ID = config['CALLER_ID'] URL_CONFERENCE_TWIML = '''http://tinyurl.com/6vyxerr''' #From TwilioRestClient.phone_numbers. NUMBER_IDS = ['account_sid', 'api_version', 'auth', 'base_uri', 'capabilities', 'date_created', 'date_updated', 'friendly_name', 'id_key', 'name', 'phone_number', 'sid', 'sms_application_sid', 'sms_fallback_method', 'sms_fallback_url', 'sms_method', 'sms_url', 'status_callback', 'status_callback_method', 'subresources', 'uri', 'voice_application_sid', 'voice_caller_id_lookup', 'voice_fallback_method', 'voice_fallback_url', 'voice_method', 'voice_url'] class RestClient(object): '''Holds client for REST connection''' def __init__(self, connect=True): self.logger = logging.getLogger("twerp") if connect: self.connect() def connect(self): '''Make a REST client connection to twilio''' self.client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) def rename_account(self, account_name, verbose=False): '''Create Twilio sub-account''' try: account = self.client.accounts.get(ACCOUNT_SID) account.update(friendly_name=account_name) except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 def list_accounts(self): '''List Twilio account and sub-accounts''' try: accounts = self.client.accounts.list() except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: print e.msg return 1 for account in accounts: print account.friendly_name print account.sid print account.status print #print dir(account) def create_subaccount(self, account_name, verbose=False): '''Create Twilio sub-account''' try: apps = self.client.accounts.create(account_name) except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 def list_applications(self, verbose=False): '''Print error messages and warnings from Twilio''' try: apps = self.client.applications.list() except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 for app in apps: print app.friendly_name print "\tSMS URL: %s" % app.sms_url print "\tVoice URL: %s" % app.voice_url print "=" * 79 print def notifications(self, verbose=False): '''Print error messages and warnings from Twilio''' try: notes = self.client.notifications.list() except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 notes.reverse() for notification in notes: print "==" print notification.date_created print notification.call_sid print "Error code: %s" % notification.error_code print "Error msg: %s" % notification.message_text print "Request URL: %s" % notification.request_url print "Error: %s" % notification.log if verbose: print notification.more_info print def list_conference_participants(self): """List all conferences""" try: conferences = self.client.conferences.list(status="in-progress") except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 for conference in conferences: print conference.status print conference.date_created print conference.date_updated print conference.friendly_name print '[' + conference.sid[0:7] + '...]' print '=' * 79 print def list_conferences(self): """List all conferences""" try: conferences = self.client.conferences.list(status="in-progress") except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 for conference in conferences: print conference.status print conference.date_created print conference.date_updated print conference.friendly_name print '[' + conference.sid[0:7] + '...]' print '=' * 79 print for participant in conference.participants.list(): print participant.sid def sid_call(self, sid): """Print results for given SID""" try: call = self.client.calls.get(sid) except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 print 'date: %s' % call.date_created print 'from: %s' % call.from_ print 'to: %s' % call.to print 'status: %s' % call.status print 'direction: %s' % call.direction print def purchase_number(self, number): """Purchase phone number""" try: number = self.client.phone_numbers.purchase(number) except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 def numbers_contain_areacode(self, area_code, contains): """Print numbers available for purchase""" try: numbers = self.client.phone_numbers.search( area_code=area_code, contains=contains) except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 for number in numbers: print number.phone_number print "Zip code: %s" % number.postal_code print "Region: %s" % number.region print "=" * 15 print def numbers_contain(self, contains): """Print numbers available for purchase""" try: numbers = self.client.phone_numbers.search(contains=contains) except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 for number in numbers: print number.phone_number print "Zip code: %s" % number.postal_code print "Region: %s" % number.region print "=" * 15 print def search_numbers(self, area_code): """Print numbers available for purchase""" try: numbers = self.client.phone_numbers.search(area_code=area_code) except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 for number in numbers: print number.phone_number print "Zip code: %s" % number.postal_code print "Region: %s" % number.region print "=" * 15 print def get_sms_sid(self, sid): """Print results for given SID""" try: sms = self.client.sms.messages.get(sid) except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 print('date: %s' % sms.date_sent) print 'from: %s' % sms.from_ print 'to: %s' % sms.to print 'status: %s' % sms.status print 'body: %s' % sms.body print def hangup(self, sid): '''Hangup a call by SID''' try: self.client.calls.hangup(sid) print "Call hung up." print except TwilioRestException, e: msg = json.loads(e.msg) print msg["message"] return 1 def hangup_all_calls(self): '''Call a URL/Twimlet''' try: calls = self.client.calls.list(status=Call.IN_PROGRESS) except TwilioRestException, e: msg = json.loads(e.msg) #print msg["message"] self.logger.error(msg) return 1 self.logger.info("Checking for calls in progress...") for c in calls: print "Hung up IN_PROGRESS SID: %s From:%s" % (c.sid, c.from_) c.hangup() try: calls = self.client.calls.list(status=Call.RINGING) except TwilioRestException, e: msg = json.loads(e.msg) #print msg["message"] self.logger.error(msg) return 1 self.logger.info("Checking for calls that are ringing...") for c in calls: print "Hung up RINGING SID: %s From:%s" % (c.sid, c.from_) c.hangup() self.logger.info("Checking for calls that are queued...") try: calls = self.client.calls.list(status=Call.QUEUED) except TwilioRestException, e: msg = json.loads(e.msg) #print msg["message"] self.logger.error(msg) return 1 for c in calls: print "Hung up QUEUED SID: %s From:%s" % (c.sid, c.from_) c.hangup() print def list_calls(self): '''List calls IN_PROGRESS, RINGING, or QUEUED''' try: calls = self.client.calls.list(status=Call.IN_PROGRESS) except TwilioRestException, e: msg = json.loads(e.msg) #print msg["message"] self.logger.error(msg) return 1 for c in calls: print "SID: %s" % c.sid print "From: %s" % c.from_ #print "Answered by: %s" % c.answered_by #This always shows None, maybe we can't get till call ends print "Status: %s" % c.status print "Direction: %s" % c.direction print "Start: %s" % c.start_time try: calls = self.client.calls.list(status=Call.RINGING) except TwilioRestException, e: msg = json.loads(e.msg) #print msg["message"] self.logger.error(msg) return 1 for c in calls: print "Ringing: %s" % c.sid try: calls = self.client.calls.list(status=Call.QUEUED) except TwilioRestException, e: msg = json.loads(e.msg) #print msg["message"] self.logger.error(msg) return 1 for c in calls: print "Queued: %s" % c.sid def create_conference(self, recipients, room, verbose=False, callerid=CALLER_ID): """ callerid: string recipients: list of strings representing each phone number """ if callerid is None: callerid = CALLER_ID my_url = URL_CONFERENCE_TWIML.replace('ROOM_NAME', room) self.logger.debug(my_url) for phone in recipients: self.logger.info("Placing call to: %s" % phone) try: call = self.client.calls.create(to=phone, from_=callerid, url=my_url) except ServerNotFoundError, e: self.logger.error(e) return except TwilioRestException, e: self.logger.error(e) return self.logger.info("Status: %s" % call.status) self.logger.debug("SID: %s" % call.sid) return call.sid def call_numbers(self, recipients, verbose=False, callerid=CALLER_ID, url=None, say=None): """ callerid: string recipients: list of strings representing each phone number """ if callerid is None: callerid = CALLER_ID if say: url = '''http://twimlets.com/message?Message%5B0%5D=''' text = quote_plus(say) url = '%s%s' % (url, text) for phone in recipients: self.logger.info("Placing call to: %s" % phone) try: call = self.client.calls.create(to=phone, from_=callerid, url=url) except ServerNotFoundError, e: self.logger.error(e) return None except TwilioRestException, e: self.logger.error(e) return None self.logger.info("Status: %s" % call.status) self.logger.info("SID: %s" % call.sid) return call.sid def send_sms(self, recipients, message, verbose=False, callerid=CALLER_ID): """ callerid: string recipients: list of strings representing each phone number message: Text to send via SMS""" for phone in recipients: print("PHONE", phone) try: message = self.client.sms.messages.create(to=phone, from_=callerid, body=message) except ServerNotFoundError, e: print e return 1 except TwilioRestException, e: print e return 1 if verbose: print("Status: %s" % message.status) print("SID: %s" % message.sid) print("From: %s" % message.from_) def list_numbers(self, verbose=False): """List all my Twilio numbers""" try: for number in self.client.phone_numbers.iter(): puts('%s [%s]' % (number.phone_number, number.friendly_name)) if verbose: with indent(4, quote=colored.blue(' >')): for id in NUMBER_IDS: puts("%s: %s" % (colored.green(id), getattr(number, NUMBER_IDS[NUMBER_IDS.index(id)]))) except ServerNotFoundError, e: self.logger.error(e) return 1 def list_sms(self): """ Retrieve list of all sms messages TODO: Add filtering for from, to and date """ try: messages = self.client.sms.messages.list() except ServerNotFoundError, e: self.logger.error(e) return 1 except TwilioRestException, e: print e return 1 messages.reverse() for message in messages: print "%s t:%s f:%s sid:%s\n\t%s" % (message.date_sent, message.to, message.from_, message.sid, message.body) <file_sep>[tox] envlist = py267,py271,py272 [testenv] changedir=tests deps= mock pytest commands=py.test --junitxml=junit-{envname}.xml [testenv:py271] basepython=/var/lib/jenkins/.pythonbrew/pythons/Python-2.7.1/bin/python2.7 [testenv:py272] basepython=/var/lib/jenkins/.pythonbrew/pythons/Python-2.7.2/bin/python2.7 [testenv:py267] basepython=/var/lib/jenkins/.pythonbrew/pythons/Python-2.6.7/bin/python2.6
67a92e651213881f2ff6b61ad9c1e967cf171f82
[ "Python", "reStructuredText", "INI" ]
8
reStructuredText
cakebread/twerp
86cdcc64b619b01f2893aa11c9a63eb998ce34ad
01d9be2566849ee29e2f9a20f1e2e5cebd5184c6
refs/heads/master
<repo_name>ctrung/interview-java<file_sep>/README.md ## 1.5 ### Generics See [dedicated page](generics) ## 9 ### Jigsaw - modules See [dedicated page](modules) ### Process API (new) Before 9, OS specific ```java // like int pid = Integer.parseInt(new File("/proc/self").getCanonicalFile().getName()); // or Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "echo $PPID"}); if (proc.waitFor() == 0) { InputStream in = proc.getInputStream(); String pid = new String(in.readAllBytes()); System.out.println("PID - " + pid); } ``` From 9, new classes *java.lang.ProcessHandler* and *java.lang.ProcessHandler.Info* are portable. ```java ProcessHandle.allProcesses() .filter(p -> p.info().command().isPresent()) .limit(5) .forEach(p -> { System.out.println("PID - " + p.pid()); System.out.println("Command - " + p.info().command().orElse(null)); System.out.println("Command-line - " + p.info().commandLine().orElse(null)); System.out.println("Command-args - " + Arrays.toString(p.info().arguments().orElse(null))); System.out.println("Start-time - " + p.info().startInstant().orElse(null)); System.out.println("Total-CPU-duration - " + p.info().totalCpuDuration().orElse(null)); System.out.println("User - " + p.info().user().orElse(null) + "\n"); }); ``` <file_sep>/generics/src/generics/RawTypePitfall.java package generics; import java.util.ArrayList; import java.util.List; /** * Backward compatibility : raw types supported but compiler won't detect runtime errors. * * @author clement.trung */ public class RawTypePitfall { public static void main(String[] args) { List<String> stringList = new ArrayList<>(); stringList.add("hello"); stringList.add("world"); List rawList = stringList; // warning: unchecked conversion rawList.add(1); // warning: unchecked call List rawList2 = new ArrayList(); rawList2.add(1); stringList = rawList2; System.out.println("rawList = " + rawList); for (String s : stringList) { System.out.println(s); // runtime error on the 3rd item in the list // java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String } } }<file_sep>/generics/README.md # java-generics [<< summary](../README.md) ##### Raw types allowed but compilation won't detect runtime errors ```java List<String> stringList = ... List rawList = stringList; // warning: unchecked conversion rawList.add(1); // warning: unchecked call for (String s : stringList) { ... } // java.lang.ClassCastException ``` ##### Multiple bounded types allowed but class must be declared before interfaces ```java Class A { /* ... */ } interface B { /* ... */ } interface C { /* ... */ } class D <T extends B & A & C> { /* ... */ } // compile-time error ``` ##### Inheritance pitfall `Box<Integer>` is not a subtype of `Box<Number>` even though `Integer` is a subtype of `Number` ```java public void boxTest(Box<Number> n) { /* ... */ } Box<Integer> intBox = ... boxTest(intBox) // compile-time error ``` ##### Bridge methods These are introduced during type erasure to ensure polymorphism ```java public class Node { public Object data; public Node(Object data) { this.data = data; } public void setData(Object data) { System.out.println("Node.setData"); this.data = data; } } public class MyNode extends Node { public MyNode(Integer data) { super(data); } public void setData(Integer data) { System.out.println("MyNode.setData"); super.setData(data); } } ``` after type erasure, it becomes ```java class MyNode extends Node { // Bridge method generated by the compiler // // java.lang.ClassCastException might occur in Runtime : stacktrace will point out to this method but at line where this class is declared ! public void setData(Object data) { setData((Integer) data); } public void setData(Integer data) { System.out.println("MyNode.setData"); super.setData(data); } // ... } ``` ##### Non-Reifiable Types A reifiable type is a type whose type information is fully available at runtime. This includes primitives, non-generic types, raw types, and invocations of unbound wildcards. Non-reifiable types are types where information has been removed at compile-time by type erasure. ##### Heap pollution Heap pollution occurs when a variable of a parameterized type refers to an object that is not of that parameterized type. This situation occurs if the program performed some operation that gives rise to an unchecked warning at compile-time. ##### Potential Vulnerabilities Varargs Methods with Non-Reifiable Formal Parameters It will generate a heap pollution warning at the vargargs method declaration ```java public static <T> void addToList (List<T> listArg, T... elements) { // warning: [varargs] Possible heap pollution from parameterized vararg type T // the code below is fine for (T x : elements) { listArg.add(x); } } public static void faultyMethod(List<String>... l) { // warning: [varargs] Possible heap pollution from parameterized vararg type T // the code below is bad Object[] objectArray = l; // Valid objectArray[0] = Arrays.asList(42); String s = l[0].get(0); // ClassCastException thrown here } ``` ##### Arrays The component type of an array object may not be a type variable or a parameterized type, unless it is an (unbounded) wildcard type. You can declare array types whose element type is a type variable or a parameterized type, but not array objects. ```java // not allowed List<String>[] lsa = new List<String>[10]; // OK, array of unbounded wildcard type. List<?>[] lsa = new List<?>[10]; // Error. List<String>[] lsa = new List<?>[10]; ``` ##### Generics restrictions * Cannot Instantiate Generic Types with Primitive Types * Cannot Create Instances of Type Parameters ```java public static <E> void append(List<E> list) { E elem = new E(); // compile-time error list.add(elem); } ``` as a workaround ```java public static <E> void append(List<E> list, Class<E> cls) throws Exception { E elem = cls.newInstance(); // OK list.add(elem); } ``` * Cannot Declare Static Fields Whose Types are Type Parameters Because a static field is common to all instance of the class, if it were allowed, for different type parameters, the static field would have multiple types at the same time. * Cannot Use Casts or instanceof With Parameterized Types * Cannot Create Arrays of Parameterized Types * Cannot Create, Catch, or Throw Objects of Parameterized Types A generic class cannot extend the Throwable class directly or indirectly. For example, the following classes will not compile: ```java // Extends Throwable indirectly class MathException<T> extends Exception { /* ... */ } // compile-time error // Extends Throwable directly class QueueFullException<T> extends Throwable { /* ... */ // compile-time error ``` A method cannot catch an instance of a type parameter: ```java public static <T extends Exception, J> void execute(List<J> jobs) { try { for (J job : jobs) // ... } catch (T e) { // compile-time error // ... } } ``` You can, however, use a type parameter in a throws clause: ```java class Parser<T extends Exception> { public void parse(File file) throws T { // OK // ... } } ``` * Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type <file_sep>/modules/README.md # Java 9 modules [<< summary](../README.md) ### Commands #### Listing ```sh > java --list-modules #lists the JDK’s set of modules java.activation@9.0.1 java.base@9.0.1 java.compiler@9.0.1 java.corba@9.0.1 java.datatransfer@9.0.1 ``` #### Compilation ``` > javac -d mods/com.deitel.welcome src/com.deitel.welcome/module-info.java src/com.deitel.welcome/com/deitel/welcome/Welcome.java ``` **-d** : output directory #### Description ``` > java --module-path mods --describe-module <module> ``` **--module-path** : list of module locations (ie. jar, exploded-module folder) ``` > java --module-path mods --describe-module com.deitel.welcome com.deitel.welcome pathContainingModsFolder/mods/com.deitel.welcome/ requires java.base contains com.deitel.welcome ``` #### Running a module ``` > java --module-path <module locations> --module <module>/<fully qualified main class> ``` **--module** : module name and the fully qualiied class name of the app’s entry point Example ``` > java --module-path mods --module com.deitel.welcome/com.deitel.welcome.Welcome ``` #### Packaging a jar file ``` > jar --create -f jars/com.deitel.welcome.jar --main-class com.deitel.welcome.Welcome -C mods/com.deitel.welcome ``` **-C** : which folder contains the files that should be included in the JAR and is followed by the files to include #### Running a jar file ```sh # entry point specified during jar creation > java --module-path jars com.deitel.welcome > java -p jars -m com.deitel.welcome # no entry point specified during jar creation, explicitely specifying the module name and fully qualiied class name > java --module-path jars com.deitel.welcome/com.deitel.welcome.Welcome > java -p jars -m com.deitel.welcome/com.deitel.welcome.Welcome ``` ### Glossary * **module descriptor** : module-info.class * **module declaration** : module-info.java * **module A read module B** : module A requires module B * **exploded-module folder** : structure folders containing the compiled code ### Module directives Keyword | Description | Example ------- | ----------- | ------- module | module | ```module <modulename> { }``` requires | dependency | ```requires <modulename>;``` requires static | dependency at compile time only | ```requires static <modulename>;``` requires transitive | other modules reading your module also read that dependency | ```requires transitive <modulename>;``` exports | speciies one of the module’s packages whose public types should be accessible to code in all other modules | ```exports com.package;``` exports...to | specify in a comma-separated list precisely which module’s or modules’ code can access the exported package | uses | a service used by this module (a service is an object of a class that implements the interface or extends the abstract class speciied in the uses directive) | ```uses com.package.MyService;``` provides...with | inverse of uses. a module provides a service implementation—making the module a service provider | open, opens, and opens...to | allowing runtime-only access to a package (including reflection) | ```opens package ```<br><br> ```opens package to comma-separated-list-of-modules ```<br><br> ```open module modulename { } ``` ### App structure ``` <AppFolder> |__src |__<ModuleNameFolder> |__<PackageFolders> | |__<JavaSourceCodeFiles> |__module-info.java ```
a1bc76a31e394a2e05abe57e770c9c710b8822bb
[ "Markdown", "Java" ]
4
Markdown
ctrung/interview-java
84107f5fc3134b11a85940a9dc7309b0baa35e07
df78fa747b4e80b61f053b09c327e3adc982e66f
refs/heads/master
<file_sep># NetworkSystem 发送接收网络信息 ````c# public class NetworkTest : MonoBehaviour, IEventHandler { public void HandlerEvent(EventBase eventid) { EventData<Package> msg = (EventData<Package>)eventid; Debug.Log(BitConverter.ToInt32(msg.args[0].msg, 0)); } void Start() { print(NetworkManager.Instance.ToString()); EventManager.Instance.Registration(HandlerEvent, MessageType.login); Send(); } void Send() { Package package = new Package("127.0.0.1", 60000, (int)MessageType.login, BitConverter.GetBytes(12)); EventData<Package>.CreateEvent(PackageDir.send, package).Send(); } } ````<file_sep>using System; using System.Collections.Generic; using UnityEngine; public class EventManager:Singleton<EventManager> { private Dictionary<Enum, Action<EventBase>> HandlerList = new Dictionary<Enum, Action<EventBase>>(); public void SendEvent(EventBase eventBase) { HandlerList[eventBase.eid].Invoke(eventBase); } /// <summary> /// 注册监听者 /// </summary> /// <param name="e"></param> /// <param name="action"></param> public void Registration(Enum e, Action<EventBase> action) { if (!HandlerList.ContainsKey(e)) { HandlerList.Add(e, action); } else { HandlerList[e] += action; } } /// <summary> /// 注册监听者(监听多个Enum) /// </summary> /// <param name="action"></param> /// <param name="enums"></param> public void Registration(Action<EventBase> action,params Enum[] enums) { for (int i = 0; i < enums.Length; i++) { Registration(enums[i], action); } } /// <summary> /// 注销监听者 /// </summary> public void Cancellation(Enum e, Action<EventBase> action) { if (HandlerList.ContainsKey(e)) { HandlerList[e] -= action; } } public void Cancellation(Action<EventBase> action,params Enum[] enums) { for (int i = 0; i < enums.Length; i++) { Cancellation(enums[i], action); } } } public interface IEventHandler { void HandlerEvent(EventBase eventid); }<file_sep>public enum MessageType { Test1,Test2,Test3 }<file_sep>using UnityEngine; using System.Collections; using System; public class EventData<T> : EventBase { public T[] args = null; public EventData(Enum eid, params T[] args) { this.eid = eid; this.args = args; } public static EventData<T> CreateEvent(Enum e, params T[] args) { EventData<T> eventBase = new EventData<T>(e, args); return eventBase; } } public class EventData:EventBase { public object args = null; public EventData(Enum eid, params object[] args) { this.eid = eid; this.args = args; } public static EventData CreateEvent(Enum e, params object[] args) { EventData eventBase = new EventData(e, args); return eventBase; } } public class EventBase { public Enum eid; public void Send() { if (EventManager.Instance != null) EventManager.Instance.SendEvent(this); } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using UnityEngine; public class Network { private const int BUFF_SIZE = 128; public class UDPClient { UdpClient client; public void Init(string ip="127.0.0.1",int port=60000) { client = new UdpClient(); client.Connect(ip, port); client.BeginReceive(Receive, client); } public void Send(Package package) { byte[] msgBytes = package.Pack(); client.Send(msgBytes, msgBytes.Length); } private void Receive(IAsyncResult ar) { UdpClient u = (UdpClient)ar.AsyncState; IPEndPoint e = new IPEndPoint(IPAddress.Any, 0); byte[] receiveBytes = u.EndReceive(ar, ref e); new EventData<Package>(PackageDir.receive, new Package().UnPack(receiveBytes)).Send(); client.BeginReceive(Receive, client); } public void Close() { client.Close(); } } public class UDPServer { UdpClient server; public void Init(int port = 60000) { server = new UdpClient(port); //ThreadPool.QueueUserWorkItem(Receive); server.BeginReceive(Receive, server); } private void Receive(IAsyncResult ar) { UdpClient u = (UdpClient)ar.AsyncState; IPEndPoint e = new IPEndPoint(IPAddress.Any, 0); byte[] receiveBytes = u.EndReceive(ar, ref e); new EventData<Package>(PackageDir.receive, new Package().UnPack(receiveBytes)).Send(); server.BeginReceive(Receive, server); } } public class TCPClient { private TcpClient tcpclient = null; byte[] result; public void Init(string ip,int port=60001) { tcpclient = new TcpClient(); //连接服务器 tcpclient.BeginConnect(IPAddress.Parse(ip), port, ConnectCallback, tcpclient); } /// <summary> /// 连接回调 /// </summary> /// <param name="ar"></param> private void ConnectCallback(IAsyncResult ar) { TcpClient client = (TcpClient)ar.AsyncState; try { if (client.Connected) { //连接成功 client.EndConnect(ar); //开始接受数据 ReceiveData(client); } } catch (Exception e) { Debug.Log("ConnectCallback:" + e.Message); } } /// <summary> /// 接收数据 /// </summary> /// <param name="client"></param> private void ReceiveData(TcpClient client) { NetworkStream stream = client.GetStream(); result = new byte[client.Available]; try { stream.BeginRead(result, 0, result.Length, ReadCallBack, stream); } catch (Exception e) { Debug.Log("ReceiveData:" + e.Message); } } /// <summary> /// 接受消息回调 /// </summary> /// <param name="ar"></param> private void ReadCallBack(IAsyncResult ar) { NetworkStream stream; try { stream = (NetworkStream)ar.AsyncState; stream.EndRead(ar); byte[] sizeData = new byte[4]; stream.Read(sizeData, 0, sizeData.Length); int size = BitConverter.ToInt32(sizeData,0); byte[] data = new byte[size]; stream.Read(data, 0, data.Length); EventData<Package>.CreateEvent(PackageDir.receive,new Package().UnPack(data)).Send(); } catch (IOException e) { Debug.Log("远程服务器关闭"+e.Message); } } /// <summary> /// 发送消息 /// </summary> /// <param name="data"></param> public void Send(Package package) { if (tcpclient.Connected) { NetworkStream stream = tcpclient.GetStream(); byte[] data = package.Pack(); stream.BeginWrite(data, 0, data.Length, SendCallback, stream); } } /// <summary> /// 发送消息回调 /// </summary> /// <param name="ar"></param> private void SendCallback(IAsyncResult ar) { NetworkStream stream = (NetworkStream)ar.AsyncState; stream.EndWrite(ar); } } public class TCPServer { private TcpListener server; byte[] buffer = new byte[1024]; /// <summary> /// 接受消息 /// </summary> List<byte> receiveDataList = new List<byte>(); public void Init(int port=60001) { server = new TcpListener(new IPEndPoint(IPAddress.Any, port)); //开启侦听,最多只能连接20个客户端数目 server.Start(20); server.BeginAcceptSocket(ClientConnect, server); } /// <summary> /// 客户端连接 /// </summary> /// <param name="ar"></param> private void ClientConnect(IAsyncResult ar) { try { TcpListener listener = (TcpListener)ar.AsyncState; Socket client = listener.EndAcceptSocket(ar); Debug.Log(client.RemoteEndPoint.ToString() + "连接成功"); //侦听结束后开始接收数据 ReceiveData(client); //重新侦听是否有新的客户端连接 //如果这里不写 那么只能侦听一次 server.BeginAcceptSocket(ClientConnect, server); } catch (Exception e) { Debug.Log("ClientConnect" + e.Message); } } /// <summary> /// 接受数据的回调 /// </summary> /// <param name="client"></param> private void ReceiveData(Socket client) { SocketError socketError; client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, out socketError, ReceiveCallback, client); } /// <summary> /// 一次接收的数据的长度 /// </summary> int receLen = 0; private void ReceiveCallback(IAsyncResult ar) { try { SocketError socketError; Socket client = (Socket)ar.AsyncState; receLen = client.EndReceive(ar, out socketError); if (receLen > 0) { lock (receiveDataList) { //处理接收到的数据 OnReceiveData(client); } } else//当receLen<=0的时候表示客户端断开和服务器的连接 { Debug.Log(client.LocalEndPoint.ToString() + "关闭了"); } //重新接受数据 ReceiveData(client); } catch (Exception e) { Debug.Log("ReceiveCallback:" + e.Message + " " + e.StackTrace); } } /// <summary> /// 接受数据 /// </summary> /// <param name="socket"></param> private void OnReceiveData(Socket socket) { byte[] tempArr = new byte[receLen]; Array.Copy(buffer, tempArr, receLen); receiveDataList.AddRange(tempArr); if (receiveDataList.Count >= 4) { byte[] dataArray = receiveDataList.GetRange(0, 4).ToArray(); //int len = BitConverter.ToInt32(dataArray, 0); int len = NetworkUtils.ByteArray2Int(dataArray, 0); //Debug.Log("receiveDataList: " + receiveDataList.Count+" == ?"+len); if (receiveDataList.Count >= len) { Package package = new Package(); package.UnPack(receiveDataList.ToArray()); EventData<Package>.CreateEvent(PackageDir.receive, package).Send(); } } } /// <summary> /// 发送数据 /// </summary> /// <param name="socket"></param> /// <param name="data"></param> public void Send(Socket socket,Package package) { SocketError socketError; byte[] data = package.Pack(); socket.BeginSend(data, 0, data.Length, SocketFlags.None, out socketError, SendCallBack, socket);//异步发送数据 } /// <summary> /// 发送数据的回调 /// </summary> /// <param name="ar"></param> private void SendCallBack(IAsyncResult ar) { SocketError socketError; Socket client = (Socket)ar.AsyncState; client.EndSend(ar, out socketError); } } } public enum PackageDir { send=100,receive }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EventTest : MonoBehaviour, IEventHandler { /// <summary> /// 事件处理器 /// </summary> /// <param name="eventid"></param> public void HandlerEvent(EventBase eventid) { EventData<string> eventData = (EventData<string>)eventid; print("user:"+eventData.args[0] +" password:"+ eventData.args[1]); } /// <summary> /// 订阅事件 /// </summary> private void Start() { EventManager.Instance.Registration(HandlerEvent, MessageType.Test1); Send(); } /// <summary> /// 发送事件 /// </summary> private void Send() { EventData<string>.CreateEvent(MessageType.Test1, "<PASSWORD>", "<PASSWORD>").Send(); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class Test : MonoBehaviour, IEventHandler { public Texture2D texture; public void HandlerEvent(EventBase eventid) { switch ((MessageType)eventid.eid) { case MessageType.Test1: print("wo " + (eventid as EventData<Package>).args[0].GetString()); break; case MessageType.Test2: print("wo " + (eventid as EventData<Package>).args[0].GetString()); break; default: break; } } private void Start() { NetworkManager.Instance.Registration(HandlerEvent, MessageType.Test1, MessageType.Test2); } private void Update() { if (Input.GetKeyUp(KeyCode.Space)) { Package package = new Package( 0, "test"); EventData<Package>.CreateEvent(PackageDir.send, package).Send(); Package package1 = new Package((int)MessageType.Test2, "哈哈哈啊哈哈哈哈哈哈啊哈哈哈哈哈哈啊哈哈哈哈哈"); EventData<Package>.CreateEvent(PackageDir.send, package1).Send(); } } } <file_sep>using System; using System.Linq; using System.Net; using System.Text; using UnityEngine; public class Package { public static int messageIndex = 0; //总的消息编号 //------------------------------包内容------------------------------------------------- public int size; //包大小 public int type; //消息类型 public int index; //当前消息编号 public byte[] msg; //真正的消息 private byte[] fullData; //编码过后的信息 //小松只有9分了 /// <summary> /// 初始化包 /// </summary> public Package() { type = 0; index = 0; msg = null; } /// <summary> /// 初始化包 /// </summary> /// <param name="ip">IP地址</param> /// <param name="port">端口号</param> /// <param name="type">消息类型</param> /// <param name="msg">消息体</param> public Package(int type, byte[] msg) { Format(type, msg); } /// <summary> /// 初始化包 /// </summary> /// <param name="ip">IP地址</param> /// <param name="port">端口号</param> /// <param name="type">消息类型</param> /// <param name="msg">消息体</param> public Package(int type, string msg) { Format(type, Encoding.UTF8.GetBytes(msg)); } /// <summary> /// 初始化包 /// </summary> /// <param name="ip">IP地址</param> /// <param name="port">端口号</param> /// <param name="type">消息类型</param> /// <param name="msg">消息体</param> public Package(int type, int msg) { Format(type, BitConverter.GetBytes(msg)); } /// <summary> /// 格式化消息 /// </summary> /// <param name="ip">IP地址</param> /// <param name="port">端口号</param> /// <param name="type">消息类型</param> /// <param name="msg">消息体</param> private void Format(int type, byte[] msg) { this.type = type; this.index = messageIndex; this.msg = msg; Pack(); } public string GetString() { if (msg == null) return ""; return Encoding.UTF8.GetString(msg); } public int GetInt() { if (msg == null) return 0; return BitConverter.ToInt32(msg, 0); } /// <summary> /// 编码 /// </summary> /// <returns></returns> public byte[] Pack() { byte[] packHead = new byte[4 * 3]; size = msg.Length + packHead.Length; //3个int(4)型数据 size type index //包大小 packHead[0] = (byte)((size >> 24)); packHead[1] = (byte)((size >> 16)); packHead[2] = (byte)((size >> 8)); packHead[3] = (byte)(size); //包类型 packHead[4] = (byte)((type >> 24)); packHead[5] = (byte)((type >> 16)); packHead[6] = (byte)((type >> 8)); packHead[7] = (byte)(type); //包编号 packHead[8] = (byte)((index >> 24)); packHead[9] = (byte)((index >> 16)); packHead[10] = (byte)((index >> 8)); packHead[11] = (byte)(index); fullData = packHead.Concat(msg).ToArray(); return fullData; } public int GetLength() { if (size == 0) { Debug.Log("消息没有打包 Pack()"); return 0; } else { return size; } } public Package UnPack() { UnPack(fullData); return this; } public Package UnPack(byte[] bytes) { size = (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3]; type = (bytes[4] << 24) + (bytes[5] << 16) + (bytes[6] << 8) + bytes[7]; index = (bytes[8] << 24) + (bytes[9] << 16) + (bytes[10] << 8) + bytes[11]; msg = new byte[bytes.Length - 12]; Array.Copy(bytes, 12, msg, 0, msg.Length); return this; } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class NetworkManager : Singleton<NetworkManager>, IEventHandler { //private Queue<Package> packages = new Queue<Package>(); private Network.UDPClient udpClient; private Network.UDPServer udpServer; private Network.TCPClient tcpClient; private Network.TCPServer tcpServer; protected override void InitSingleton() { EventManager.Instance.Registration(HandlerEvent, PackageDir.send, PackageDir.receive); udpClient = new Network.UDPClient(); udpServer = new Network.UDPServer(); tcpClient = new Network.TCPClient(); tcpServer = new Network.TCPServer(); udpServer.Init(); tcpServer.Init(); udpClient.Init("127.0.0.1"); tcpClient.Init("127.0.0.1"); } /// <summary> /// 注册监听者 /// </summary> /// <param name="e"></param> /// <param name="action"></param> public void Registration(Enum e, Action<EventBase> action) { EventManager.Instance.Registration(e, action); } /// <summary> /// 注册监听者(监听多个Enum) /// </summary> /// <param name="action"></param> /// <param name="enums"></param> public void Registration(Action<EventBase> action, params Enum[] enums) { for (int i = 0; i < enums.Length; i++) { Registration(enums[i], action); } } /// <summary> /// 注销监听者 /// </summary> public void Cancellation(Enum e, Action<EventBase> action) { EventManager.Instance.Registration(e, action); } /// <summary> /// 注销多个监听者 /// </summary> /// <param name="action"></param> /// <param name="enums"></param> public void Cancellation(Action<EventBase> action, params Enum[] enums) { for (int i = 0; i < enums.Length; i++) { Cancellation(enums[i], action); } } public void HandlerEvent(EventBase eventid) { switch ((PackageDir)eventid.eid) { case PackageDir.send: Send((EventData<Package>)eventid); break; case PackageDir.receive: Receive((EventData<Package>)eventid); break; default: break; } } private void Receive(EventData<Package> msg) { //Debug.Log(msg.args[0].type); foreach (var item in msg.args) { //Debug.Log((MessageType)item.type); EventData<Package>.CreateEvent((MessageType)item.type, item).Send(); } } private void Send(EventData<Package> msg) { foreach (Package item in msg.args) { if (item.size >= 1024) { tcpClient.Send(item); Debug.Log("从TCP发送"); } else { udpClient.Send(item); Debug.Log("从UDP发送"); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class NetworkTest : MonoBehaviour, IEventHandler { public void HandlerEvent(EventBase eventid) { EventData<Package> msg = (EventData<Package>)eventid; switch ((MessageType)msg.eid) { case MessageType.Test1: Debug.Log("Int: "+msg.args[0].GetInt()); break; case MessageType.Test2: Debug.Log("Bytes: " + msg.args[0].msg.Length); break; case MessageType.Test3: Debug.Log("String: " + msg.args[0].GetString()); break; default: break; } } void Start() { print(NetworkManager.Instance.ToString()); EventManager.Instance.Registration(HandlerEvent, MessageType.Test1,MessageType.Test2,MessageType.Test3); Send(); } void Send() { //int Package intPack = new Package((int)MessageType.Test1, 12); EventData<Package>.CreateEvent(PackageDir.send, intPack).Send(); //小字节数组 Package smallByteArrayPack = new Package((int)MessageType.Test2, new byte[10]); EventData<Package>.CreateEvent(PackageDir.send, smallByteArrayPack).Send(); //大字节数组 Package bigByteArrsyPack = new Package((int)MessageType.Test2, new byte[1024000]); EventData<Package>.CreateEvent(PackageDir.send, bigByteArrsyPack).Send(); //字符串 Package stringPack = new Package((int)MessageType.Test3, "test"); EventData<Package>.CreateEvent(PackageDir.send, stringPack).Send(); } } <file_sep>namespace NetWorkEvent { internal class NetReceive { private object p; public NetReceive(object p) { this.p = p; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class tttt : MonoBehaviour { //123456 private int[] bytes=new int[1024]; private int[] tmp=new int[1012]; // Start is called before the first frame update void Start() { DateTime startTime = DateTime.Now; for (int i = 0; i < 10000000; i++) { Array.Copy(bytes, 12, tmp, 0, 1012); } print((DateTime.Now - startTime).ToString()); } // Update is called once per frame void Update() { } public static byte[] Int2ByteArray(int value) { byte[] buffer = new byte[4]; buffer[0] = (byte)((value >> 24)); buffer[1] = (byte)((value >> 16)); buffer[2] = (byte)((value >> 8)); buffer[3] = (byte)(value); return buffer; } } <file_sep>using System.Collections; using System.Collections.Generic; using System.Net; using UnityEngine; public class NetworkUtils { public static IPAddress GetLocalIP() { IPAddress AddressIP=IPAddress.Any; foreach (IPAddress iPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (iPAddress.AddressFamily.ToString() == "InterNetwork") { return iPAddress; } } return AddressIP; } public static string GetLocalIPString() { return GetLocalIP().ToString(); } public static byte[] Int2ByteArray(int value) { byte[] buffer = new byte[4]; buffer[0] = (byte)((value >> 24)); buffer[1] = (byte)((value >> 16)); buffer[2] = (byte)((value >> 8)); buffer[3] = (byte)(value); return buffer; } public static int ByteArray2Int(byte[] bytes,int startIndex) { return (bytes[startIndex] << 24) + (bytes[startIndex + 1] << 16) + (bytes[startIndex + 2] << 8) + bytes[startIndex + 3]; } }
4572b0ed56bc9e69570abd9be5ef4beb440548e1
[ "Markdown", "C#" ]
13
Markdown
wenanlee/NetSystem
45394fbbd0671412aa8cf0c576f7178031befd31
87ff19867b1c3c6d38c2b93c34e62002d7cbdd5b
refs/heads/master
<file_sep>const WHITE_KEYS = ['z', 'x', 'c', 'v', 'b', 'n', 'm'] const BLACK_KEYS = ['s', 'd', 'f', 'g', 'h'] const keys = document.querySelectorAll('.key') const whiteKeys = document.querySelectorAll('.key.white') const blackKeys = document.querySelectorAll('.key.black') keys.forEach(key => { key.addEventListener('click', () => playNote(key)) }) document.addEventListener('keydown', e => { if(e.repeat) return const key = e.key const whiteKeyIndex = WHITE_KEYS.indexOf(key) const blackKeyIndex = BLACK_KEYS.indexOf(key) if(whiteKeyIndex > -1) playNote(whiteKeys[whiteKeyIndex]) if(blackKeyIndex > -1) playNote(blackKeys[blackKeyIndex]) }) function playNote(key) { const noteAudio = document.getElementById(key.dataset.note) noteAudio.currentTime=0 noteAudio.play() key.classList.add('active') noteAudio.addEventListener('ended', () => { key.classList.remove('active') }) } document.addEventListener('keydown', event => { //const keyCode = event.key switch (event.keyCode) { case 090: // z setBackgroundColor('red'); break; case 088: // x setBackgroundColor('green'); break; case 67: // c setBackgroundColor('blue'); break; case 086: // v setBackgroundColor('yellow'); break; case 66: // b setBackgroundColor('black'); break; case 78: // n setBackgroundColor('white'); break; case 77: // m setBackgroundColor('purple'); break; case 083: // s setBackgroundColor('aqua'); break; case 068: //d setBackgroundColor('grey'); break; case 70: //f setBackgroundColor('brown'); break; case 71: //g setBackgroundColor('pink'); break; case 72: //h setBackgroundColor('gold') } }); function setBackgroundColor(color) { document.querySelector('body').style.backgroundColor = color; }<file_sep># JS-Piano Simple Piano using JavaScript
93a65ea81e0713c11fd3af1db36eba224dba0471
[ "JavaScript", "Markdown" ]
2
JavaScript
Girum-Haile/JS-Piano
d2562bbf722f36ebb4c1d5176da8f208989b7340
479eea62ecb9c45f391641c2a7b50257e9cdc745
refs/heads/master
<repo_name>tkkhuu/TrafficSignClassifier<file_sep>/traffic_classifier.py import TKDNNUtil.DNNBuilder as DNNBuilder from DataLoaderTSC import DataLoaderTSC from keras.utils import to_categorical data_loader = DataLoaderTSC() # Preparing data train_file = '../traffic-signs-data/train.p' valid_file = '../traffic-signs-data/valid.p' test_file = '../traffic-signs-data/test.p' train = data_loader.LoadPickleData(train_file) valid = data_loader.LoadPickleData(valid_file) test = data_loader.LoadPickleData(test_file) X_train, y_train = train['features'], train['labels'] X_valid, y_valid = valid['features'], valid['labels'] X_test, y_test = test['features'], test['labels'] print("Succesfully imported data\n") # Store data properties into variables n_train = X_train.shape[0] n_validation = X_valid.shape[0] n_test = X_test.shape[0] image_shape = X_train[0].shape n_classes = 43 BATCH_SIZE = 16 EPOCHS = 8 print('Train data shape: {}'.format(X_train.shape)) print('Train label shape: {}'.format(y_train.shape)) print('Number of training examples: {}'.format(n_train)) print('Number of validation examples: {}'.format(n_validation)) print('Number of testing examples: {}'.format(n_test)) print('Image data shape: {}'.format(image_shape)) print('Number of classes: {}\n'.format(n_classes)) one_hot_y_train = to_categorical(y_train, num_classes=n_classes) one_hot_y_valid = to_categorical(y_valid, num_classes=n_classes) train_generator = data_loader.GenerateTrainingBatch((X_train, one_hot_y_train)) valid_generator = data_loader.GenerateTrainingBatch((X_valid, one_hot_y_valid)) def normalize(data): return (data - 128.0) / 128.0 traffic_dnn_layers = ( {'layer_type': 'lambda', 'function': normalize}, {'layer_type': 'convolution', 'shape': (5, 5, 16), 'padding': 'valid', 'activation': 'relu'}, {'layer_type': 'convolution', 'shape': (5, 5, 32), 'padding': 'valid', 'activation': 'relu'}, {'layer_type': 'dropout', 'keep_prob': 0.4}, {'layer_type': 'flatten'}, {'layer_type': 'dropout', 'keep_prob': 0.4}, {'layer_type': 'fully connected', 'units': 400, 'activation': 'relu'}, {'layer_type': 'fully connected', 'units': 120, 'activation': 'relu'}, {'layer_type': 'fully connected', 'units': 84, 'activation': 'relu'}, {'layer_type': 'fully connected', 'units': n_classes, 'activation': 'softmax'} ) print('Creating Network ...') traffic_dnn = DNNBuilder.DNNSequentialModelBuilder2D({'input_shape': X_train.shape[1:], 'model_architecture': traffic_dnn_layers}) print('Initializing Network ...') traffic_dnn.Initialize() print('Compiling Network ...') traffic_dnn.Compile('categorical_crossentropy', 'adam') print('Training Network ...') traffic_dnn.FitGenerator(train_generator, validation_data=valid_generator, steps_per_epoch=n_train, validation_steps=n_validation, epochs=EPOCHS) print('Evaluate Model ...') traffic_dnn.Evaluate(X_valid, y_valid) <file_sep>/DataLoaderTSC.py from TKDNNUtil.DataLoader import DataLoader from sklearn.utils import shuffle import numpy as np class DataLoaderTSC(DataLoader): def GenerateTrainingBatch(self, samples, batch_size=32, flip_images=False, side_cameras=False): train_samples = samples[0] label_samples = samples[1] num_samples = len(train_samples) while 1: # Loop forever so the generator never terminates X, y = shuffle(train_samples, label_samples) for offset in range(0, num_samples, batch_size): train_batch = train_samples[offset:offset+batch_size] label_batch = label_samples[offset:offset+batch_size] X_train = np.array(train_batch) y_train = np.array(label_batch) yield shuffle(X_train, y_train)
26b47fb21c4d2fa5c63ab85214c6c3360eb5d3c9
[ "Python" ]
2
Python
tkkhuu/TrafficSignClassifier
8405c608d95cf37214f0ed044f6e4c523d0bc4c4
44391a710b7622a57ee93cec849411d17c69b240
refs/heads/main
<file_sep>#include "ticket_topic_choose_state_processor.h" #include "../translate.h" #include "../context.h" #include <Poco/Logger.h> #include <Poco/JSON/Parser.h> #include <inttypes.h> #include <regex> namespace NOctoshell { TReactions TTicketTopicChooseStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("ticket_topic_choose_processor").information("on_start from user %" PRIu64, update.UserId); TReaction reaction; const std::string response = Ctx_.Octoshell().SendQueryWithAuth(state, {{"method", "topics"}}); Poco::JSON::Parser parser; auto result = parser.parse(response); auto object = result.extract<Poco::JSON::Object::Ptr>(); std::string status = object->getValue<std::string>("status"); if (status == "fail") { reaction.Text = "main.fail-auth"; } else { reaction.Text = "main.tickets.topics.message"; const std::string locale = state.language() == TUserState_ELanguage_EN ? "en" : "ru"; auto topicsArr = object->getArray("topics"); for (size_t i = 0; i < topicsArr->size(); ++i) { auto topic = topicsArr->getObject(i); reaction.Keyboard.push_back({topic->getValue<std::string>("name_" + locale)}); } } reaction.Keyboard.push_back({"auth.button.back"}); return {std::move(reaction)}; } TReactions TTicketTopicChooseStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { auto& logger = Poco::Logger::get("ticket_topic_choose_processor"); logger.information("on_update from user %" PRIu64, update.UserId); const std::string code = TryGetTemplate(update.Text, state.language(), Ctx_.Translate()); logger.information("Pressed button is \"%s\"", code); // user wants to exit if (code == "auth.button.back") { state.set_state(TUserState_EState_MAIN_MENU); return {}; } // user selected the topic (we suppose that he clicked at the menu) (*state.mutable_extradata())["topic"] = update.Text; state.set_state(TUserState_EState_TICKET_CLUSTER_CHOOSE); return {}; } } // namespace NOctoshell <file_sep>#include "auth_settings_state_processor.h" #include "../auth_status.h" #include "../context.h" #include "../translate.h" #include <Poco/Logger.h> #include <inttypes.h> #include <sstream> namespace NOctoshell { namespace { std::string ConstructShowSettingsText(const TUserState& state) { std::stringstream ss; ss << "auth.settings.header" << std::endl; ss << "auth.settings.email" << ": " << (state.email().empty() ? "auth.blank-email" : state.email()) << std::endl; ss << "auth.settings.token" << ": " << (state.token().empty() ? "auth.blank-token" : state.token()) << std::endl; return ss.str(); } TReaction ConstructShowSettingsReaction(const TUserState& state) { TReaction reaction; reaction.Text = ConstructShowSettingsText(state); return reaction; } } // namespace TReactions TAuthSettingsStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("auth_settings_processor").information("on_start from user %" PRIu64, update.UserId); const static TReaction::TKeyboard keyboardTemplate = { {"auth.button.change-email", "auth.button.change-token"}, {"auth.button.show-settings"}, {"auth.button.check-connection"}, {"auth.button.back"}, }; TReaction reaction; reaction.Text = "auth.message"; reaction.Keyboard = keyboardTemplate; return {std::move(reaction)}; } TReactions TAuthSettingsStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { auto& logger = Poco::Logger::get("auth_settings_processor"); logger.information("on_update from user %" PRIu64, update.UserId); const std::string code = TryGetTemplate(update.Text, state.language(), Ctx_.Translate()); logger.information("Pressed button is \"%s\"", code); if (code == "auth.button.change-email") { state.set_state(TUserState_EState_AUTH_NEW_EMAIL); return {}; } if (code == "auth.button.change-token") { state.set_state(TUserState_EState_AUTH_NEW_TOKEN); return {}; } if (code == "auth.button.show-settings") { return {ConstructShowSettingsReaction(state)}; } if (code == "auth.button.check-connection") { const EAuthStatus authStatus = TryAuth(Ctx_.Octoshell(), state); TReaction reaction; reaction.Text = AuthToTemplateMap.at(authStatus); return {std::move(reaction)}; } if (code == "auth.button.back") { state.set_state(TUserState_EState_MAIN_MENU); return {}; } return {}; } } // namespace NOctoshell <file_sep>#pragma once #include <string> #include <Poco/JSON/Object.h> #include <proto/user_state.pb.h> #include "../model.h" #include "../fwd.h" namespace NOctoshell { class IClient { public: IClient(TContext& ctx) : Ctx_{ctx} {} virtual ~IClient() = default; virtual TUpdate ParseUpdate(const Poco::JSON::Object& data) const = 0; virtual void SendReaction(const TUpdate& update, const TReaction& reaction) const = 0; virtual TUserState_ESource Source() const = 0; protected: TContext& Ctx_; }; } // namespace NOctoshell <file_sep>#include "telegram.h" #include "util.h" #include "../context.h" #include <Poco/Logger.h> #include <Poco/URI.h> #include <Poco/Net/HTTPSClientSession.h> #include <Poco/Net/HTTPRequest.h> #include <Poco/Net/HTTPResponse.h> using namespace Poco::Net; namespace NOctoshell { namespace { Poco::JSON::Object ConstructReplyMarkup(const TReaction::TKeyboard& keyboard) { Poco::JSON::Object markup; markup.set("resize_keyboard", true); Poco::JSON::Array keyboardArr; for (const auto& row : keyboard) { Poco::JSON::Array keyboardRow; for (const auto& text : row) { Poco::JSON::Object button; button.set("text", text); keyboardRow.add(button); } keyboardArr.add(keyboardRow); } markup.set("keyboard", keyboardArr); return markup; } std::string ConstructReplyMarkupJson(const TReaction::TKeyboard& keyboard) { auto obj = ConstructReplyMarkup(keyboard); std::stringstream ss; obj.stringify(ss); return ss.str(); } } // namespace TUpdate TTelegramClient::ParseUpdate(const Poco::JSON::Object& data) const { Poco::Logger::get("telegram").information("parsing telegram update"); TUpdate update; if (data.has("message")) { auto msg = data.getObject("message"); if (msg->has("from")) { update.UserId = msg->getObject("from")->getValue<std::uint64_t>("id"); } if (msg->has("text")) { update.Text = msg->getValue<std::string>("text"); } } return update; } void TTelegramClient::SendReaction(const TUpdate& update, const TReaction& reaction) const { auto& logger = Poco::Logger::get("telegram"); logger.information("send telegram reaction"); auto msgs = DivideMessage(reaction.Text, Ctx_.Config().getInt("telegram.msg_size")); for (const std::string& msg : msgs) { std::stringstream ss; ss << "https://api.telegram.org/bot" << Ctx_.Config().getString("telegram.token") << "/sendMessage"; ss << "?chat_id=" << std::to_string(update.UserId); ss << "&text=" << UrlQuote(msg, /* escapeUnderscore = */ true); if (!reaction.Keyboard.empty()) { ss << "&reply_markup=" << UrlQuote(ConstructReplyMarkupJson(reaction.Keyboard), /* escapeUnderscore = */ true); } if (reaction.ForceReply) { ss << "&reply_markup=" << R"({"force_reply":true})"; } ss << "&parse_mode=markdown"; Poco::URI uri{UrlQuote(ss.str())}; std::string path(uri.getPathAndQuery()); if (path.empty()) { path = "/"; } HTTPSClientSession session(uri.getHost(), uri.getPort()); HTTPRequest request(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1); session.sendRequest(request); HTTPResponse response; std::istream& rs = session.receiveResponse(response); std::stringstream responseStream; responseStream << rs.rdbuf(); logger.information("sendMessage response: code %d, reason %s, body %s", static_cast<int>(response.getStatus()), response.getReason(), responseStream.str()); } } TUserState_ESource TTelegramClient::Source() const { return TUserState_ESource_TELEGRAM; } } // namespace NOctoshell <file_sep>#include "main_menu_state_processor.h" #include "../translate.h" #include "../context.h" #include <Poco/Logger.h> #include <Poco/JSON/Parser.h> #include <inttypes.h> #include <sstream> namespace NOctoshell { namespace { std::string GetStringSafe(Poco::JSON::Object::Ptr json, const std::string& key, const std::string defaultValue = "<empty>") { try { return json->getValue<std::string>(key); } catch (...) { return defaultValue; } } TReaction ConstructInformationReaction() { TReaction reaction; reaction.Text = "main.information"; return reaction; } TReaction ConstructUserProjectsReaction(TOctoshell& octoshell, const TUserState& state) { TReaction reaction; const std::string response = octoshell.SendQueryWithAuth(state, {{"method", "user_projects"}}); Poco::JSON::Parser parser; auto result = parser.parse(response); auto object = result.extract<Poco::JSON::Object::Ptr>(); std::string status = object->getValue<std::string>("status"); if (status == "fail") { reaction.Text = "main.fail-auth"; } else { auto projArr = object->getArray("projects"); std::vector<Poco::JSON::Object::Ptr> projVector(projArr->size()); for (size_t i = 0; i < projArr->size(); ++i) { projVector[i] = projArr->getObject(i); } std::sort(projVector.begin(), projVector.end(), [](const Poco::JSON::Object::Ptr& a, const Poco::JSON::Object::Ptr& b) -> bool { if (a->has("updated_at") && b->has("updated_at")) { return a->getValue<std::string>("updated_at") > b->getValue<std::string>("updated_at"); } else if (a->has("updated_at")) { return true; } else if (b->has("updated_at")) { return false; } else { return a->getValue<std::string>("title") > b->getValue<std::string>("title"); } }); std::stringstream ss; ss << "main.projects.header " << projArr->size() << "\n"; for (size_t i = 0; i < projVector.size(); ++i) { auto proj = projVector[i]; if (proj->has("state")) { std::string state = proj->getValue<std::string>("state"); if (state == "blocked" || state == "finished") { continue; } } ss << "\n"; ss << "main.projects.number" << i + 1 << "\n"; ss << "main.projects.login " << "\"" << proj->getValue<std::string>("login") << "\"\n"; ss << "main.projects.title " << "\"" << proj->getValue<std::string>("title") << "\"\n"; if (proj->has("state")) { std::string state = proj->getValue<std::string>("state"); ss << "main.projects.state: *" << state << "*\n"; } if (proj->getValue<bool>("owner")) { ss << "main.projects.is-owner" << "\n"; } else { ss << "main.projects.is-not-owner" << "\n"; } if (proj->has("updated_at")) { ss << "main.projects.updated-at" << ": `" << proj->getValue<std::string>("updated_at") << "`\n"; } } reaction.Text = ss.str(); } return reaction; } TReaction ConstructUserJobsReaction(TOctoshell& octoshell, const Poco::Util::PropertyFileConfiguration& config, const TUserState& state) { const size_t maxJobs = config.getInt("octoshell.max_user_jobs"); TReaction reaction; const std::string response = octoshell.SendQueryWithAuth(state, { {"method", "user_jobs"}, {"limit", std::to_string(maxJobs)}, }); Poco::JSON::Parser parser; auto result = parser.parse(response); auto object = result.extract<Poco::JSON::Object::Ptr>(); std::string status = object->getValue<std::string>("status"); if (status == "fail") { reaction.Text = "main.fail-auth"; } else { auto jobsArr = object->getArray("jobs"); std::vector<Poco::JSON::Object::Ptr> jobsVector(jobsArr->size()); for (size_t i = 0; i < jobsArr->size(); ++i) { jobsVector[i] = jobsArr->getObject(i); } std::sort(jobsVector.begin(), jobsVector.end(), [](const Poco::JSON::Object::Ptr& a, const Poco::JSON::Object::Ptr& b) -> bool { return a->getValue<int>("id") > b->getValue<int>("id"); }); std::stringstream ss; if (object->has("jobs_count")) { ss << "main.jobs.header: " << object->getValue<int>("jobs_count") << "\n\n"; } else { ss << "main.jobs.header: " << jobsArr->size() << "\n\n"; } for (size_t i = 0; i < std::min(jobsVector.size(), maxJobs); ++i) { auto& job = jobsVector[i]; if (job->has("id")) { ss << "main.jobs.number" << " *" << job->getValue<int>("id") << "*"; if (job->has("state")) { ss << " (" << "main.jobs.state" << " *" << job->getValue<std::string>("state") << "*)"; } ss << "\n"; } if (job->has("submit_time")) { ss << "main.jobs.submitted" << ": `" << job->getValue<std::string>("submit_time") << "`\n"; } if (job->has("state")) { const std::string state = job->getValue<std::string>("state"); if (state != "PENDING") { if (job->has("start_time")) { ss << "main.jobs.started" << ": `" << job->getValue<std::string>("start_time") << "`\n"; } if (job->has("end_time")) { ss << "main.jobs.ended" << ": `" << job->getValue<std::string>("end_time") << "`\n"; } } } if (job->has("get_duration_hours")) { ss << "main.jobs.duration-hours" << ": " << job->getValue<double>("get_duration_hours") << "\n"; } if (job->has("num_cores") && job->has("num_nodes")) { ss << "main.jobs.num-nodes" << ": " << job->getValue<int>("num_nodes") << ", "; ss << "main.jobs.num-cores" << ": " << job->getValue<int>("num_cores") << "\n"; } if (job->has("rules")) { std::stringstream rulesSs; const auto rules = job->getObject("rules"); for (const auto& pair : *rules) { rulesSs << pair.second.extract<std::string>() << "; "; } const std::string rulesStr = rulesSs.str(); if (!rulesStr.empty()) { ss << "main.jobs.rules" << ": " << rulesStr; } } if (job->has("command")) { ss << "\n" << "main.jobs.command" << ": `" << job->getValue<std::string>("command") << "`\n"; } ss << "\n\n"; } reaction.Text = ss.str(); } return reaction; } TReaction ConstructTicketsReaction(TOctoshell& octoshell, const Poco::Util::PropertyFileConfiguration& config, const TUserState& state) { const size_t maxTickets = config.getInt("octoshell.max_user_tickets"); auto& logger = Poco::Logger::get("main_menu_processor"); TReaction reaction; const std::string response = octoshell.SendQueryWithAuth(state, { {"method", "user_tickets"}, {"limit", std::to_string(maxTickets)}, }); Poco::JSON::Parser parser; auto result = parser.parse(response); auto object = result.extract<Poco::JSON::Object::Ptr>(); std::string status = object->getValue<std::string>("status"); if (status == "fail") { reaction.Text = "main.fail-auth"; } else { auto ticketsArr = object->getArray("tickets"); int ticketsCount = 0; std::stringstream ss; if (object->has("tickets_count")) { ss << "main.tickets.header" << " " << object->getValue<int>("tickets_count") << "\n"; } else { ss << "main.tickets.header" << " " << ticketsArr->size() << "\n"; } for (size_t i = 0; i < std::min(ticketsArr->size(), 2 * maxTickets); ++i) { try { auto ticket = ticketsArr->getObject(i); const std::string locale = state.language() == TUserState_ELanguage_EN ? "en" : "ru"; const std::string who = "main.tickets.who-is-" + ticket->getValue<std::string>("who"); const std::string topicName = GetStringSafe(ticket, "topic_name_" + locale); const std::string projectTitle = GetStringSafe(ticket, "project_title"); const std::string clusterName = GetStringSafe(ticket, "cluster_name_" + locale); const std::string subject = ticket->getValue<std::string>("subject"); const std::string message = ticket->getValue<std::string>("message"); const std::string state = ticket->getValue<std::string>("state"); ss << "\n"; ss << "main.tickets.number" << ticketsCount + 1 << "\n"; ss << "main.tickets.who-status" << ": " << who << "\n"; ss << "main.tickets.topic-title" << ": " << topicName << "\n"; ss << "main.tickets.project-title" << ": " << projectTitle << "\n"; ss << "main.tickets.cluster-title" << ": " << clusterName << "\n"; ss << "main.tickets.subject-title" << ": " << subject << "\n"; ss << "main.tickets.state-title" << ": " << "main.tickets.state." << state << "\n"; ss << "main.tickets.desc" << ": " << message << "\n"; if (ticket->has("updated_at")) { ss << "main.tickets.updated-at" << ": `" << ticket->getValue<std::string>("updated_at") << "`\n"; } ++ticketsCount; } catch (...) { logger.warning("skip ticket %d", i); } } reaction.Text = ss.str(); } return reaction; } } // namespace TReactions TMainMenuStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("main_menu_processor").information("on_start from user %" PRIu64, update.UserId); const static TReaction::TKeyboard keyboardTemplate = { {"main.button.show-user-projects", "main.button.show-user-jobs"}, {"main.button.show-tickets", "main.button.create-tickets"}, {"main.button.to-auth-settings"}, {"main.button.to-locale-settings"}, {"main.button.information"}, }; TReaction reaction; reaction.Text = "main.message"; reaction.Keyboard = keyboardTemplate; return {std::move(reaction)}; } TReactions TMainMenuStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { auto& logger = Poco::Logger::get("main_menu_processor"); logger.information("on_update from user %" PRIu64, update.UserId); const std::string code = TryGetTemplate(update.Text, state.language(), Ctx_.Translate()); logger.information("Pressed button is \"%s\"", code); if (code == "main.button.to-auth-settings") { state.set_state(TUserState_EState_AUTH_SETTINGS); return {}; } if (code == "main.button.show-user-projects") { return {ConstructUserProjectsReaction(Ctx_.Octoshell(), state)}; } if (code == "main.button.show-user-jobs") { return {ConstructUserJobsReaction(Ctx_.Octoshell(), Ctx_.Config(), state)}; } if (code == "main.button.show-tickets") { return {ConstructTicketsReaction(Ctx_.Octoshell(), Ctx_.Config(), state)}; } if (code == "main.button.create-tickets") { state.set_state(TUserState_EState_TICKET_PROJECT_CHOOSE); return {}; } if (code == "main.button.to-locale-settings") { state.set_state(TUserState_EState_LOCALE_SETTINGS); return {}; } if (code == "main.button.information") { return {ConstructInformationReaction()}; } return {}; } } // namespace NOctoshell <file_sep>#pragma once #include "state_processor.h" namespace NOctoshell { class TTicketSubjectChooseStatesProcessor final : public IStatesProcessor { public: using IStatesProcessor::IStatesProcessor; TReactions OnStart(TUpdate update, TUserState& state) override; TReactions OnUpdate(TUpdate update, TUserState& state) override; }; } // namespace NOctoshell <file_sep>#include "util.h" #include <regex> namespace NOctoshell { std::string UrlQuote(std::string s, bool escapeUnderscore) { s = std::regex_replace(s, std::regex(" "), "%20"); s = std::regex_replace(s, std::regex("\n"), "%0A"); s = std::regex_replace(s, std::regex("\r"), "%0D"); std::string res; if (escapeUnderscore) { bool inCode = false; for (const auto c : s) { if (c == '`') { inCode = !inCode; } if (c == '_' && !inCode) { res += "\\"; } res += c; } } else { res = s; } return res; } std::vector<std::string> DivideMessage(const std::string& msg, size_t msgSize) { std::vector<std::string> res; std::string curMessage = ""; std::string curLine = ""; for (size_t i = 0; i < msg.size(); ++i) { curLine.push_back(msg[i]); if (i == msg.size() - 1 || msg[i] == '\n') { if (curMessage.size() + curLine.size() > msgSize) { res.push_back(std::move(curMessage)); curMessage = curLine; } else { curMessage += curLine; } curLine = ""; } } if (!curLine.empty()) { if (curMessage.size() + curLine.size() > msgSize) { res.push_back(std::move(curMessage)); curMessage = curLine; } else { curMessage += curLine; } } if (!curMessage.empty()) { res.push_back(std::move(curMessage)); } return res; } } // namespace NOctoshell <file_sep>#pragma once #include <string> #include "octoshell.h" #include <proto/user_state.pb.h> namespace NOctoshell { enum class EAuthStatus { SUCCESS = 0, INACTIVE_TOKEN = 1, WRONG_TOKEN = 2, WRONG_EMAIL = 3, SERVICE_UNAVAILABLE = 4, }; EAuthStatus TryAuth(TOctoshell& octoshell, const TUserState& state); static std::unordered_map<EAuthStatus, std::string> AuthToTemplateMap = { {EAuthStatus::SUCCESS, "auth.status.success"}, {EAuthStatus::INACTIVE_TOKEN, "auth.status.inactive-token"}, {EAuthStatus::WRONG_TOKEN, "auth.status.wrong-token"}, {EAuthStatus::WRONG_EMAIL, "auth.status.wrong-email"}, {EAuthStatus::SERVICE_UNAVAILABLE, "auth.status.service-unavailable"}, }; } // namespace NOctoshell <file_sep>#include "auth_status.h" #include <Poco/Logger.h> #include <Poco/JSON/Parser.h> namespace NOctoshell { EAuthStatus TryAuth(TOctoshell& octoshell, const TUserState& state) { auto& logger = Poco::Logger::get("try_auth"); std::string response = octoshell.SendQueryWithAuth(state, {{"method", "auth"}}); Poco::JSON::Parser parser; auto result = parser.parse(response); auto object = result.extract<Poco::JSON::Object::Ptr>(); if (object->has("status")) { return static_cast<EAuthStatus>(object->getValue<int>("status")); } logger.error("invalid response from server!"); return EAuthStatus::SERVICE_UNAVAILABLE; } } // namespace NOctoshell <file_sep>unavailable=Octoshell service is temporarily unavailable main.message=Press button in menu main.fail-auth=Please set correct authentication settings main.projects.header=📚 User projects: main.projects.number=📖 Project # main.projects.login=User login main.projects.title=Title main.projects.state=State main.projects.is-owner=You are the owner main.projects.is-not-owner=You aren't the owner main.projects.updated-at=Updated at main.tickets.header=🎫 User tickets count: main.tickets.number=🎟️ Ticket # main.tickets.who-status=User status main.tickets.who-is-reporter=📢 Reporter main.tickets.who-is-responsible=👓 Responsible main.tickets.topic-title=Topic main.tickets.project-title=Project main.tickets.cluster-title=Cluster main.tickets.subject-title=Subject main.tickets.desc=Description main.tickets.updated-at=Updated at main.tickets.state-title=State main.tickets.state.answered_by_reporter=Answered by reporter main.tickets.state.answered_by_support=Answered by support main.tickets.state.closed=Closed main.tickets.state.pending=Pending main.tickets.state.resolved=Resolved main.tickets.projects.message=Step 1/5. Choose the project main.tickets.topics.message=Step 2/5. Choose the topic main.tickets.clusters.message=Step 3/5. Choose the cluster main.tickets.subject.message=Step 4/5. Enter ticket subject (short description) main.tickets.message.message=Step 5/5. Enter ticket message (full description) main.tickets.response.message=Ticket creating status main.jobs.header=🎯 User jobs main.jobs.number=📜 Job main.jobs.state=State main.jobs.submitted=Submitted main.jobs.started=Started main.jobs.ended=Ended main.jobs.command=Command main.jobs.num-nodes=Nodes main.jobs.num-cores=cores main.jobs.duration-hours=Duration (in hours) main.jobs.rules=Problems found main.button.show-user-projects=🎨 Show projects main.button.show-user-jobs=🎯 Show jobs main.button.to-auth-settings=🔐 Authentication settings main.button.to-locale-settings=🌎 Language settings main.button.show-tickets=🎫👀 Show tickets main.button.create-tickets=✏️🎫 Create new ticket main.button.information=ℹ️ Information main.information=This bot can execute some actions: notify about ticket updates, register new tickets, show the projects.\n\n\ To use these functions, it is necessary to enter your email and token in the authentication section.\n\n\ You can generate the bot token in Octoshell in "Profile" section. auth.email.message=Enter new e-mail auth.email.wrong.message=An incorrect e-mail entered! auth.token.message=Enter new token auth.message=Press button in menu. Here you can enter your email and token. auth.blank-email=<Blank e-mail> auth.blank-token=<Blank token> auth.settings.header=⚙️ Authentication settings auth.settings.email=E-mail auth.settings.token=Token auth.check.header=🔮 Checking connection auth.status.success=Successfully authenticated! auth.status.inactive-token=An inactive token entered auth.status.wrong-token=A wrong token entered auth.status.wrong-email=A wrong email entered auth.status.service-unavailable=Octoshell service is temporarily unavailable auth.button.change-email=📧 Change e-mail auth.button.change-token=🔑 Change token auth.button.show-settings=👀 Print authentication settings auth.button.check-connection=🔌 Check connection to Octoshell auth.button.back=🚪 Back locale.message=Choose language locale.button.russian=🇷🇺 Русский locale.button.english=🇬🇧 English notify.ticket.header=🎫 Ticket notification notify.ticket.subject=Ticket subject notify.ticket.status.close=🚫 Ticket is closed notify.ticket.status.resolve=☑️ Ticket is resolved! notify.ticket.status.reopen=📖️ Ticket is reopened notify.ticket.status.update=➕ Ticket is updated notify.announcement.header=📣 You have received an announcement notify.announcement.type.title=Type notify.announcement.type.info=Information notify.announcement.type.service=Service notify.announcement.title=✉️ Title notify.announcement.body=✉️ Body notify.announcement.has-attachment=The announcement has an attachment, you can see it on the website <file_sep>#pragma once #include <vector> #include <proto/user_state.pb.h> #include "../model.h" #include "../fwd.h" namespace NOctoshell { class TStatesHolder { public: TStatesHolder(TContext& ctx); TReactions ProcessUpdate(TUpdate update, TUserState& state); private: TContext& Ctx_; }; } // namespace NOctoshell <file_sep>#include "states_holder.h" #include "state_processor.h" #include "auth_new_email_state_processor.h" #include "auth_new_token_state_processor.h" #include "auth_settings_state_processor.h" #include "locale_settings_state_processor.h" #include "main_menu_state_processor.h" #include "ticket_cluster_choose_state_processor.h" #include "ticket_project_choose_state_processor.h" #include "ticket_topic_choose_state_processor.h" #include "ticket_subject_choose_state_processor.h" #include "ticket_message_choose_state_processor.h" #include <inttypes.h> #include <unordered_map> #include <Poco/Logger.h> namespace NOctoshell { namespace { using TProcessorsMap = std::unordered_map<int, std::unique_ptr<IStatesProcessor>>; TProcessorsMap ConstructStatesProcessors(TContext& ctx) { TProcessorsMap map; map.emplace(TUserState_EState_MAIN_MENU, std::make_unique<TMainMenuStatesProcessor>(ctx)); map.emplace(TUserState_EState_LOCALE_SETTINGS, std::make_unique<TLocaleSettingsStatesProcessor>(ctx)); map.emplace(TUserState_EState_AUTH_SETTINGS, std::make_unique<TAuthSettingsStatesProcessor>(ctx)); map.emplace(TUserState_EState_AUTH_NEW_EMAIL, std::make_unique<TAuthNewEmailStatesProcessor>(ctx)); map.emplace(TUserState_EState_AUTH_NEW_TOKEN, std::make_unique<TAuthNewTokenStatesProcessor>(ctx)); map.emplace(TUserState_EState_TICKET_PROJECT_CHOOSE, std::make_unique<TTicketProjectChooseStatesProcessor>(ctx)); map.emplace(TUserState_EState_TICKET_TOPIC_CHOOSE, std::make_unique<TTicketTopicChooseStatesProcessor>(ctx)); map.emplace(TUserState_EState_TICKET_CLUSTER_CHOOSE, std::make_unique<TTicketClusterChooseStatesProcessor>(ctx)); map.emplace(TUserState_EState_TICKET_SUBJECT_CHOOSE, std::make_unique<TTicketSubjectChooseStatesProcessor>(ctx)); map.emplace(TUserState_EState_TICKET_MESSAGE_CHOOSE, std::make_unique<TTicketMessageChooseStatesProcessor>(ctx)); return map; } IStatesProcessor* FindStateProcessor(TUserState& state, const TProcessorsMap& map) { const auto iter = map.find(state.state()); if (iter == map.end()) { return nullptr; } return iter->second.get(); } } // namespace TStatesHolder::TStatesHolder(TContext& ctx) : Ctx_{ctx} { } TReactions TStatesHolder::ProcessUpdate(TUpdate update, TUserState& state) { const static auto processorsMap = ConstructStatesProcessors(Ctx_); auto& logger = Poco::Logger::get("states_holder"); logger.information("processing update from user %" PRIu64, update.UserId); TReactions reactions; for (const auto func : {&IStatesProcessor::OnUpdate, &IStatesProcessor::OnStart}) { if (const auto processor = FindStateProcessor(state, processorsMap)) { auto r = (processor->*func)(update, state); std::move(r.begin(), r.end(), std::inserter(reactions, reactions.end())); } else { logger.error("unimplemented state %d!", static_cast<int>(state.state())); } } return reactions; } } // namespace NOctoshell <file_sep>#include "mongo.h" #include "context.h" #include <iostream> #include <inttypes.h> #include <bsoncxx/builder/stream/document.hpp> #include <bsoncxx/json.hpp> #include <Poco/JSON/Parser.h> #include "../contrib/json2pb.h" using namespace bsoncxx::builder::stream; namespace NOctoshell { TMongo::TMongo(TContext& ctx) : Ctx_{ctx} , Instance_{} , Client_{mongocxx::uri{ctx.Config().getString("mongodb.url")}} , Database_{Client_["default"]} , StatesCollection_{Database_.collection("states")} { } TUserState TMongo::Load(std::uint64_t userId, const TUserState_ESource source) { auto& logger = Poco::Logger::get("mongo"); logger.information("getting state for userId %" PRIu64, userId); try { mongocxx::cursor cursor = StatesCollection_.find(document{} << "_id" << static_cast<std::int64_t>(userId) << finalize); for (auto doc : cursor) { std::string json = bsoncxx::to_json(doc); TUserState state; json2pb(state, json.c_str(), json.length()); if (state.source() == source) { logger.information("got state for userId %" PRIu64 ": %s", userId, json); return state; } } } catch (const std::exception& e) { logger.error(e.what()); } logger.information("got no state for userId %" PRIu64, userId); TUserState state; state.set_userid(userId); return state; } std::vector<TUserState> TMongo::LoadByAuth(const std::string& email, const std::string& token) { auto& logger = Poco::Logger::get("mongo"); logger.information("getting all states for email %s, token %s", email, token); std::vector<TUserState> states; try { mongocxx::cursor cursor = StatesCollection_.find(document{} << "Email" << email << "Token" << token << finalize); for (auto doc : cursor) { std::string json = bsoncxx::to_json(doc); TUserState state; json2pb(state, json.c_str(), json.length()); states.push_back(std::move(state)); } } catch (const std::exception& e) { logger.error(e.what()); } logger.information("got %d states for email %s, token %s", static_cast<int>(states.size()), email, token); return states; } void TMongo::Store(const TUserState& state) { auto& logger = Poco::Logger::get("mongo"); std::string json = pb2json(state); logger.information("storing state %s", json); try { auto filter = document{} << "_id" << static_cast<std::int64_t>(state.userid()) << finalize; auto stateDoc = bsoncxx::from_json(std::move(json)); StatesCollection_.replace_one(std::move(filter), std::move(stateDoc), mongocxx::options::replace().upsert(true)); } catch (const std::exception& e) { logger.error(e.what()); } } } // namespace NOctoshell <file_sep>#pragma once #include <vector> #include <proto/user_state.pb.h> #include "../model.h" #include "../fwd.h" namespace NOctoshell { class IStatesProcessor { public: virtual ~IStatesProcessor() = default; IStatesProcessor(TContext& ctx) : Ctx_{ctx} {}; virtual TReactions OnStart(TUpdate update, TUserState& state) = 0; virtual TReactions OnUpdate(TUpdate update, TUserState& state) = 0; protected: TContext& Ctx_; }; } // namespace NOctoshell <file_sep>CMAKE_MINIMUM_REQUIRED(VERSION 2.8.4) PROJECT(octoshellbot) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1z -Wall -g") ADD_SUBDIRECTORY(proto) FIND_PACKAGE(Poco COMPONENTS Foundation Util Net NetSSL JSON REQUIRED) FIND_PACKAGE(mongocxx REQUIRED) FIND_PACKAGE(OpenSSL REQUIRED) INCLUDE_DIRECTORIES(/usr/local/include ${OPENSSL_INCLUDE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) ADD_EXECUTABLE(octoshellbot contrib/json2pb.cc src/client/telegram.cpp src/client/vkontakte.cpp src/client/util.cpp src/auth_status.cpp src/context.cpp src/handlers.cpp src/main.cpp src/mongo.cpp src/octoshell.cpp src/states/auth_new_email_state_processor.cpp src/states/auth_new_token_state_processor.cpp src/states/auth_settings_state_processor.cpp src/states/locale_settings_state_processor.cpp src/states/main_menu_state_processor.cpp src/states/states_holder.cpp src/states/ticket_cluster_choose_state_processor.cpp src/states/ticket_message_choose_state_processor.cpp src/states/ticket_project_choose_state_processor.cpp src/states/ticket_subject_choose_state_processor.cpp src/states/ticket_topic_choose_state_processor.cpp src/translate.cpp ) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/resources/ru.properties DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/resources/en.properties DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) TARGET_LINK_LIBRARIES(octoshellbot proto ${OPENSSL_LIBRARIES} ${Poco_LIBRARIES} mongo::mongocxx_shared -lprotobuf -ljansson) <file_sep>#pragma once #include <cstdint> #include <string> #include <vector> namespace NOctoshell { /* * Update from a messenger */ struct TUpdate { std::uint64_t UserId; std::string Text; }; /* * Reaction from the bot */ struct TReaction { using TKeyboardRow = std::vector<std::string>; using TKeyboard = std::vector<TKeyboardRow>; std::string Text; TKeyboard Keyboard; bool ForceReply = false; }; using TReactions = std::vector<TReaction>; } // namespace NOctoshell <file_sep>#include "ticket_subject_choose_state_processor.h" #include "../translate.h" #include "../context.h" #include <Poco/Logger.h> #include <Poco/JSON/Parser.h> #include <inttypes.h> #include <regex> namespace NOctoshell { TReactions TTicketSubjectChooseStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("ticket_subject_choose_processor").information("on_start from user %" PRIu64, update.UserId); TReaction reaction; reaction.ForceReply = true; reaction.Text = "main.tickets.subject.message"; return {std::move(reaction)}; } TReactions TTicketSubjectChooseStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { Poco::Logger::get("ticket_subject_choose_processor").information("on_update from user %" PRIu64, update.UserId); // user entered the subject (*state.mutable_extradata())["subject"] = update.Text; state.set_state(TUserState_EState_TICKET_MESSAGE_CHOOSE); return {}; } } // namespace NOctoshell <file_sep>#include "translate.h" #include <queue> #include <regex> #include <Poco/Logger.h> namespace NOctoshell { namespace { std::unordered_map<std::string, TLangTranslate> ConstructLangMap() { return { {"ru", TLangTranslate{"ru"}}, {"en", TLangTranslate{"en"}}, }; } std::vector<std::pair<std::string, std::string>> ConstructValues(const Poco::Util::PropertyFileConfiguration& conf) { std::vector<std::pair<std::string, std::string>> res; std::queue<std::string> q; q.push(""); while (!q.empty()) { std::string prefix = q.front(); q.pop(); std::vector<std::string> child; conf.keys(prefix, child); if (child.empty()) { std::string value = conf.getString(prefix); res.emplace_back(std::move(prefix), std::move(value)); } else { for (auto&& v : child) { if (!prefix.empty()) { q.push(prefix + "." + std::move(v)); } else { q.push(std::move(v)); } } } } return res; } const TLangTranslate* FindLangTranslate(const TUserState_ELanguage lang, const TTranslate& translate) { switch (lang) { case TUserState_ELanguage_EN: return &translate.LangTranslate("en"); case TUserState_ELanguage_RU: return &translate.LangTranslate("ru"); default: return static_cast<const TLangTranslate*>(nullptr); } } } // namespace TLangTranslate::TLangTranslate(const std::string& lang) : Map_{new Poco::Util::PropertyFileConfiguration(lang + ".properties")} , Values_{ConstructValues(*Map_)} { } std::string TLangTranslate::Get(const std::string& key) const { return Map_->getString(key); } const std::vector<std::pair<std::string, std::string>>& TLangTranslate::Values() const { return Values_; } TTranslate::TTranslate() : LangMap_{ConstructLangMap()} { } std::string TTranslate::Get(const std::string& lang, const std::string& key) const { return LangTranslate(lang).Get(key); } const TLangTranslate& TTranslate::LangTranslate(const std::string& lang) const { return LangMap_.find(lang)->second; } void TranslateReaction(TReaction& reaction, const TUserState_ELanguage lang, const TTranslate& translate) { const TLangTranslate* lt = FindLangTranslate(lang, translate); if (!lt) { Poco::Logger::get("translate").error("unknown language"); return; } const auto func = [val = lt->Values()](std::string& text) { for (const auto& [key, value] : val) { if (text.find(key) != std::string::npos) { text = std::regex_replace(text, std::regex(key), value); } } }; func(reaction.Text); for (auto& row : reaction.Keyboard) { for (auto& text : row) { func(text); } } } std::string TryGetTemplate(const std::string& text, const TUserState_ELanguage lang, const TTranslate& translate) { const TLangTranslate* lt = FindLangTranslate(lang, translate); if (!lt) { Poco::Logger::get("translate").error("unknown language"); return ""; } for (const auto& [key, value] : lt->Values()) { if (text.find(value) != std::string::npos) { return key; } } return ""; } } // namespace NOctoshell <file_sep>#pragma once #include <memory> #include <Poco/Logger.h> #include <Poco/Net/HTTPServer.h> #include <Poco/Util/PropertyFileConfiguration.h> #include "model.h" #include "mongo.h" #include "octoshell.h" #include "states/states_holder.h" #include "translate.h" namespace NOctoshell { class TContext { public: TContext(const std::string& configPath); void StartServer(); void StopServer(); const Poco::Util::PropertyFileConfiguration& Config() const; const TTranslate& Translate() const; TMongo& Mongo(); TOctoshell& Octoshell(); [[nodiscard]] TReactions OnUpdate(TUpdate update, const TUserState_ESource source); private: Poco::Logger& Logger() const; private: Poco::AutoPtr<Poco::Util::PropertyFileConfiguration> Config_; std::unique_ptr<Poco::Net::HTTPServer> HttpServer_; TTranslate Translate_; TStatesHolder StatesHolder_; TMongo Mongo_; TOctoshell Octoshell_; }; } // namespace NOctoshell <file_sep>#include "octoshell.h" #include "context.h" #include <regex> #include <sstream> #include <Poco/Logger.h> #include <Poco/URI.h> #include <Poco/Net/HTTPClientSession.h> #include <Poco/Net/HTTPRequest.h> #include <Poco/Net/HTTPResponse.h> #include <Poco/Net/HTTPSClientSession.h> using namespace Poco::Net; namespace NOctoshell { namespace { std::string UrlQuote(std::string s) { s = std::regex_replace(s, std::regex(" "), "%20"); s = std::regex_replace(s, std::regex("\n"), "%0A"); s = std::regex_replace(s, std::regex("\r"), "%0D"); return s; } } // namespace std::string TOctoshell::SendQueryWithAuth(const TUserState& state, const std::unordered_map<std::string, std::string>& params) { auto& logger = Poco::Logger::get("octoshell"); logger.information("add user's mail and token to the query"); auto paramsCopy = params; paramsCopy["email"] = state.email(); paramsCopy["token"] = state.token(); return SendQuery(paramsCopy); } std::string TOctoshell::SendQuery(const std::unordered_map<std::string, std::string>& params) { auto& logger = Poco::Logger::get("octoshell"); logger.information("send query to octoshell server"); std::stringstream ss; ss << Ctx_.Config().getString("octoshell.url"); if (!params.empty()) { ss << "?"; } bool needAmpersand = false; for (const auto& [key, value] : params) { if (needAmpersand) { needAmpersand = false; ss << "&"; } ss << key << "=" << value; needAmpersand = true; } Poco::URI uri{UrlQuote(ss.str())}; std::string path(uri.getPathAndQuery()); if (path.empty()) { path = "/"; } std::unique_ptr<HTTPClientSession> session; if (uri.getScheme() == "http") { session = std::make_unique<HTTPClientSession>(uri.getHost(), uri.getPort()); } else { session = std::make_unique<HTTPSClientSession>(uri.getHost(), uri.getPort()); } const Poco::Timespan ts(/* seconds = */ 5L, /* microseconds = */ 0L); session->setTimeout(ts); HTTPRequest request(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1); session->sendRequest(request); HTTPResponse response; std::istream& rs = session->receiveResponse(response); std::stringstream responseStream; responseStream << rs.rdbuf(); logger.information("sendMessage response: code %d, reason %s, body %s", static_cast<int>(response.getStatus()), response.getReason(), responseStream.str()); return responseStream.str(); } } // namespace NOctoshell <file_sep>#pragma once namespace NOctoshell { class TContext; } // namespace NOctoshell <file_sep>#include "auth_new_email_state_processor.h" #include "../translate.h" #include "../context.h" #include <Poco/Logger.h> #include <inttypes.h> #include <regex> namespace NOctoshell { namespace { static const std::string MAIL_REGEX_STR = R"((?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]))"; static const auto MAIL_REGEX = std::regex(MAIL_REGEX_STR); } // namespace TReactions TAuthNewEmailStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("auth_new_email_processor").information("on_start from user %" PRIu64, update.UserId); TReaction reaction; reaction.Text = "auth.email.message"; reaction.ForceReply = true; return {std::move(reaction)}; } TReactions TAuthNewEmailStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { auto& logger = Poco::Logger::get("auth_new_email_processor"); logger.information("on_update from user %" PRIu64, update.UserId); const std::string code = TryGetTemplate(update.Text, state.language(), Ctx_.Translate()); logger.information("Pressed button is \"%s\"", code); state.set_state(TUserState_EState_AUTH_SETTINGS); if (std::regex_match(update.Text, MAIL_REGEX)) { state.set_email(update.Text); return {}; } else { TReaction reaction; reaction.Text = "auth.email.wrong.message"; return {std::move(reaction)}; } } } // namespace NOctoshell <file_sep>#include "ticket_project_choose_state_processor.h" #include "../translate.h" #include "../context.h" #include <Poco/Logger.h> #include <Poco/JSON/Parser.h> #include <inttypes.h> #include <regex> namespace NOctoshell { TReactions TTicketProjectChooseStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("ticket_project_choose_processor").information("on_start from user %" PRIu64, update.UserId); TReaction reaction; const std::string response = Ctx_.Octoshell().SendQueryWithAuth(state, {{"method", "user_projects"}}); Poco::JSON::Parser parser; auto result = parser.parse(response); auto object = result.extract<Poco::JSON::Object::Ptr>(); std::string status = object->getValue<std::string>("status"); if (status == "fail") { reaction.Text = "main.fail-auth"; } else { reaction.Text = "main.tickets.projects.message"; auto projArr = object->getArray("projects"); for (size_t i = 0; i < projArr->size(); ++i) { auto proj = projArr->getObject(i); reaction.Keyboard.push_back({proj->getValue<std::string>("title")}); } } reaction.Keyboard.push_back({"auth.button.back"}); return {std::move(reaction)}; } TReactions TTicketProjectChooseStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { auto& logger = Poco::Logger::get("ticket_project_choose_processor"); logger.information("on_update from user %" PRIu64, update.UserId); const std::string code = TryGetTemplate(update.Text, state.language(), Ctx_.Translate()); logger.information("Pressed button is \"%s\"", code); // user wants to exit if (code == "auth.button.back") { state.set_state(TUserState_EState_MAIN_MENU); return {}; } // user selected the project (we suppose that he clicked at the menu) (*state.mutable_extradata())["project"] = update.Text; state.set_state(TUserState_EState_TICKET_TOPIC_CHOOSE); return {}; } } // namespace NOctoshell <file_sep>#include "ticket_message_choose_state_processor.h" #include "../translate.h" #include "../context.h" #include <Poco/Logger.h> #include <Poco/JSON/Parser.h> #include <inttypes.h> #include <regex> namespace NOctoshell { TReactions TTicketMessageChooseStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("ticket_message_choose_processor").information("on_start from user %" PRIu64, update.UserId); TReaction reaction; reaction.ForceReply = true; reaction.Text = "main.tickets.message.message"; return {std::move(reaction)}; } TReactions TTicketMessageChooseStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { auto& logger = Poco::Logger::get("ticket_message_choose_processor"); logger.information("on_update from user %" PRIu64, update.UserId); // user entered the message (*state.mutable_extradata())["message"] = update.Text; state.set_state(TUserState_EState_MAIN_MENU); // send request for creating ticket std::unordered_map<std::string, std::string> params; for (const auto& key : {"project", "topic", "cluster", "subject", "message"}) { params[key] = state.extradata().at(key); } params["method"] = "create_ticket"; const std::string response = Ctx_.Octoshell().SendQueryWithAuth(state, params); Poco::JSON::Parser parser; auto result = parser.parse(response); auto object = result.extract<Poco::JSON::Object::Ptr>(); TReaction reaction; reaction.Text = "main.tickets.response.message: " + object->getValue<std::string>("status"); return {std::move(reaction)}; } } // namespace NOctoshell <file_sep>#include "handlers.h" #include "client/client.h" #include "client/telegram.h" #include "client/vkontakte.h" #include <proto/user_state.pb.h> #include <Poco/Net/HTTPServerResponse.h> #include <Poco/JSON/Parser.h> #include <exception> #include <inttypes.h> #include <sstream> using namespace Poco::Net; namespace NOctoshell { namespace { std::unique_ptr<IClient> ConstructClient(const TUserState_ESource source, TContext& ctx) { if (source == TUserState_ESource_TELEGRAM) { return std::make_unique<TTelegramClient>(ctx); } else if (source == TUserState_ESource_VKONTAKTE) { return std::make_unique<TVkontakteClient>(ctx); } else { throw std::runtime_error("unknown client source"); } } std::string ReadInput(HTTPServerRequest& request) { std::istream& is = request.stream(); char c; std::string str; while (is.get(c)) { str += c; } return str; } void ConfirmVkontakte(const Poco::JSON::Object& data, const TContext& ctx, HTTPServerRequest& request, HTTPServerResponse& response) { auto& logger = Poco::Logger::get("vkontakte_confirm"); if (!data.has("secret") || data.getValue<std::string>("secret") != ctx.Config().getString("vk.secret_code")) { logger.warning("wrong or absent \"secret\" in VK confirm request"); return; } if (!data.has("group_id") || data.getValue<std::string>("group_id") != ctx.Config().getString("vk.group_id")) { logger.warning("wrong or absent \"group_id\" in VK confirm request"); return; } logger.information("successfully confirmed VK server"); response.setStatus(HTTPServerResponse::HTTP_OK); response.setContentType("text/plain"); response.send() << ctx.Config().getString("vk.confirmation_code"); } template<typename TClient, std::enable_if_t<std::is_base_of<IClient, TClient>::value, int> = 0> class TClientHandler final : public HTTPRequestHandler { public: TClientHandler(TContext& ctx) : Ctx_{ctx} , Client_{new TClient(ctx)} { } void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) override { auto& logger = Poco::Logger::get("client_handler"); logger.information("Client query from %s", request.getURI()); // read full stream std::string in = ReadInput(request); logger.information("Body: %s", in); try { // parse Json from HTTP Poco::JSON::Parser parser; auto result = parser.parse(in); auto object = result.extract<Poco::JSON::Object::Ptr>(); // corner case - VKontakte identification if (object->has("type") && object->getValue<std::string>("type") == "confirmation") { ConfirmVkontakte(*object, Ctx_, request, response); return; } // send default 200 HTTP OK response.send() << "ok"; // parse Update from Json TUpdate update = Client_->ParseUpdate(*object); logger.information("new update: Text \"%s\", UserId \"%" PRIu64 "\"", update.Text, update.UserId); // send Reactions from Update auto reactions = Ctx_.OnUpdate(std::move(update), Client_->Source()); for (const auto& reaction : reactions) { Client_->SendReaction(update, reaction); } } catch (const Poco::JSON::JSONException& e) { logger.error(e.displayText()); } catch (const std::exception& e) { logger.error(e.what()); } } private: TContext& Ctx_; std::unique_ptr<IClient> Client_; }; class TDummyHandler final : public HTTPRequestHandler { public: void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) override { auto& logger = Poco::Logger::get("dummy_handler"); logger.information("Request input: %s", ReadInput(request)); response.setStatus(HTTPServerResponse::HTTP_IM_A_TEAPOT); response.setContentType("text/plain"); response.send() << "I Am A Teapot"; } }; class TNotifyHandler final : public HTTPRequestHandler { public: TNotifyHandler(TContext& ctx) : Ctx_{ctx} {} void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) override { auto& logger = Poco::Logger::get("notify_handler"); const std::string in = ReadInput(request); logger.information("Notify body: %s", in); // immediate answer response.setStatus(HTTPServerResponse::HTTP_OK); response.setContentType("text/plain"); response.send() << "ok"; // working with input Poco::JSON::Parser parser; Poco::Dynamic::Var result = parser.parse(in); const std::string& uri = request.getURI(); if (uri == "/notify/ticket") { OnNotifyTicket(std::move(result)); } else if (uri == "/notify/announcement") { OnNotifyAnnouncement(std::move(result)); } else { logger.warning("Unknown uri!"); } } private: void OnNotifyTicket(Poco::Dynamic::Var result) { auto objectsArr = result.extract<Poco::JSON::Array::Ptr>(); for (size_t i = 0; i < objectsArr->size(); ++i) { const auto object = objectsArr->getObject(i); if (!object->has("token")) { return; } const std::string email = object->getValue<std::string>("email"); const std::string token = object->getValue<std::string>("token"); const std::string event = object->getValue<std::string>("event"); const std::string subject = object->getValue<std::string>("subject"); auto& mongo = Ctx_.Mongo(); std::vector<TUserState> states = mongo.LoadByAuth(email, token); for (const TUserState& state : states) { auto client = ConstructClient(state.source(), Ctx_); TUpdate update; update.UserId = state.userid(); TReaction reaction; std::stringstream ss; ss << "notify.ticket.header" << "\n" << "notify.ticket.subject" << ": \"" << subject << "\"\n" << "notify.ticket.status." << event << "\n"; reaction.Text = ss.str(); TranslateReaction(reaction, state.language(), Ctx_.Translate()); client->SendReaction(update, reaction); } } } void OnNotifyAnnouncement(Poco::Dynamic::Var result) { auto& logger = Poco::Logger::get("notify_handler"); auto object = result.extract<Poco::JSON::Object::Ptr>(); if (!object->has("users") || !object->has("announcement")) { return; } const auto announce = object->getObject("announcement"); const auto usersArr = object->getArray("users"); auto& mongo = Ctx_.Mongo(); for (size_t i = 0; i < usersArr->size(); ++i) { const auto& user = usersArr->getObject(i); if (!user->has("email") || !user->has("token")) { continue; } const std::string email = user->getValue<std::string>("email"); const std::string token = user->getValue<std::string>("token"); logger.information("send notify to email %s, token %s", email, token); std::vector<TUserState> states = mongo.LoadByAuth(email, token); for (const TUserState& state : states) { const std::string locale = state.language() == TUserState_ELanguage_EN ? "en" : "ru"; auto client = ConstructClient(state.source(), Ctx_); TUpdate update; update.UserId = state.userid(); TReaction reaction; std::stringstream ss; ss << "notify.announcement.header" << "\n\n" << "notify.announcement.type.title" << ": " << (announce->getValue<bool>("is_special") ? "notify.announcement.type.service" : "notify.announcement.type.info") << "\n\n" << "notify.announcement.title" << ": \"" << announce->getValue<std::string>("title_" + locale) << "\"\n\n" << "notify.announcement.body" << ": \"" << announce->getValue<std::string>("body_" + locale) << "\"\n"; if (announce->has("attachment") && !announce->isNull("attachment")) { ss << "\n" << "notify.announcement.has-attachment"; } reaction.Text = ss.str(); TranslateReaction(reaction, state.language(), Ctx_.Translate()); client->SendReaction(update, reaction); } } } private: TContext& Ctx_; }; class TPingHandler final : public HTTPRequestHandler { public: void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) override { response.setStatus(HTTPServerResponse::HTTP_OK); response.setContentType("text/plain"); response.send() << "pong"; } }; } // namespace THandlerFactory::THandlerFactory(TContext& ctx) : Ctx_{ctx} { } HTTPRequestHandler* THandlerFactory::createRequestHandler(const HTTPServerRequest& request) { auto& logger = Poco::Logger::get("handlers"); const std::string& uri = request.getURI(); logger.information("Got request at URI %s", uri); if (uri == "/ping") { return new TPingHandler(); } if (uri == "/api/telegram") { return new TClientHandler<TTelegramClient>(Ctx_); } if (uri == "/api/vkontakte") { return new TClientHandler<TVkontakteClient>(Ctx_); } // `uri` starts with "/notify" if (uri.rfind("/notify", 0) == 0) { return new TNotifyHandler(Ctx_); } return new TDummyHandler(); } } // namespace NOctoshell <file_sep>#include "ticket_cluster_choose_state_processor.h" #include "../translate.h" #include "../context.h" #include <Poco/Logger.h> #include <Poco/JSON/Parser.h> #include <inttypes.h> #include <regex> namespace NOctoshell { TReactions TTicketClusterChooseStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("ticket_cluster_choose_processor").information("on_start from user %" PRIu64, update.UserId); TReaction reaction; const std::string response = Ctx_.Octoshell().SendQueryWithAuth(state, {{"method", "clusters"}}); Poco::JSON::Parser parser; auto result = parser.parse(response); auto object = result.extract<Poco::JSON::Object::Ptr>(); std::string status = object->getValue<std::string>("status"); if (status == "fail") { reaction.Text = "main.fail-auth"; } else { reaction.Text = "main.tickets.clusters.message"; const std::string locale = state.language() == TUserState_ELanguage_EN ? "en" : "ru"; auto clustersArr = object->getArray("clusters"); for (size_t i = 0; i < clustersArr->size(); ++i) { auto cluster = clustersArr->getObject(i); reaction.Keyboard.push_back({cluster->getValue<std::string>("name_" + locale)}); } } reaction.Keyboard.push_back({"auth.button.back"}); return {std::move(reaction)}; } TReactions TTicketClusterChooseStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { auto& logger = Poco::Logger::get("ticket_cluster_choose_processor"); logger.information("on_update from user %" PRIu64, update.UserId); const std::string code = TryGetTemplate(update.Text, state.language(), Ctx_.Translate()); logger.information("Pressed button is \"%s\"", code); // user wants to exit if (code == "auth.button.back") { state.set_state(TUserState_EState_MAIN_MENU); return {}; } // user selected the cluster (we suppose that he clicked at the menu) (*state.mutable_extradata())["cluster"] = update.Text; state.set_state(TUserState_EState_TICKET_SUBJECT_CHOOSE); return {}; } } // namespace NOctoshell <file_sep>#pragma once #include "client.h" namespace NOctoshell { class TVkontakteClient final : public IClient { public: using IClient::IClient; TUpdate ParseUpdate(const Poco::JSON::Object& data) const override; void SendReaction(const TUpdate& update, const TReaction& reaction) const override; TUserState_ESource Source() const override; }; } // namespace NOctoshell <file_sep>#pragma once #include <Poco/Util/PropertyFileConfiguration.h> #include <string> #include <unordered_map> #include "model.h" #include <proto/user_state.pb.h> namespace NOctoshell { class TLangTranslate { public: TLangTranslate(const std::string& lang); std::string Get(const std::string& key) const; const std::vector<std::pair<std::string, std::string>>& Values() const; private: Poco::AutoPtr<Poco::Util::PropertyFileConfiguration> Map_; std::vector<std::pair<std::string, std::string>> Values_; }; class TTranslate { public: TTranslate(); std::string Get(const std::string& lang, const std::string& key) const; const TLangTranslate& LangTranslate(const std::string& lang) const; private: std::unordered_map<std::string, TLangTranslate> LangMap_; }; void TranslateReaction(TReaction& reaction, const TUserState_ELanguage lang, const TTranslate& translate); std::string TryGetTemplate(const std::string& text, const TUserState_ELanguage lang, const TTranslate& translate); } // namespace NOctoshell <file_sep># базовый образ FROM ubuntu:18.04 as build # установка необходимых пакетов для компиляции приложения RUN apt-get update && apt-get install -y \ cmake \ g++ \ libjansson-dev \ protobuf-compiler \ libprotobuf-dev \ libpoco-dev \ wget \ curl \ git # устанавливаем библиотеки для работы с MongoDB # сначала "libmongoc" RUN wget https://github.com/mongodb/mongo-c-driver/releases/download/1.17.2/mongo-c-driver-1.17.2.tar.gz -O /mongoc.tar.gz RUN tar xzf /mongoc.tar.gz WORKDIR /mongo-c-driver-1.17.2 RUN mkdir cmake-build && \ cd cmake-build && \ cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF .. && \ cmake --build . && \ cmake --build . --target install # потом "mongocxx" WORKDIR / RUN curl -OL https://github.com/mongodb/mongo-cxx-driver/releases/download/r3.6.1/mongo-cxx-driver-r3.6.1.tar.gz RUN tar -xzf mongo-cxx-driver-r3.6.1.tar.gz WORKDIR /mongo-cxx-driver-r3.6.1/build RUN cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local RUN cmake --build . && cmake --build . --target install # построение исходников приложения COPY ./src/resources/app.properties /app.properties COPY ./src /app/src WORKDIR /app/bin RUN cmake ../src && cmake --build . # запуск бота ENTRYPOINT ["./octoshellbot", "/app.properties"] <file_sep>#include "auth_new_token_state_processor.h" #include "../translate.h" #include "../context.h" #include <Poco/Logger.h> #include <inttypes.h> #include <regex> namespace NOctoshell { TReactions TAuthNewTokenStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("auth_new_token_processor").information("on_start from user %" PRIu64, update.UserId); TReaction reaction; reaction.Text = "auth.token.message"; reaction.ForceReply = true; return {std::move(reaction)}; } TReactions TAuthNewTokenStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { auto& logger = Poco::Logger::get("auth_new_token_processor"); logger.information("on_update from user %" PRIu64, update.UserId); const std::string code = TryGetTemplate(update.Text, state.language(), Ctx_.Translate()); logger.information("Pressed button is \"%s\"", code); state.set_state(TUserState_EState_AUTH_SETTINGS); if (!update.Text.empty()) { state.set_token(update.Text); } return {}; } } // namespace NOctoshell <file_sep>#include <iostream> #include <memory> #include <Poco/Util/ServerApplication.h> #include "context.h" using namespace Poco; class TApp final : public Util::ServerApplication { private: int main(const std::vector<std::string>& args) override { if (args.size() < 1) { std::cerr << "Please provide path to .properties file" << std::endl; return 1; } const std::string& configPath = args[0]; NOctoshell::TContext ctx(configPath); ctx.StartServer(); waitForTerminationRequest(); ctx.StopServer(); return 0; } }; POCO_SERVER_MAIN(TApp) <file_sep>**Как пользоваться ботом?** Откройте ваш "Профиль" - https://users.parallel.ru/profile Нажмите на "Сгенерировать токен" ![token](https://user-images.githubusercontent.com/5406399/115353631-6d555100-a1c<PASSWORD>.png) Откройте Telegram-бот https://t.me/OctoshellBot или Vkontakte-бот https://vk.com/octoshell Вам будет доступно "Главное меню": ![hello](https://user-images.githubusercontent.com/5406399/115353970-ce7d2480-a1c1-11eb-8041-a5607e516976.png) Нажмите на кнопку "Настройки аутентификации": ![auth](https://user-images.githubusercontent.com/5406399/115354195-071cfe00-a1c2-11eb-9f7d-d84e1c1f7cfd.png) Нажмите на кнопку "Поменять email", введите email (указанный Вами во время регистрации на Octoshell). Таким же образом введите токен (который Вы только что сгенерировали в "Профиле"): ![in](https://user-images.githubusercontent.com/5406399/115354548-6f6bdf80-a1c2-11eb-9ee0-d40bc5b561c9.png) Теперь Вам доступны быстрые уведомления: об обновлениях в ваших заявках, о массовых рассылках. Также Вы можете через бота создавать заявления в техподдержку, просматривать статус Ваших задач, просматривать Ваши текущие проекты и заявления в техподдержку. <file_sep>#include "locale_settings_state_processor.h" #include "../translate.h" #include "../context.h" #include <Poco/Logger.h> #include <inttypes.h> namespace NOctoshell { TReactions TLocaleSettingsStatesProcessor::OnStart(TUpdate update, TUserState& state) { Poco::Logger::get("locale_settings_processor").information("on_start from user %" PRIu64, update.UserId); TReaction reaction; reaction.Text = "locale.message"; reaction.Keyboard = {{"locale.button.russian", "locale.button.english"}}; return {std::move(reaction)}; } TReactions TLocaleSettingsStatesProcessor::OnUpdate(TUpdate update, TUserState& state) { auto& logger = Poco::Logger::get("locale_settings_processor"); logger.information("main menu on_update from user %" PRIu64, update.UserId); const std::string code = TryGetTemplate(update.Text, state.language(), Ctx_.Translate()); logger.information("Pressed button is \"%s\"", code); if (code == "locale.button.russian") { state.set_state(TUserState_EState_MAIN_MENU); state.set_language(TUserState_ELanguage_RU); return {}; } if (code == "locale.button.english") { state.set_state(TUserState_EState_MAIN_MENU); state.set_language(TUserState_ELanguage_EN); return {}; } return {}; } } // namespace NOctoshell <file_sep>#include "vkontakte.h" #include "util.h" #include "../context.h" #include <sstream> #include <Poco/Logger.h> #include <Poco/URI.h> #include <Poco/Net/HTTPSClientSession.h> #include <Poco/Net/HTTPRequest.h> #include <Poco/Net/HTTPResponse.h> using namespace Poco::Net; namespace NOctoshell { namespace { Poco::JSON::Object ConstructReplyMarkup(const TReaction::TKeyboard& keyboard) { Poco::JSON::Object markup; markup.set("one_time", false); markup.set("inline", false); Poco::JSON::Array keyboardArr; for (const auto& row : keyboard) { Poco::JSON::Array keyboardRow; for (const auto& text : row) { Poco::JSON::Object action; action.set("type", "text"); action.set("label", text); Poco::JSON::Object button; button.set("action", action); keyboardRow.add(button); } keyboardArr.add(keyboardRow); } markup.set("buttons", keyboardArr); return markup; } std::string ConstructReplyMarkupJson(const TReaction::TKeyboard& keyboard) { auto obj = ConstructReplyMarkup(keyboard); std::stringstream ss; obj.stringify(ss); return ss.str(); } } // namespace TUpdate TVkontakteClient::ParseUpdate(const Poco::JSON::Object& data) const { Poco::Logger::get("vkontakte").information("parsing vkontakte update"); TUpdate update; if (data.has("object")) { auto obj = data.getObject("object"); if (obj->has("message")) { auto msg = obj->getObject("message"); update.UserId = msg->getValue<std::uint64_t>("peer_id"); update.Text = msg->getValue<std::string>("text"); } } return update; } void TVkontakteClient::SendReaction(const TUpdate& update, const TReaction& reaction) const { auto& logger = Poco::Logger::get("vkontakte"); logger.information("send vkontakte reaction"); auto msgs = DivideMessage(reaction.Text, Ctx_.Config().getInt("vk.msg_size")); for (const std::string& msg : msgs) { std::stringstream ss; ss << "https://api.vk.com/method/messages.send"; ss << "?message=" << UrlQuote(msg); ss << "&peer_id=" << update.UserId; ss << "&access_token=" << Ctx_.Config().getString("vk.access_token"); ss << "&v=" << "5.124"; ss << "&random_id=" << "0"; ss << "&keyboard=" << UrlQuote(ConstructReplyMarkupJson(reaction.Keyboard)); Poco::URI uri{UrlQuote(ss.str())}; std::string path(uri.getPathAndQuery()); if (path.empty()) { path = "/"; } HTTPSClientSession session(uri.getHost(), uri.getPort()); HTTPRequest request(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1); request.setContentLength(0); session.sendRequest(request); HTTPResponse response; std::istream& rs = session.receiveResponse(response); std::stringstream responseStream; responseStream << rs.rdbuf(); logger.information("sendMessage response: code %d, reason %s, body %s", static_cast<int>(response.getStatus()), response.getReason(), responseStream.str()); } } TUserState_ESource TVkontakteClient::Source() const { return TUserState_ESource_VKONTAKTE; } } // namespace NOctoshell <file_sep>#pragma once #include <string> #include <unordered_map> #include <proto/user_state.pb.h> #include "fwd.h" namespace NOctoshell { class TOctoshell { public: TOctoshell(TContext& ctx) : Ctx_{ctx} {}; std::string SendQueryWithAuth(const TUserState& state, const std::unordered_map<std::string, std::string>& params); std::string SendQuery(const std::unordered_map<std::string, std::string>& params); private: TContext& Ctx_; }; } // namespace NOctoshell <file_sep>#include "context.h" #include "handlers.h" #include <inttypes.h> #include <map> #include <queue> #include <sstream> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> #include <Poco/Logger.h> #include <Poco/SimpleFileChannel.h> #include <Poco/ConsoleChannel.h> #include <Poco/PatternFormatter.h> #include <Poco/FormattingChannel.h> #include <Poco/Environment.h> #include <Poco/Net/HTTPResponse.h> #include <Poco/Net/HTTPSClientSession.h> #include <Poco/URI.h> using namespace Poco; using namespace Poco::Net; namespace NOctoshell { namespace { std::unique_ptr<Net::HTTPServer> ConstructHttpServer(TContext& ctx) { std::uint16_t port = ctx.Config().getInt("port"); return std::make_unique<Net::HTTPServer>(new THandlerFactory(ctx), port); } Poco::AutoPtr<Poco::Util::PropertyFileConfiguration> ConstructConfig(const std::string& configPath) { Poco::AutoPtr<Poco::Util::PropertyFileConfiguration> config = new Util::PropertyFileConfiguration(configPath); std::vector<std::string> keys; std::queue<std::string> q; q.push(""); while (!q.empty()) { std::string prefix = q.front(); q.pop(); std::vector<std::string> child; config->keys(prefix, child); if (child.empty()) { keys.push_back(std::move(prefix)); } else { for (auto&& v : child) { if (!prefix.empty()) { q.push(prefix + "." + std::move(v)); } else { q.push(std::move(v)); } } } } for (const auto& key : keys) { std::string envVar = "OCTOBOT_" + translate(toUpper(key), ".", "_"); if (Poco::Environment::has(envVar)) { config->setString(key, Poco::Environment::get(envVar)); } } return config; } void InitLogs(const Util::PropertyFileConfiguration& config) { AutoPtr<ConsoleChannel> channel; if (config.has("logpath")) { AutoPtr<SimpleFileChannel> channel(new SimpleFileChannel); channel->setProperty("path", config.getString("logpath")); } else { channel = new ConsoleChannel; } AutoPtr<PatternFormatter> patternFormatter(new PatternFormatter); patternFormatter->setProperty("pattern", "[%Y/%b/%d %H:%M:%S.%i] [thread %I] [%p] [%s] %t"); AutoPtr<FormattingChannel> formattingChannel(new FormattingChannel(patternFormatter, channel)); Logger::root().setChannel(formattingChannel.get()); } void SetTelegramWebhook(const Util::PropertyFileConfiguration& config) { auto& logger = Poco::Logger::get("telegram"); logger.information("setting telegram webhook to %s", config.getString("url")); std::stringstream ss; ss << "https://api.telegram.org/bot" << config.getString("telegram.token"); ss << "/setWebhook?url=" << config.getString("url"); if (config.getString("url").back() != '/') { ss << "/"; } ss << "api/telegram"; URI uri{ss.str()}; std::string path(uri.getPathAndQuery()); if (path.empty()) { path = "/"; } HTTPSClientSession session(uri.getHost(), uri.getPort()); HTTPRequest request(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1); session.sendRequest(request); HTTPResponse response; std::istream& rs = session.receiveResponse(response); std::stringstream responseStream; responseStream << rs.rdbuf(); logger.information("https response: code %d, reason %s, body %s", static_cast<int>(response.getStatus()), response.getReason(), responseStream.str()); } } // namespace TContext::TContext(const std::string& configPath) : Config_{ConstructConfig(configPath)} , HttpServer_{ConstructHttpServer(*this)} , StatesHolder_{*this} , Mongo_{*this} , Octoshell_{*this} { InitLogs(*Config_); SetTelegramWebhook(*Config_); } void TContext::StartServer() { HttpServer_->start(); Logger().information("Server started"); } void TContext::StopServer() { HttpServer_->stopAll(); Logger().information("Server stopped"); } const Util::PropertyFileConfiguration& TContext::Config() const { return *Config_; } const TTranslate& TContext::Translate() const { return Translate_; } TMongo& TContext::Mongo() { return Mongo_; } TOctoshell& TContext::Octoshell() { return Octoshell_; } Logger& TContext::Logger() const { return Logger::get("context"); } TReactions TContext::OnUpdate(TUpdate update, const TUserState_ESource source) { auto lang = TUserState_ELanguage_EN; try { Logger().information("working with update from %" PRIu64, update.UserId); TUserState state = Mongo_.Load(update.UserId, source); TReactions reactions = StatesHolder_.ProcessUpdate(update, state); lang = state.language(); for (auto& r : reactions) { TranslateReaction(r, lang, Translate_); } state.set_source(source); Mongo_.Store(state); return reactions; } catch (const std::exception& e) { Logger().error(e.what()); TReaction reaction; reaction.Text = "unavailable"; TranslateReaction(reaction, lang, Translate_); return {std::move(reaction)}; } } } // namespace NOctoshell <file_sep>CMAKE_MINIMUM_REQUIRED(VERSION 2.8.4) INCLUDE(FindProtobuf) FIND_PACKAGE(Protobuf REQUIRED) INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR}) PROTOBUF_GENERATE_CPP(PROTO_SRC PROTO_HEADER user_state.proto) ADD_LIBRARY(proto ${PROTO_HEADER} ${PROTO_SRC}) <file_sep>#pragma once #include <vector> #include <string> namespace NOctoshell { std::string UrlQuote(std::string s, bool escapeUnderscore = false); std::vector<std::string> DivideMessage(const std::string& msg, size_t msgSize); } // namespace NOctoshell <file_sep>#pragma once #include <proto/user_state.pb.h> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> #include "fwd.h" namespace NOctoshell { class TMongo { public: TMongo(TContext& ctx); TUserState Load(std::uint64_t userId, const TUserState_ESource source); std::vector<TUserState> LoadByAuth(const std::string& email, const std::string& token); void Store(const TUserState& state); private: TContext& Ctx_; mongocxx::instance Instance_; mongocxx::client Client_; mongocxx::database Database_; mongocxx::collection StatesCollection_; }; } // namespace NOctoshell <file_sep>#pragma once #include "context.h" #include <Poco/Net/HTTPRequestHandler.h> #include <Poco/Net/HTTPRequestHandlerFactory.h> #include <Poco/Net/HTTPServerRequest.h> namespace NOctoshell { class THandlerFactory final : public Poco::Net::HTTPRequestHandlerFactory { public: THandlerFactory(TContext& ctx); Poco::Net::HTTPRequestHandler* createRequestHandler(const Poco::Net::HTTPServerRequest& request) override; private: TContext& Ctx_; }; } // namespace NOctoshell <file_sep>unavailable=Сервис Octoshell временно недоступен main.message=Нажмите на кнопку в меню main.fail-auth=Установите корректные данные для аутентификации main.projects.header=📚 Проектов пользователя: main.projects.number=📖 Проект № main.projects.login=Логин пользователя main.projects.title=Название main.projects.state=Статус main.projects.is-owner=Является владельцем main.projects.is-not-owner=Не является владельцем main.projects.updated-at=Обновлено main.tickets.header=🎫 Заявок пользователя: main.tickets.number=🎟️ Заяка № main.tickets.who-status=Статус юзера main.tickets.who-is-reporter=📢 Репортер main.tickets.who-is-responsible=👓 Ответственный main.tickets.topic-title=Тема main.tickets.project-title=Проект main.tickets.cluster-title=Кластер main.tickets.subject-title=Заголовок main.tickets.desc=Описание main.tickets.updated-at=Обновлено main.tickets.state-title=Состояние main.tickets.state.answered_by_reporter=Есть ответ от автора main.tickets.state.answered_by_support=Есть ответ от поддержки main.tickets.state.closed=Закрыта main.tickets.state.pending=Ожидает обработки main.tickets.state.resolved=Решена main.tickets.projects.message=Шаг 1/5. Выберите проект main.tickets.topics.message=Шаг 2/5. Выберите тематику main.tickets.clusters.message=Шаг 3/5. Выберите кластер main.tickets.subject.message=Шаг 4/5. Введите тему заявки (краткое описание) main.tickets.message.message=Шаг 5/5. Введите текст заявки (полное описание) main.tickets.response.message=Статус создания заявки main.jobs.header=🎯 Задач пользователя main.jobs.number=📜 Задача main.jobs.state=Статус main.jobs.submitted=Создано main.jobs.started=Запуск main.jobs.ended=Завершение main.jobs.command=Команда main.jobs.num-nodes=Узлов main.jobs.num-cores=ядер main.jobs.duration-hours=Время счета (часы) main.jobs.rules=Найденные проблемы main.button.show-user-projects=🎨 Показать проекты main.button.show-user-jobs=🎯 Показать задачи main.button.to-auth-settings=🔐 Настройки аутентификации main.button.to-locale-settings=🌎 Настройки языка main.button.show-tickets=🎫👀 Показать заявки main.button.create-tickets=✏️🎫 Создать заявку main.button.information=ℹ️ Информация о боте main.information=Этот бот может выполнять некоторые действия: уведомлять о решениях запроса, регистрировать запросы, показывать проекты.\n\n\ Чтобы получить доступ к функциям, необходимо зайти в раздел аутентификации и ввести свой e-mail и токен.\n\n\ Токен для бота можно сгенерировать в Octoshell в разделе "Профиль". auth.email.message=Введите новый e-mail auth.email.wrong.message=Введён некорректный e-mail! auth.token.message=Введите новый токен auth.message=Нажмите на кнопку в меню. Здесь Вы можете ввести Ваш email и токен. auth.blank-email=<Пустой e-mail> auth.blank-token=<Пустой токен> auth.settings.header=⚙️ Настройки аутентификации auth.settings.email=E-mail auth.settings.token=<PASSWORD> auth.check.header=🔮 Проверка подключения auth.status.success=Успешная аутентификация! auth.status.inactive-token=Введен неактивный токен auth.status.wrong-token=Введен неверный токен auth.status.wrong-email=Введен неверный email auth.status.service-unavailable=Сервис временно недоступен auth.button.change-email=📧 Поменять e-mail auth.button.change-token=🔑 Поменять токен auth.button.show-settings=👀 Вывести текущие настройки авторизации auth.button.check-connection=🔌 Проверка подключения к Octoshell auth.button.back=🚪 Назад locale.message=Выберите язык locale.button.russian=🇷🇺 Русский locale.button.english=🇬🇧 English notify.ticket.header=🎫 Уведомление о заявке notify.ticket.subject=Тема заявки notify.ticket.status.close=🚫 Заявка закрыта notify.ticket.status.resolve=☑️ Заявка решёна! notify.ticket.status.reopen=📖️ Заявка переоткрыта notify.ticket.status.update=➕ Заявка обновлена notify.announcement.header=📣 Вам пришла рассылка notify.announcement.type.title=Тип рассылки notify.announcement.type.info=Информационная notify.announcement.type.service=Служебная notify.announcement.title=✉️ Заголовок notify.announcement.body=✉️ Тело notify.announcement.has-attachment=Рассылка имеет вложение, его можно увидеть на сайте
dea7cbac3f1d04759642ceefc37332d2b75e7e74
[ "CMake", "Markdown", "Dockerfile", "INI", "C++" ]
41
C++
Izaron/octoshell-bot
0d6e7c3fbca670146111e2e44c098e212011cd08
1905843adcba79045552182a2b2dfb02c485dcee
refs/heads/master
<file_sep>package kz.bsbnb.usci.sync.service.impl; import kz.bsbnb.usci.receiver.client.BatchClient; import kz.bsbnb.usci.sync.service.BatchService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.Map; /** * @author <NAME> */ @Service public class BatchServiceImpl implements BatchService { private static final Logger logger = LoggerFactory.getLogger(BatchServiceImpl.class); private final BatchClient batchClient; public BatchServiceImpl(BatchClient batchClient) { this.batchClient = batchClient; } @Override public void endBatch(long batchId) { try { batchClient.endBatch(batchId); } catch(Exception e) { logger.error("Ошибка вызова метода feign клиента", e); } } @Override public boolean incrementActualCounts(Map<Long, Long> batchesToUpdate) { try { return batchClient.incrementActualCounts(batchesToUpdate); } catch(Exception e) { logger.error("Ошибка вызова метода feign клиента", e); } return false; } } <file_sep>package kz.bsbnb.usci.eav.model.core; import kz.bsbnb.usci.eav.model.base.BaseEntity; import java.io.Serializable; /** * @author <NAME> */ public class EavHub implements Serializable { private Long respondentId; private String entityKey; private String newEntityKey; private Long metaClassId; private Long entityId; private Long parentEntityId; private Long parentClassId; private Long batchId; public EavHub() { /*Пустой конструктор*/ } public EavHub(BaseEntity baseEntity, String key) { this.entityId = baseEntity.getId(); this.parentClassId = baseEntity.parentIsKey()? baseEntity.getParentEntity().getMetaClass().getId(): 0; this.parentEntityId = baseEntity.parentIsKey()? baseEntity.getParentEntity().getId(): 0; this.entityKey = key; this.metaClassId = baseEntity.getMetaClass().getId(); this.respondentId = baseEntity.getRespondentId(); this.batchId = baseEntity.getBatchId(); } public EavHub(BaseEntity baseEntity, String oldEntityKey, String newEntityKey) { this(baseEntity, oldEntityKey); this.newEntityKey = newEntityKey; } //region Getters and Setters public Long getRespondentId() { return respondentId; } public void setRespondentId(Long respondentId) { this.respondentId = respondentId; } public Long getParentClassId() { return parentClassId; } public void setParentClassId(Long parentClassId) { this.parentClassId = parentClassId; } public String getEntityKey() { return entityKey; } public void setEntityKey(String entityKey) { this.entityKey = entityKey; } public String getNewEntityKey() { return newEntityKey; } public void setNewEntityKey(String newEntityKey) { this.newEntityKey = newEntityKey; } public Long getMetaClassId() { return metaClassId; } public void setMetaClassId(Long metaClassId) { this.metaClassId = metaClassId; } public Long getEntityId() { return entityId; } public void setEntityId(Long entityId) { this.entityId = entityId; } public Long getParentEntityId() { return parentEntityId; } public void setParentEntityId(Long parentEntityId) { this.parentEntityId = parentEntityId; } public Long getBatchId() { return batchId; } public void setBatchId(Long batchId) { this.batchId = batchId; } //endregion @Override public String toString() { return "EavHub{" + "respondentId=" + respondentId + ", entityKey='" + entityKey + '\'' + ", newEntityKey='" + newEntityKey + '\'' + ", metaClassId=" + metaClassId + ", entityId=" + entityId + ", parentEntityId=" + parentEntityId + ", parentClassId=" + parentClassId + ", batchId=" + batchId + '}'; } } <file_sep>package kz.bsbnb.usci.model.respondent; import java.time.LocalDateTime; /** * @author <NAME> */ public class ConfirmStageJson { private Long id; private Long confirmId; private Long statusId; private String statusName; private LocalDateTime stageDate; private Long userId; private String userName; private String signature; private byte[] document; private Long userPosId; private String userPosName; public ConfirmStageJson() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getConfirmId() { return confirmId; } public void setConfirmId(Long confirmId) { this.confirmId = confirmId; } public Long getStatusId() { return statusId; } public void setStatusId(Long statusId) { this.statusId = statusId; } public String getStatusName() { return statusName; } public void setStatusName(String statusName) { this.statusName = statusName; } public LocalDateTime getStageDate() { return stageDate; } public void setStageDate(LocalDateTime stageDate) { this.stageDate = stageDate; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public byte[] getDocument() { return document; } public void setDocument(byte[] document) { this.document = document; } public Long getUserPosId() { return userPosId; } public void setUserPosId(Long userPosId) { this.userPosId = userPosId; } public String getUserPosName() { return userPosName; } public void setUserPosName(String userPosName) { this.userPosName = userPosName; } } <file_sep>package kz.bsbnb.usci.receiver.parser.impl; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseValue; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.receiver.parser.BatchParser; import kz.bsbnb.usci.receiver.parser.exceptions.UnknownTagException; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.xml.sax.SAXException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** * @author <NAME> * @author <NAME> */ @Component @Scope("prototype") public class ChangeTurnoverParser extends BatchParser { public ChangeTurnoverParser() { super(); } private BaseEntity currentIssue; private BaseEntity currentInterest; boolean interestFlag = false; private BaseEntity currentDebt; boolean debtFlag = false; private MetaClass refTurnOverIssueMeta, refTurnOverIssueDebtMeta, refTurnOverissueInterestMeta; @Override public void init() { currentBaseEntity = new BaseEntity(metaClassRepository.getMetaClass("turnover"), respondentId, batch.getReportDate(), batch.getId()); currentIssue = null; currentInterest = null; interestFlag = false; currentDebt = null; debtFlag = false; refTurnOverIssueMeta = metaClassRepository.getMetaClass("turnover_issue"); refTurnOverIssueDebtMeta = metaClassRepository.getMetaClass("turnover_issue_debt"); refTurnOverissueInterestMeta = metaClassRepository.getMetaClass("turnover_issue_interest"); } @Override public boolean startElement(XMLEvent event, StartElement startElement, String localName) throws SAXException { switch (localName) { case "turnover": break; case "issue": currentIssue = new BaseEntity(refTurnOverIssueMeta, respondentId, batch.getReportDate(), batch.getId()); break; case "debt": currentDebt = new BaseEntity(refTurnOverIssueDebtMeta, respondentId, batch.getReportDate(), batch.getId()); debtFlag = true; break; case "interest": currentInterest = new BaseEntity(refTurnOverissueInterestMeta, respondentId, batch.getReportDate(), batch.getId()); interestFlag = true; break; case "amount": if (interestFlag) { event = (XMLEvent) xmlReader.next(); currentInterest.put("amount", new BaseValue(new Double(trim(event.asCharacters().getData())))); } else if (debtFlag) { event = (XMLEvent) xmlReader.next(); currentDebt.put("amount", new BaseValue(new Double(trim(event.asCharacters().getData())))); } break; case "amount_currency": if (interestFlag) { event = (XMLEvent) xmlReader.next(); currentInterest.put("amount_currency", new BaseValue(new Double(trim(event.asCharacters().getData())))); } else if (debtFlag) { event = (XMLEvent) xmlReader.next(); currentDebt.put("amount_currency", new BaseValue(new Double(trim(event.asCharacters().getData())))); } break; default: throw new UnknownTagException(localName); } return false; } @Override public boolean endElement(String localName) throws SAXException { switch (localName) { case "turnover": return true; case "issue": currentBaseEntity.put("issue", new BaseValue(currentIssue)); break; case "debt": debtFlag = false; currentIssue.put("debt", new BaseValue(currentDebt)); break; case "interest": interestFlag = false; currentIssue.put("interest", new BaseValue(currentInterest)); break; case "amount": break; case "amount_currency": break; default: throw new UnknownTagException(localName); } return false; } } <file_sep>package kz.bsbnb.usci.mail.dao; import kz.bsbnb.usci.mail.model.MailTemplate; import kz.bsbnb.usci.mail.model.UserMailTemplate; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @Repository public class MailTemplateDaoImpl implements MailTemplateDao { private final MailTemplateMapper mailTemplateMapper = new MailTemplateMapper(); private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; public MailTemplateDaoImpl(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) { this.jdbcTemplate = jdbcTemplate; this.npJdbcTemplate = npJdbcTemplate; } public MailTemplate getTemplate(String code) { return jdbcTemplate.queryForObject("select * from USCI_MAIL.MAIL_TEMPLATE where CODE = ?", new Object[]{code}, mailTemplateMapper); } @Override public boolean isTemplateEnabledForUser(Long templateId, long userId) { int count = jdbcTemplate.queryForObject("select count(ID)\n" + " from USCI_MAIL.MAIL_USER_MAIL_TEMPLATE\n" + " where PORTAL_USER_ID = ?\n" + " and MAIL_TEMPLATE_ID = ?" + " and ENABLED = 1", new Object[]{userId, templateId}, Integer.class); return count > 0; } @Override public List<UserMailTemplate> getUserMailTemplateList(Long userId) { String query = "select mt.ID,\n" + " mt.ENABLED,\n" + " m.ID as MAIL_TEMPLATE_ID,\n" + " m.CODE,\n" + " m.NAME_RU,\n" + " m.NAME_KZ,\n" + " m.CONFIG_TYPE_ID,\n" + " m.SUBJECT,\n" + " m.TEXT\n" + "from USCI_MAIL.MAIL_USER_MAIL_TEMPLATE mt, USCI_MAIL.MAIL_TEMPLATE m\n" + "where mt.MAIL_TEMPLATE_ID = m.ID\n" + " and mt.PORTAL_USER_ID = :userId"; MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("userId", userId); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); List<UserMailTemplate> userMailTemplateList = new ArrayList<>(); for (Map<String, Object> row : rows) { UserMailTemplate userMailTemplate = new UserMailTemplate(); userMailTemplate.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); userMailTemplate.setEnabled(SqlJdbcConverter.convertToBoolean(row.get("ENABLED"))); userMailTemplate.setUserId(userId); userMailTemplate.setMailTemplate(mapRowToMailTemplate(row)); userMailTemplateList.add(userMailTemplate); } return userMailTemplateList; } @Override public void saveUserMailTemplateList(List<UserMailTemplate> userMailTemplateList) { List<MapSqlParameterSource> params = new ArrayList<>(); for (UserMailTemplate userMailTemplate : userMailTemplateList) { params.add(new MapSqlParameterSource("enabled", SqlJdbcConverter.convertToByte(userMailTemplate.isEnabled())) .addValue("id", userMailTemplate.getId())); } String query = "update USCI_MAIL.MAIL_USER_MAIL_TEMPLATE\n" + "set ENABLED = :enabled\n" + "where ID = :id"; if (userMailTemplateList.size() > 1) { int counts[] = npJdbcTemplate.batchUpdate(query, params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException("Ошибка update записи в таблице USCI_MAIL.MAIL_USER_MAIL_TEMPLATE"); } else { int count = npJdbcTemplate.update(query, params.get(0)); if (count != 1) throw new UsciException("Ошибка update записи в таблице USCI_MAIL.MAIL_USER_MAIL_TEMPLATE"); } } private MailTemplate mapRowToMailTemplate(Map<String, Object> row) { MailTemplate mailTemplate = new MailTemplate(); mailTemplate.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); mailTemplate.setCode(String.valueOf(row.get("CODE"))); mailTemplate.setText(String.valueOf(row.get("TEXT"))); mailTemplate.setSubject(String.valueOf(row.get("SUBJECT"))); mailTemplate.setNameRu(String.valueOf(row.get("NAME_RU"))); mailTemplate.setNameKz(String.valueOf(row.get("NAME_KZ"))); mailTemplate.setTypeId(SqlJdbcConverter.convertToLong(row.get("CONFIG_TYPE_ID"))); return mailTemplate; } private static class MailTemplateMapper implements RowMapper<MailTemplate> { @Override public MailTemplate mapRow(ResultSet rs, int rowNum) throws SQLException { MailTemplate mailTemplate = new MailTemplate(); mailTemplate.setId(rs.getLong("ID")); mailTemplate.setCode(rs.getString("CODE")); mailTemplate.setText(rs.getString("TEXT")); mailTemplate.setSubject(rs.getString("SUBJECT")); mailTemplate.setNameRu(rs.getString("NAME_RU")); mailTemplate.setNameKz(rs.getString("NAME_KZ")); mailTemplate.setTypeId(rs.getLong("CONFIG_TYPE_ID")); return mailTemplate; } } } <file_sep>package kz.bsbnb.usci.util.balancer; import java.util.List; import java.util.Optional; public class CircleRoundRobin<T> extends RoundRobin<T> { private int cursor; public CircleRoundRobin(final List<T> list) { super(list); cursor = 0; } @Override public synchronized Optional<T> get() { if (routes.isEmpty()) { return Optional.empty(); } return Optional.of(routes.get(getCursor())); } private synchronized int getCursor() { try { return cursor++; } finally { if (cursor >= (size)) { cursor = 0; } } } } <file_sep>var label_SEND = 'Жіберу'; var label_EDIT = 'Өңдеу'; var label_DATE = 'Күні'; var label_CODE = 'Коды'; var label_TITLE = 'Аты'; var label_ITEMS = 'Элементтер'; var label_ERROR = 'Қате'; var label_ERROR_NO_DATA = 'Мәліметтерді алу мүмкін емес'; var label_VIEW = 'Көру'; var label_ERROR_NO_DATA_FOR = 'Мәліметтерді алу мүмкін емес: {0}'; var label_SAVE = 'Сақтау'; var label_CANCEL = 'Болдырмау'; var label_VALUE = 'Мәні'; var label_SIMPLE = 'Қарапайым'; var label_ARRAY = 'Массив'; var label_TYPE = 'Тип'; var label_INPUT_FORM = "Енгізу формасы"; var label_REF = 'Анықтама'; var label_ITEMS = 'Элементтер'; var label_ENTITY_ID = 'Болмыс идентификаторы'; var label_DEL = 'Жою'; var label_CLOSE = 'Жабу'; var label_CLASS = 'Класс'; var LABEL_UPDATE = 'Жанарту'; var label_date = 'Күні'; var label_CONFIRM_CHANGES = "Өзгерістерді растау"; var label_REQUIRED_FIELD = "Міндетті өріс"; var label_SUBJECT_NAME = "Жылдам шолу"; var label_LOADING = "Жүктеп жатыр..."; var label_NUll_SEARCH = 'Іздеу нәтижесі 0 нәтиже берді'; var label_BVU_NO = 'ЕДБ/КЕҰ'; var label_CONTRACT = 'Қарыз туралы шарт / шартты міндеттемелер (кредит)'; var label_DOGOVOR = 'Шарт'; var label_NUMBER = 'Нөмір'; var label_YES = 'Ия'; var label_NO ='Жоқ'; var label_ADD_TO = 'Қосылу '; var label_SAVE_NEW_RECORD = 'Жаңа жазбаны сақтаңыз'; var label_PROF_WORKS = "Алдын алу жұмыстары жүріп жатыр, өтінімді кейінірек орындауға тырысыңыз."; var label_ALL_INFO = "Барлық ақпарат "; var label_ALREADY_ADDED = " қазірдің өзінде қосылды"; var label_ADD_ELEMENT = "Элементті қосу"; var label_NOT_ADDED_KEY_ATRIBUT = "Негізгі төлсипат жоқ: "; var label_ADD = 'Қосу'; var label_SUCCEFUL_SAVED = "Сәтті сақталды. Өзгерістеріңізді \"Өзгертулерді жіберу\" портлеті арқылы жіберуіңіз керек"; var label_APLLY_DELETE = 'Жою үшін растау?'; var label_ARE_YOU_SURE_DELETE = 'Вы точно хотите отметить на удаление? '; var label_MEAN = ' мән: '; var label_YES = "Ия"; var label_NO = "Жоқ"; var label_SUCC_OPERATION = "Операция сәтті өтті. Міндетті "; var label_DATA_SAVE = "деректерді сақтап, өңдеуге жіберіңіз"; var label_OPERATION_SUCC = "Операция сәтті аяқталды"; var label_ADD_RECORD = 'Жазбаны қосу'; var label_ADD_ELEEMENT_MASSIV = 'Массив элементін қосу'; var label_SEARCH_TYPE = 'Іздеу түрі'; var label_ALL_RESULTS = 'Жалпы нәтижелер:'; var label_NON_SAVED = 'Менде сақталмаған деректер бар'; var label_UPDATE_RECORD = 'Жазбаны жаңарту'; var label_RULES = 'Ережелер'; var label_ERROR_RULES = 'Бизнес ережесінің қатесі'; var label_ERRORS = 'Қателер'; var label_NO_ERRORS = "Бизнес ережелері бойынша табысты сыналды. Қателер жоқ."; var label_OPEN_DATE = 'Ашылу күні'; var label_CLOSE_DATE = 'Жабу күні'; var label_SEND_CHANGES = 'Өзгерістерді жіберіңіз'; var label_CHANGE = 'Таңдау'; var label_DIFFERENT_REP_DATES = "Әр түрлі есепті күндер үшін жойылмайды"; var label_CHANGING = ', Өзгерту:'; var label_REF_CHOOSE = 'Анықтамалықты таңдау \"'; var label_REF_CHOICE = 'Анықтамалықты таңдаңыз'; var label_CONTRACT_NUMBER = 'Шарт нөмірі'; var label_CONTRACT_DATE ='Келісімшарт мерзімі'; var label_DO_YOU_WANT_TO_ADD = 'Іздестіру нәтижесі 0 қайтарылды, жаңа келісімшартты қосқыңыз келе ме?'; var label_DOCS = "Құжаттар"; var label_ADD_SEARCH_DOC = 'іздеу құжатын қосыңыз'; var label_CLEAR = 'Тазарту'; var label_PERSONS_NAME = 'Атауы'; var label_LAST_NAME = 'Тегі'; var label_MIDDLE_NAME = '<NAME>'; var label_RESPONDENT_TYPE = 'Кредитордың типі'; var label_UR = 'Заңды беті'; var label_FIZ = 'Жеке тұлға'; var label_BANK = 'Банкі'; var label_CONTINUE = 'Келесі'; var label_ADD_DOC_SEARCH = 'іздеу құжатын қосыңыз'; var label_CLEAR = 'Тазарту'; var label_RESPONDENT = 'Кредиторі'; var label_BATCH = 'Батч'; var errors = { "communication failure" : "уакыт шамадан тыс, суракты толыктыру мумкиндигин карастырыныз" } <file_sep>group = 'kz.bsbnb.usci.sync' version '0.1.0' dependencies { compile project(':util') compile project(':eav:eav-api') compile project(':sync:sync-api') compile project(':receiver:receiver-api') runtime("org.springframework.boot:spring-boot-starter-web") runtime("org.springframework.boot:spring-boot-starter-jdbc") } jar { baseName = 'usci-sync-core' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>package kz.bsbnb.usci.wsclient.model.currency; import java.time.LocalDate; public class NSIEntitySystem { private Long entityNum; private String operType; private LocalDate operDate; private Long entityID; private LocalDate beginDate; private LocalDate endDate; public NSIEntitySystem() { } public Long getEntityNum() { return entityNum; } public void setEntityNum(Long entityNum) { this.entityNum = entityNum; } public String getOperType() { return operType; } public void setOperType(String operType) { this.operType = operType; } public LocalDate getOperDate() { return operDate; } public void setOperDate(LocalDate operDate) { this.operDate = operDate; } public Long getEntityID() { return entityID; } public void setEntityID(Long entityID) { this.entityID = entityID; } public LocalDate getBeginDate() { return beginDate; } public void setBeginDate(LocalDate beginDate) { this.beginDate = beginDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } } <file_sep>group = 'kz.bsbnb.usci' version = '0.1.0' dependencies { compile project(':model') compile project(':util:util-api') compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.cloud:spring-cloud-starter-openfeign') compile('org.springframework.boot:spring-boot-starter-jdbc') compile('org.springframework.boot:spring-boot-starter-web') } bootJar { baseName = 'usci-fstore' version = '0.1.0' } springBoot { mainClassName = 'kz.bsbnb.usci.fstore.FstoreApplication' }<file_sep>package kz.bsbnb.usci.core.dao; import kz.bsbnb.usci.model.creditor.AuditEvent; import kz.bsbnb.usci.model.json.AuditJson; import java.util.List; public interface AuditDao { void insertAuditEvent(AuditEvent auditEvent); List<AuditEvent> getAudit(long userId); List <AuditJson> getAuditJson(long userId); } <file_sep>package kz.bsbnb.usci.core.controller; import kz.bsbnb.usci.core.service.PositionService; import kz.bsbnb.usci.model.adm.Position; import kz.bsbnb.usci.util.json.ext.ExtJsJson; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author <NAME> */ @RestController @RequestMapping(value = "/position") public class PositionRestController { private final PositionService positionService; public PositionRestController(PositionService positionService) { this.positionService = positionService; } @GetMapping(value = "getPositionList") public List<Position> getPositionList() { return positionService.getPositionList(); } @GetMapping(value = "getUserPositionListByProduct") public List<Position> getUserPositionListByProduct(@RequestParam(name = "userId") Long userId, @RequestParam(name = "productId") Long productId) { return positionService.getUserPosListByProductId(userId, productId); } @GetMapping(value = "getPositionById") public Position getPositionById(@RequestParam(name = "id") Long id) { return positionService.getPositionById(id); } @PutMapping(value = "addUserPosition") public ExtJsJson addUserPosition(@RequestParam(name = "userId") Long userId, @RequestParam(name = "productId") Long productId, @RequestParam(name = "positionIds") List<Long> positionIds) { positionService.addUserPosition(userId, productId, positionIds); return new ExtJsJson(true); } @PostMapping(value = "delUserPosition") public ExtJsJson delUserPosition(@RequestParam(name = "userId") Long userId, @RequestParam(name = "productId") Long productId, @RequestParam(name = "positionIds") List<Long> positionIds) { positionService.delUserPosition(userId, productId, positionIds); return new ExtJsJson(true); } } <file_sep>package kz.bsbnb.usci.model.util; /** * @author <NAME> */ public interface ConstantType { String type(); String code(); } <file_sep>package kz.bsbnb.usci.util.dao.impl; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.model.util.Text; import kz.bsbnb.usci.util.dao.TextDao; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * @author <NAME> */ @Repository public class TextDaoImpl implements TextDao { private final NamedParameterJdbcTemplate npJdbcTemplate; private SimpleJdbcInsert textInsert; public TextDaoImpl(NamedParameterJdbcTemplate npJdbcTemplate) { this.npJdbcTemplate = npJdbcTemplate; this.textInsert = new SimpleJdbcInsert(npJdbcTemplate.getJdbcTemplate()) .withSchemaName("USCI_UTIL") .withTableName("CONSTANT_") .usingGeneratedKeyColumns("ID"); } @Override public Long insert(Text text) { Number id = textInsert.executeAndReturnKey(new MapSqlParameterSource() .addValue("TYPE", text.getType()) .addValue("CODE", text.getCode()) .addValue("NAME_RU", text.getNameRu()) .addValue("NAME_KZ", text.getNameKz())); text.setId(id.longValue()); return id.longValue(); } @Override public void update(Text text) { int count = npJdbcTemplate.update("update USCI_UTIL.CONSTANT_\n" + " set TYPE = :type, CODE = :code, NAME_RU = :nameRu, NAME_KZ = :nameKz\n" + " where ID = :id", new MapSqlParameterSource("id", text.getId()) .addValue("type", text.getType()) .addValue("code", text.getCode()) .addValue("nameRu", text.getNameRu()) .addValue("nameKz", text.getNameKz())); if (count != 1) throw new UsciException("Ошибка update записи в таблице USCI_UTIL.CONSTANT_"); } @Override public void delete(Long id) { int count = npJdbcTemplate.update("delete from USCI_UTIL.CONSTANT_ where ID = :id", new MapSqlParameterSource("id", id)); if (count != 1) throw new UsciException("Ошибка delete записи из таблицы USCI_UTIL.CONSTANT_"); } @Override public Text get(String type, String code) { return npJdbcTemplate.queryForObject("select * from USCI_UTIL.CONSTANT_ where TYPE = :type and CODE = :code", new MapSqlParameterSource("type", type) .addValue("code", code), new TextMapper()); } @Override public Text get(Long id) { return npJdbcTemplate.queryForObject("select * from USCI_UTIL.CONSTANT_ where ID = :id", new MapSqlParameterSource("id", id), new TextMapper()); } @Override public List<Text> getAll() { return npJdbcTemplate.query("select * from USCI_UTIL.CONSTANT_", new TextMapper()); } @Override public List<Text> getConstantsByType(List<String> types) { return npJdbcTemplate.query("select * from USCI_UTIL.CONSTANT_ where TYPE in (:types)", new MapSqlParameterSource("types", types), new TextMapper()); } private class TextMapper implements RowMapper<Text> { TextMapper() { } public Text mapRow(ResultSet rs, int rowNum) throws SQLException { return new Text() .setId(rs.getLong("ID")) .setType(rs.getString("TYPE")) .setCode(rs.getString("CODE")) .setNameRu(rs.getString("NAME_RU")) .setNameKz(rs.getString("NAME_KZ")); } } } <file_sep>Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.selection.CellModel', 'Ext.grid.*', 'Ext.data.*', 'Ext.button.*', 'Ext.toolbar.*', 'Ext.container.*' ]); Ext.onReady(function(){ Ext.Date.patterns={ CustomFormat: "d.m.Y" }; function getFileName(value) { var startIndex = (value.indexOf('\\') >= 0 ? value.lastIndexOf('\\') : value.lastIndexOf('/')); var filename = value.substring(startIndex); if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) { filename = filename.substring(1); } return filename; } var maintenanceRespondentsStore = Ext.create('Ext.data.Store', { id: 'maintenanceRespondentsStore', fields: ['id', 'name', 'shortName', 'code', 'shutdownDate', 'changeDate', 'bin', 'rnn', 'bik', 'mainOffice', 'branches', 'subjectType'], autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/core/respondent/getUserRespondentList', extraParams: {userId: userId}, actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'name', direction: 'asc' }] }); var maintenanceBatchStore = Ext.create('Ext.data.Store', { id: 'maintenanceBatchStore', fields: ['id', 'reportDate', 'receiverDate', 'processBeginDate', 'processEndDate', 'fileName', 'statusId', 'status', 'respondent', 'respondentId', 'productId', 'product', 'totalEntityCount', 'actualEntityCount', 'successEntityCount', 'errorEntityCount', 'check'], autoLoad: false, proxy: { type: 'ajax', url: dataUrl+'/receiver/batch/getMaintenanceBatchList', method: 'GET', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } }, }); var panel = Ext.create('Ext.panel.Panel', { height: 900, width: 1200, renderTo: 'approval-content', id: 'MainPanel', items: [{ xtype: 'panel', title: label_APPROVAL, items: [{ xtype: 'panel', height: 900, margin: 0, width: 1200, title: '', titleCollapse: false, items: [{ xtype: 'displayfield', padding: 3, style: 'font-size: 20px;', labelCls: 'biggertext', value: label_ORGS, fieldCls: 'biggertext' }, { xtype: 'textfield', padding: 3, width: 1190, listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp("respondentsGrid"); if (newValue == '') { grid.store.clearFilter(); grid.getView().refresh(); } else { grid.store.filter([{ property: "name", value: newValue, anyMatch: true, caseSensitive: false }]); } } } }, { xtype: 'gridpanel', store: maintenanceRespondentsStore, multiSelect: true, height: 244, width: 1195, padding: 5, autoScroll: true, title: '', hideHeaders: true, id: 'respondentsGrid', scroll: 'vertical', columns: [{ xtype: 'gridcolumn', width: '100%', dataIndex: 'name', text: '' }], viewConfig: { autoScroll: false } }, { xtype: 'button', margin: 5, padding: 3, text: label_SELECT_ALL, listeners: { click: function () { Ext.getCmp('respondentsGrid').getSelectionModel().selectAll(); } } }, { xtype: 'datefield', id: 'reportDate', padding: 5, fieldLabel: label_REP_DATE, labelAlign: 'top', labelStyle: 'font-weight: bold;', format: 'd.m.Y' }, { xtype: 'button', margin: '0 5 0 5', text: label_DOWN_Q, listeners: { click: function () { grid = Ext.getCmp("respondentsGrid"); gridBatch = Ext.getCmp("maintenanceBatchGrid"); var credIds = []; for (var i = 0; i < grid.store.getCount(); i++) { if (grid.getSelectionModel().isSelected(i)) { credIds.push(grid.store.getAt(i).data.id); } } gridBatch.store.load({ params: { respondentIds: credIds, reportDate: Ext.Date.format(Ext.getCmp('reportDate').value, Ext.Date.patterns.CustomFormat), userId: userId }, scope: this }); gridBatch.getView().refresh(); } } }, { xtype: 'gridpanel', id: 'maintenanceBatchGrid', store: maintenanceBatchStore, height: 400, width: 1190, margin: '5 0 15 5', autoScroll: true, title: '', columns: [{ xtype: 'checkcolumn', dataIndex : 'check', width: 60, text: '' }, { xtype: 'gridcolumn', width: 220, dataIndex: 'respondent', renderer: function(value, metaData, record, rowIndex, colIndex, store, view) { return value.name; }, text: label_ORG_NAME }, { xtype: 'gridcolumn', width: 220, dataIndex: 'fileName', text: label_FILE_NAME, renderer : function(value, obj, record) { var filename = getFileName(value); return '<a href="#">'+filename+'</a>'; } }, { xtype: 'datecolumn', width: 130, dataIndex: 'receiverDate', text: label_REC_DATE, format: 'd.m.Y H:i:s' }, { xtype: 'datecolumn', width: 136, dataIndex: 'processBeginDate', text: label_BEG_DATE, format: 'd.m.Y H:i:s' }, { xtype: 'datecolumn', width: 130, dataIndex: 'processEndDate', text: label_END_DATE, format: 'd.m.Y H:i:s' }, { xtype: 'gridcolumn', width: 95, dataIndex: 'status', renderer: function(value, metaData, record, rowIndex, colIndex, store, view) { return value.nameRu; }, text: label_STATUS }, { xtype: 'datecolumn', width: 100, dataIndex: 'reportDate', text: label_DATE_REP, format: 'd.m.Y' }], dockedItems: [{ xtype: 'toolbar', dock: 'bottom', items: [{ xtype: 'button', disabled: isDataManager, text: label_SEND, listeners: { click: function () { gridBatch = Ext.getCmp("maintenanceBatchGrid"); var batchIds = []; var records = []; for (var i = 0; i < gridBatch.store.getCount(); i++) { if (gridBatch.store.getAt(i).data.check === true) { batchIds.push(gridBatch.store.getAt(i).data.id); records.push(gridBatch.store.getAt(i)); } } Ext.Ajax.request({ url: dataUrl+'/receiver/batch/approveAndSendMaintenance', method: 'POST', params: { batchIds: batchIds }, reader: { type: 'json', root: 'data' }, success: function() { Ext.Msg.alert(label_CONFIRMED); gridBatch.store.remove(records); }, failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); gridBatch.getView().refresh(); } } }, { xtype: 'tbseparator' }, { xtype: 'button', disabled: isDataManager, text: label_CANCAL, listeners: { click: function () { gridBatch = Ext.getCmp("maintenanceBatchGrid"); var batchIds = []; var records = []; for (var i = 0; i < gridBatch.store.getCount(); i++) { if (gridBatch.store.getAt(i).data.check === true) { batchIds.push(gridBatch.store.getAt(i).data.id); records.push(gridBatch.store.getAt(i)); } } Ext.Ajax.request({ url: dataUrl+'/receiver/batch/declineAndSendMaintenance', method: 'POST', params: { batchIds: batchIds }, reader: { type: 'json', root: 'data' }, success: function() { Ext.Msg.alert(label_CANCELED); gridBatch.store.remove(records); }, failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); gridBatch.getView().refresh(); } } }] }], viewConfig:{ markDirty:false } }] }] }] }); });<file_sep>package kz.bsbnb.usci.receiver.dao; import kz.bsbnb.usci.receiver.model.Batch; import kz.bsbnb.usci.receiver.model.BatchStatusType; import java.util.List; import java.util.Map; public interface BatchDao { Batch load(long id); long save(Batch batch); List<Batch> getPendingBatchList(); void updateBatchStatus(long batchId, BatchStatusType status); void approveMaintenanceBatchList(List<Long> batchIds); void declineMaintenanceBatchList(List<Long> batchIds); void clearActualCount(long batchId); void incrementActualCount(long batchId, long count); void setBatchTotalCount(long batchId, long totalCount); List<Batch> getBatchFromJdbcMap(List<Map<String, Object>> rows); } <file_sep>package kz.bsbnb.usci.receiver.validator.impl; import kz.bsbnb.usci.model.respondent.Respondent; import kz.bsbnb.usci.receiver.model.Batch; import kz.bsbnb.usci.receiver.model.exception.ReceiverException; import kz.bsbnb.usci.receiver.reader.ManifestReader; import kz.bsbnb.usci.receiver.validator.BatchValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; /** * @author <NAME> * @author <NAME> */ @Service public class BatchValidatorImpl implements BatchValidator { private static final Logger logger = LoggerFactory.getLogger(BatchValidatorImpl.class); private final ManifestReader manifestReader; public BatchValidatorImpl(ManifestReader manifestReader) { this.manifestReader = manifestReader; } @Override public void validateUserRespondent(Batch batch, List<Respondent> userRespondents) { if (userRespondents.size() > 0) { Optional<Respondent> optRespondent = manifestReader.getRespondent(batch, userRespondents); batch.setRespondent(optRespondent.orElseThrow(() -> new ReceiverException("Несоответствие респондента пользователю портала"))); } else throw new ReceiverException("Пользователь не имеет доступа к респондентам: " + batch.getUserId()); } } <file_sep>Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.selection.CellModel', 'Ext.grid.*', 'Ext.data.*', 'Ext.tab.*', 'Ext.tip.*' ]); Ext.onReady(function () { checkBoxValues = {}; var updateCheckBoxGroup = function() { var checkBoxGroup = Ext.getCmp('mailTemplateGroup'); checkBoxGroup.removeAll(); mailTemplateStore.each(function(record) { var mailTemplateName = record.get('mailTemplate'); checkBoxGroup.add({ cls: 'checkBox', inputValue: record.get('id'), boxLabel: mailTemplateName.nameRu, checked: record.get('enabled'), name: 'myGroup' }); }); checkBoxGroup.items.each(function(checkbox){ var checkboxValue = checkbox.inputValue; checkBoxValues[checkboxValue] = checkbox.getValue() === true ? 'on' : 'off'; }); } var mailTemplateStore = Ext.create('Ext.data.Store', { id: 'mailTemplateStore', fields: ['id', 'userId', 'mailTemplate', 'enabled'], autoLoad: true, proxy: { type: 'ajax', url: dataUrl+'/mail/mail/getUserMailTemplateList', method: 'GET', extraParams: { userId: userId }, reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } }, }); mailTemplateStore.on({ load: updateCheckBoxGroup }); var panel = Ext.create('Ext.tab.Panel', { renderTo: 'notification-content', height: 500, width: 1200, items: [{ xtype: 'panel', border: false, title: label_SETUP, layout: { type: 'vbox', align: 'center' }, bodyPadding: 12, items: [{ xtype: 'displayfield', padding: '20', style: 'font-size: 20px;', labelCls: 'biggertext', value: label_TYPES, fieldCls: 'biggertext' }, { xtype: 'checkboxgroup', id: 'mailTemplateGroup', width: 400, layout: { type: 'vbox', autoFlex: false }, items: [], listeners: { change: function (checkboxGroup, newValue) { var values ; if (typeof newValue.myGroup === 'object') { values = newValue.myGroup; } else { values = [newValue.myGroup]; } checkboxGroup.items.each(function(checkbox){ var checkboxValue = checkbox.inputValue; checkBoxValues[checkboxValue] = values.indexOf(checkboxValue) !== -1 ? 'on' : 'off'; }); } } }, { xtype: 'button', text: label_SAVE, id: 'btnSave', height: 30, margin: '20px 10px 20px 180px', listeners: { click: function () { var recordList = { userMailTemplateList: []}; var founded; for (key in checkBoxValues) { var founded = mailTemplateStore.findRecord('id', key) founded.data.enabled = checkBoxValues[key] === "on" ? true : false ; recordList.userMailTemplateList.push(founded.data); } Ext.Ajax.request({ url: dataUrl+'/mail/mail/saveUserMailTemplateList', method: 'POST', jsonData: recordList, reader: { type: 'json', root: 'data' }, success: function() { Ext.Msg.alert(label_SUC_SAVED); }, failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); } } }] }] }); }); <file_sep>package kz.bsbnb.usci.eav.meta.controller; import kz.bsbnb.usci.eav.model.meta.json.MetaAttributeJson; import kz.bsbnb.usci.eav.model.meta.json.MetaClassJson; import kz.bsbnb.usci.eav.service.MetaClassService; import kz.bsbnb.usci.util.json.ext.ExtJsJson; import kz.bsbnb.usci.util.json.ext.ExtJsTree; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author <NAME> */ @RestController @RequestMapping(value = "/meta") public class MetaClassController { private final MetaClassService metaClassService; public MetaClassController(MetaClassService metaClassService) { this.metaClassService = metaClassService; } @GetMapping(value = "getMetaClasses") public List<MetaClassJson> getMetaClasses() { return metaClassService.getMetaClassJsonList(); } @GetMapping(value = "getMetaClassJsonListByUserId") public List<MetaClassJson> getMetaClassJsonListByUserId(@RequestParam(name = "userId") Long userId) { return metaClassService.getMetaClassJsonListByUserId(userId); } @GetMapping(value = "getDictionaries") public List<MetaClassJson> getDictionaries() { return metaClassService.getDictionaryJsonList(); } @GetMapping(value = "getMetaClassAttributesTree") public List<ExtJsTree> getMetaClassAttributes(@RequestParam(name = "node") String node) { return metaClassService.getMetaClassAttributes(node); } @GetMapping(value = "getMetaClassData") public MetaClassJson getMetaClass(@RequestParam(name = "metaClassId") Long metaClassId) { return metaClassService.getMetaClassJson(metaClassId); } //TODO: переименовать в getMetaAttributes @GetMapping(value = "getMetaClassAttributesList") public List<MetaAttributeJson> getMetaAttributes(@RequestParam Long metaClassId) { return metaClassService.getMetaClassAttributes(metaClassId); } @PostMapping(value = "saveMetaClass") public void saveMetaClass(@RequestBody MetaClassJson metaClassJson) { metaClassService.saveMetaClass(metaClassJson); } @PostMapping(value = "saveMetaAttribute") public void saveMetaAttribute(@RequestBody MetaAttributeJson metaAttributeJson) { metaClassService.saveMetaAttribute(metaAttributeJson); } @PostMapping(value = "syncWithDb") public void syncWithDb() { metaClassService.syncWithDb(); } @GetMapping(value = "getMetaAttribute") public ExtJsJson getMetaAttribute(@RequestParam(name = "metaClassId") Long metaClassId, @RequestParam(name = "attributeId") Long attributeId) { return new ExtJsJson(metaClassService.getMetaAttribute(metaClassId, attributeId)); } @PostMapping(value = "delMetaAttribute") public void deleteAttribute(@RequestParam(name = "attrPathPart") String attrPathPart, @RequestParam(name = "attrPathCode") String attrPathCode) { metaClassService.delMetaAttribute(attrPathPart, attrPathCode); } } <file_sep>package kz.bsbnb.usci.receiver.model.json; import java.time.LocalDateTime; public class BatchSignJson { private Long id; private String fileName; private LocalDateTime receiverDate; private String hash; private String signature; private String information; private LocalDateTime signingTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public LocalDateTime getReceiverDate() { return receiverDate; } public void setReceiverDate(LocalDateTime receiverDate) { this.receiverDate = receiverDate; } public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public String getInformation() { return information; } public void setInformation(String information) { this.information = information; } public LocalDateTime getSigningTime() { return signingTime; } public void setSigningTime(LocalDateTime signingTime) { this.signingTime = signingTime; } } <file_sep>package kz.bsbnb.usci.portlet.signing; import com.liferay.util.bridges.mvc.MVCPortlet; public class SigningPortlet extends MVCPortlet { } <file_sep>buildscript { ext { gsonVersion = '2.8.2' guavaVersion = '11.0.2' } } group = 'kz.bsbnb.usci.eav' version = '0.1.0' dependencies { compile project(':model') compile project(':eav:eav-api') compile project(':eav:eav-meta') compile project(':brms:brms-core') compile project(':util:util-api') compile ("org.springframework.boot:spring-boot-starter-web") compile ("org.springframework.boot:spring-boot-starter-jdbc") compile("com.google.guava:guava:${guavaVersion}") compile("com.oracle:${ojdbcVersion}") } jar { baseName = 'usci-eav-core' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>var label_SEND = 'Отправить'; var label_EDIT = 'Редактировать'; var label_DATE = 'Отчетная дата'; var label_CODE = 'Код'; var label_TITLE = 'Наименование'; var label_ITEMS = 'Элементы'; var label_ERROR = 'Ошибка'; var label_ERROR_NO_DATA = 'Не возможно получить данные'; var label_VIEW = 'Просмотр'; var label_ERROR_NO_DATA_FOR = 'Не возможно получить данные: {0} '; var label_SAVE = 'Сохранить'; var label_CANCEL = 'Отмена'; var label_VALUE = 'Значение'; var label_SIMPLE = 'Простой'; var label_ARRAY = 'Массив'; var label_TYPE = 'Тип'; var label_INPUT_FORM = "Форма ввода"; var label_REF = 'Справочник'; var label_ITEMS = 'Элементы'; var label_ENTITY_ID = 'Идентификатор сущности'; var label_DEL = 'Удалить'; var label_CLOSE = 'Закрыть'; var label_CLASS = 'Класс'; var LABEL_UPDATE = 'Обновить'; var label_date = 'Дата'; var label_CONFIRM_CHANGES = "Подтвердить изменения"; var label_REQUIRED_FIELD = "Обязательное поле"; var label_SUBJECT_NAME = "Быстрый просмотр"; var label_LOADING = "Loading..."; var label_NUll_SEARCH = 'Поиск вернул 0 результатов'; var label_BVU_NO = 'БВУ/НО'; var label_CONTRACT = 'Договор займа/условного обязательства(кредит)'; var label_DOGOVOR = 'Договор'; var label_NUMBER = 'Номер'; var label_YES = 'Да'; var label_NO ='Нет'; var label_ADD_TO = 'Добавление в '; var label_SAVE_NEW_RECORD = 'Сохранить новую запись'; var label_PROF_WORKS = "Ведутся профилактические работы, попробуйте выполнить запрос позже"; var label_ALL_INFO = "Вся информация по "; var label_ALREADY_ADDED = " уже добавлена"; var label_ADD_ELEMENT = "Добавить элемент"; var label_NOT_ADDED_KEY_ATRIBUT = "Не заполнен ключевой атрибут: "; var label_ADD = 'Добавить'; var label_SUCCEFUL_SAVED = "Сохранено успешно. Необходимо отправить изменения через портлет \"Отправка изменений\""; var label_APLLY_DELETE = 'Потверждение на удаление?'; var label_ARE_YOU_SURE_DELETE = 'Вы точно хотите отметить на удаление? '; var label_MEAN = ' значение: '; var label_YES = "Да"; var label_NO = "Нет"; var label_SUCC_OPERATION = "Операция выполнена успешно. Необходимо "; var label_DATA_SAVE = "сохранить данные и отправить на обработку"; var label_OPERATION_SUCC = "Операция выполнена успешно"; var label_ADD_RECORD = 'Добавление записи'; var label_ADD_ELEEMENT_MASSIV = 'Добавление элемента массива'; var label_SEARCH_TYPE = 'Вид поиска'; var label_ALL_RESULTS = 'Всего результатов:'; var label_NON_SAVED = 'Есть несохраненные данные'; var label_UPDATE_RECORD = 'Обновить запись'; var label_RULES = 'Правила'; var label_ERROR_RULES = 'Ошибка бизнес правил'; var label_ERRORS = 'Ошибки'; var label_NO_ERRORS = "Успешно проверено на Бизнес Правила. Нет ошибок."; var label_OPEN_DATE = 'Дата открытия'; var label_CLOSE_DATE = 'Дата закрытия'; var label_SEND_CHANGES = 'Отправить изменения'; var label_CHANGE = 'Изменить'; var label_CHOOSE = 'Выбрать'; var label_DIFFERENT_REP_DATES = "Нельзя удалить на разные отчетные даты"; var label_CHANGING = ', Изменение:'; var label_REF_CHOOSE = 'Выбор справочника \"'; var label_REF_CHOICE = 'Выберите справочник'; var label_CONTRACT_NUMBER = 'Номер договора'; var label_CONTRACT_DATE ='Дата договора'; var label_DO_YOU_WANT_TO_ADD = 'Поиск вернул 0 результатов, желаете добавить новый договор ?'; var label_DOCS = "Документы"; var label_ADD_SEARCH_DOC = 'добавить документ поиска'; var label_CLEAR = 'Очистить'; var label_PERSONS_NAME = 'Имя'; var label_LAST_NAME = 'Фамилия'; var label_MIDDLE_NAME = 'Отчество'; var label_RESPONDENT_TYPE = 'Тип кредитора'; var label_UR = 'Юр лицо'; var label_FIZ = 'Физ лицо'; var label_BANK = 'Банк'; var label_CONTINUE = 'Далее'; var label_ADD_DOC_SEARCH = 'добавить документ поиска'; var label_CLEAR = 'Очистить'; var label_RESPONDENT = 'Респондент'; var label_REFRESH = 'Обновить'; var label_EXPORT = 'Экспорт'; var label_OPEN = 'Открыть'; var label_EDIT_ATTR = 'Редактировать атрибут'; var label_NO_AVA = 'Нет доступных операций'; var label_ID_ENTITY = 'Идентификатор сущности'; var label_ADD_NOTE = 'Добавление записи'; var label_SIMPLE_MASS = 'Простые массивы не поддерживаются'; var label_NO_AVA_ATTR = 'Нет доступных атрибутов для редактирования'; var label_EDITING = 'Редактирование: '; var label_SAVE_CHANGES = 'Сохранить изменения'; var label_SEARCH = 'Найти'; var label_SEARCHING = 'Идет поиск...'; var label_EDITING_ATTR = 'Редактировать атрибут'; var label_NO_AVA_OPER = 'Нет доступных операций'; var label_SEARCH_PARA = 'Параметры поиска'; <file_sep>package kz.bsbnb.usci.eav.service; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseEntityRegistry; import kz.bsbnb.usci.eav.model.core.BaseEntityDate; import kz.bsbnb.usci.eav.model.core.EavHub; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.model.exception.UsciException; import java.util.*; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ public class BaseEntityHolder { private final Map<MetaClass, List<BaseEntity>> processedBaseEntities = new HashMap<>(); private final Map<MetaClass, List<BaseEntity>> newBaseEntities = new HashMap<>(); private final List<BaseEntity> newBaseEntityEntries = new ArrayList<>(); private final List<BaseEntity> updatedBaseEntityEntries = new ArrayList<>(); private final List<BaseEntity> movedBaseEntityDates = new ArrayList<>(); private final List<BaseEntity> deletedBaseEntityEntries = new ArrayList<>(); private final List<EavHub> updatedBaseEntityHubs = new ArrayList<>(); private final Map<BaseEntity, List<String>> addBaseEntityHubs = new HashMap<>(); private final List<EavHub> deletedBaseEntityHubs = new ArrayList<>(); private final List<BaseEntityRegistry> newBaseEntityRegistries = Collections.synchronizedList(new ArrayList<>()); private final List<BaseEntityDate> newBaseEntityDates = new ArrayList<>(); private final List<BaseEntityDate> updatedBaseEntityDates = new ArrayList<>(); private final Map<String, List<BaseEntity>> baseEntityPairs = new HashMap<>(); //todo potom nado ubrat', dobavken dlya generacii kluchei v hub migrirovannyh dannyh private final List<BaseEntity> migrationErrorsHub = new ArrayList<>(); private void putBaseEntity(Map<MetaClass, List<BaseEntity>> objects, BaseEntity baseEntity) { MetaClass metaClass = baseEntity.getMetaClass(); if (objects.containsKey(metaClass)) objects.get(metaClass).add(baseEntity); else { List<BaseEntity> objList = new ArrayList<>(); objList.add(baseEntity); objects.put(metaClass, objList); } } public void putAsNewBaseEntity(BaseEntity baseEntity) { Objects.requireNonNull(baseEntity, "Сущность для вставки не может быть NULL"); if (baseEntity.getId() != null) throw new UsciException("Сущность для вставки не должна иметь идентификатор"); putBaseEntity(newBaseEntities, baseEntity); } public void putAsUpdatedBaseEntityEntry(BaseEntity baseEntity) { Objects.requireNonNull(baseEntity, "Сущность для обновления не может быть NULL"); Objects.requireNonNull(baseEntity.getId(), "Сущность для обновления должна иметь идентификатор"); updatedBaseEntityEntries.add(baseEntity); } public void putAsNewBaseEntityEntry(BaseEntity baseEntity) { Objects.requireNonNull(baseEntity, "Сущность для вставки записи не может быть NULL"); Objects.requireNonNull(baseEntity.getId(), "Сущность для вставки записи должна иметь идентификатор"); newBaseEntityEntries.add(baseEntity); } public void putAsUpdateBaseEntityReportDate(BaseEntity baseEntity) { Objects.requireNonNull(baseEntity, "Сущность для обновления не может быть NULL"); Objects.requireNonNull(baseEntity.getId(), "Сущность для обновления должна иметь идентификатор"); movedBaseEntityDates.add(baseEntity); } public void putAsDeletedBaseEntityEntry(BaseEntity baseEntity) { Objects.requireNonNull(baseEntity, "Сущность для удаления не может быть NULL"); Objects.requireNonNull(baseEntity.getId(), "Сущность для удаления должна иметь идентификатор"); deletedBaseEntityEntries.add(baseEntity); } public void putAsNewBaseEntityRegistry(BaseEntityRegistry baseEntityRegistry) { newBaseEntityRegistries.add(baseEntityRegistry); } public void putAsDeletedBasEntityHub(EavHub eavHub) { Objects.requireNonNull(eavHub, "Хаб для удаления не может быть NULL"); deletedBaseEntityHubs.add(eavHub); } public void putAsProcessedBaseEntity(BaseEntity baseEntity) { putBaseEntity(processedBaseEntities, baseEntity); } public void putAsUpdatedBaseEntityHub(EavHub eavHub) { Objects.requireNonNull(eavHub, "Сущность для обновления хаба не может быть NULL"); Objects.requireNonNull(eavHub.getEntityId(), "Сущность для обновления хаба должна иметь идентификатор"); updatedBaseEntityHubs.add(eavHub); } public void putAsAddBaseEntityHub(BaseEntity baseEntity, List<String> oldKeys) { Objects.requireNonNull(baseEntity, "Сущность для удаления не может быть NULL"); Objects.requireNonNull(baseEntity.getId(), "Сущность для удаления должна иметь идентификатор"); addBaseEntityHubs.put(baseEntity, oldKeys); } public void putAsNewBaseEntityDate(BaseEntityDate baseEntityDate) { newBaseEntityDates.add(baseEntityDate); } public void putAsUpdatedBaseEntityDate(BaseEntityDate baseEntityDate) { updatedBaseEntityDates.add(baseEntityDate); } public BaseEntity getProcessedBaseEntity(BaseEntity baseEntity) { MetaClass metaClass = baseEntity.getMetaClass(); if (!metaClass.isSearchable()) return null; List<BaseEntity> entityList = processedBaseEntities.get(metaClass); if (entityList == null) return null; for (BaseEntity tempBaseEntity : entityList) if (baseEntity.equalsByKey(tempBaseEntity)) return tempBaseEntity; return null; } public Map<MetaClass, List<BaseEntity>> getNewBaseEntities() { return newBaseEntities; } public List<BaseEntity> getNewBaseEntityEntries() { return newBaseEntityEntries; } public List<BaseEntityRegistry> getNewBaseEntityRegistries() { return newBaseEntityRegistries; } public List<BaseEntity> getUpdatedBaseEntityEntries() { return updatedBaseEntityEntries; } public List<BaseEntity> getMovedBaseEntityDates() { return movedBaseEntityDates; } public List<BaseEntity> getDeletedBaseEntityEntries() { return deletedBaseEntityEntries; } public List<EavHub> getUpdatedBaseEntityHubs() { return updatedBaseEntityHubs; } public Map<BaseEntity, List<String>> getAddBaseEntityHubs() { return addBaseEntityHubs; } public List<EavHub> getDeletedBaseEntityHubs() { return deletedBaseEntityHubs; } public void putBaseEntityPairs (Map<String, List<BaseEntity>> objects, BaseEntity baseEntity, BaseEntity baseEntitySaving) { if (objects.containsKey(baseEntity.getUuid().toString())) objects.get(baseEntity.getUuid().toString()).add(baseEntitySaving); else { List<BaseEntity> objList = new ArrayList<>(); objList.add(baseEntitySaving); objects.put(baseEntity.getUuid().toString(), objList); } } public void saveBaseEntitySavingAppliedPair(BaseEntity baseEntitySaving, BaseEntity baseEntityApplied) { putBaseEntityPairs(baseEntityPairs, baseEntityApplied, baseEntitySaving); // baseEntityPairs.put(baseEntityApplied.getUuid().toString(), baseEntitySaving); } public Map<String, List<BaseEntity>> getBaseEntityPairs() { return baseEntityPairs; } public List<BaseEntityDate> getNewBaseEntityDates() { return newBaseEntityDates; } public List<BaseEntityDate> getUpdatedBaseEntityDates() { return updatedBaseEntityDates; } public void putAsMigrationErrorsHub(BaseEntity baseEntity) { migrationErrorsHub.add(baseEntity); } public List<BaseEntity> getMigrationErrorsHub() { return migrationErrorsHub; } } <file_sep>package kz.bsbnb.usci.report.service; import kz.bsbnb.usci.report.crosscheck.CrossCheck; import kz.bsbnb.usci.report.crosscheck.CrossCheckMessageDisplayWrapper; import kz.bsbnb.usci.report.crosscheck.Message; import java.time.LocalDate; import java.util.List; public interface CrossCheckService { List<CrossCheck> getCrossChecks(List<Long> creditorIds, LocalDate reportDate, Long productId); void crossCheck(Long userId, Long creditorId, LocalDate reportDate, long productId, String executeClause); void crossCheckAll(Long userId, LocalDate reportDate, long productId, String executeClause); List<CrossCheckMessageDisplayWrapper> getCrossCheckMessages(Long crossCheckId); LocalDate getFirstNotApprovedDate(Long creditorId); LocalDate getLastApprovedDate(Long creditorId); CrossCheck getCrossCheck(Long crossCheckId); Message getMessage(Long messageId); byte[] exportToExcel(CrossCheck crossCheck); } <file_sep>function newRuleForm(){ return new Ext.Window({ id: 'newRuleForm', layout: 'fit', modal: 'true', title: label_NEW_RULE, items: [ Ext.create('Ext.form.Panel',{ region: 'center', width: 1200, height: 700, items: [ Ext.create('Ext.form.TextField', { fieldLabel: label_POCK, labelWidth: 55, value: Ext.getCmp('elemComboPackage').getRawValue(), disabled: true, padding: 3 }), Ext.create('Ext.form.DateField', { id: 'elemNewRuleDate', fieldLabel: 'дата', labelWidth: 55, format: 'd.m.Y', padding: 3 }), Ext.create('Ext.form.TextField', { id: 'txtTitle', fieldLabel: label_NAME_LIL, labelWidth: 55, padding: 3 }), Ext.create('Ext.form.Panel',{ tbar: [ { text: label_ADD_BIG, hidden: !isDataManager, id: 'btnNewRuleSubmit', handler: function(){ Ext.Date.patterns={ CustomFormat: "d.m.Y" }; var datefromfield = Ext.getCmp('elemNewRuleDate').value; Ext.Ajax.request({ disableCaching: false, url: dataUrl+'/rule/createRule', method: 'PUT', params: { title: Ext.getCmp('txtTitle').value, ruleBody: newRuleEditor.getSession().getValue(), date: Ext.Date.format(datefromfield, Ext.Date.patterns.CustomFormat), packageId: Ext.getCmp('elemComboPackage').value, pkgName: Ext.getCmp('elemComboPackage').getRawValue() }, reader: { type: 'json', root: 'data' }, success: function(response){ Ext.Msg.alert('', label_ADDED); }, failure: function(response){ var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); } } ] }), { html: "<div id='bknew-rule' style='height: 600px;'>function(){}</div>", } ] }) ] }); }<file_sep>package kz.bsbnb.usci.mail.json; import kz.bsbnb.usci.mail.model.MailTemplate; import kz.bsbnb.usci.model.persistence.Persistable; import java.time.LocalDateTime; /** * @author <NAME> */ public class MailMessageJson extends Persistable { private static final long serialVersionUID = 1L; private String status; private MailTemplate mailTemplate; private LocalDateTime creationDate; private LocalDateTime sendingDate; public MailMessageJson() { } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public MailTemplate getMailTemplate() { return mailTemplate; } public void setMailTemplate(MailTemplate mailTemplate) { this.mailTemplate = mailTemplate; } public LocalDateTime getCreationDate() { return creationDate; } public void setCreationDate(LocalDateTime creationDate) { this.creationDate = creationDate; } public LocalDateTime getSendingDate() { return sendingDate; } public void setSendingDate(LocalDateTime sendingDate) { this.sendingDate = sendingDate; } } <file_sep>package kz.bsbnb.usci.receiver.model.deprecated; import java.time.LocalDate; import java.util.HashMap; /** * @author <NAME> */ @Deprecated public class ManifestData { private String type; private String product; private Long userId; private Integer size; private LocalDate reportDate; private HashMap<String, String> additionalParams = new HashMap<>(); private boolean maintenance; public String getType() { return type; } public void setType(String type) { this.type = type; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public LocalDate getReportDate() { return reportDate; } public void setReportDate(LocalDate reportDate) { this.reportDate = reportDate; } public HashMap<String, String> getAdditionalParams() { return additionalParams; } public void setAdditionalParams(HashMap<String, String> additionalParams) { this.additionalParams = additionalParams; } public void setMaintenance(boolean maintenance) { this.maintenance = maintenance; } public boolean isMaintenance() { return maintenance; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } } <file_sep>package kz.bsbnb.usci.eav.model.base; import kz.bsbnb.usci.eav.model.meta.MetaAttribute; import kz.bsbnb.usci.model.exception.UsciException; import java.io.Serializable; import java.util.Objects; public class BaseEntityInfo implements Serializable, Cloneable { private static final long serialVersionUID = 1L; private BaseEntity parent; private MetaAttribute attribute; public BaseEntityInfo() { /*Пустой конструктор*/ } public BaseEntityInfo(BaseEntity parent, MetaAttribute attribute) { this.parent = parent; this.attribute = attribute; } public BaseEntity getParent() { return parent; } public void setParent(BaseEntity parent) { this.parent = parent; } public MetaAttribute getAttribute() { return attribute; } public void setAttribute(MetaAttribute attribute) { this.attribute = attribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BaseEntityInfo that = (BaseEntityInfo) o; if (parent == null || attribute == null || that.parent == null || that.attribute == null) throw new UsciException(String.format("Ошибка сравнения родителей сущностей (аргументы равны null) %s", o.toString())); if (!attribute.getId().equals(that.attribute.getId())) return false; if (parent.getId() != null && that.parent.getId() != null && Objects.equals(parent.getId(), that.parent.getId())) return true; if (parent.getId() == null && that.parent.getId() == null && parent.equalsByKey(that.parent)) return true; return false; } } <file_sep>package kz.bsbnb.usci.core.dao; import kz.bsbnb.usci.model.respondent.Confirm; import kz.bsbnb.usci.model.respondent.ConfirmMessage; import kz.bsbnb.usci.model.respondent.ConfirmMessageJson; import kz.bsbnb.usci.model.respondent.ConfirmMsgFileJson; import java.time.LocalDate; import java.util.List; import java.util.Optional; /** * @author <NAME> */ public interface ConfirmDao { long insertConfirm(Confirm confirm); void updateConfirm(Confirm confirm); Optional<Confirm> getConfirm(long respondentId, LocalDate reportDate, long productId); Confirm getConfirm(long confirmId); void addConfirmMessage(ConfirmMessage message); List<ConfirmMessageJson> getMessagesByConfirmId(long confirmId); List<ConfirmMsgFileJson> getFilesByMessage(long confirmId); byte[] getMessageFileContent(long fileId); } <file_sep>package kz.bsbnb.usci.receiver.model; import kz.bsbnb.usci.model.util.ConstantType; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author <NAME> */ public enum BatchStatusType implements ConstantType { WAITING((short)18), PROCESSING((short)19), ERROR((short)20), COMPLETED((short)21), WAITING_FOR_SIGNATURE((short)22), CANCELLED((short)23), MAINTENANCE_REQUEST((short)24), MAINTENANCE_DECLINED((short)55); short id; BatchStatusType(short id) { this.id = id; } public int getId() { return id; } @Override public String type() { return "BATCH_STATUS"; } @Override public String code() { return name(); } private static final Map<Integer, BatchStatusType> map = new ConcurrentHashMap<>(); static { for (BatchStatusType batchStatusType : BatchStatusType.values()) { map.put(batchStatusType.getId(), batchStatusType); } } public static BatchStatusType getBatchStatus(int id) { return map.get(id); } } <file_sep>package kz.bsbnb.usci.eav.service; import kz.bsbnb.usci.eav.model.meta.json.MetaClassJson; import kz.bsbnb.usci.eav.model.meta.json.ProductJson; import kz.bsbnb.usci.model.adm.Position; import kz.bsbnb.usci.model.batch.Product; import kz.bsbnb.usci.model.json.ApproveIterationJson; import java.time.LocalDate; import java.util.List; import java.util.Optional; /** * @author <NAME> * @author <NAME> * */ public interface ProductService { List<Product> getProducts(); void generateXsd(); Product getProductById(Long id); Optional<Product> findProductByCode(String code); long createProduct(ProductJson product); void updateProduct(ProductJson json); void addProductMetaClass(long productId, List<Long> metaIds); void deleteProductMetaClass(long productId, List<Long> metaIds); List<MetaClassJson> getMetaClasses(long productId, boolean available); boolean isOpenDictionary(Long id); List<Long> getProductIdsByMetaClassId(Long metaClassId); List<Position> getPositions(Long productId, boolean available); void addProductPosition(Long productId, List<Long> posIds); void deleteProductPosition(Long productId, List<Long> posIds); List<ApproveIterationJson> getApproveIterations(Long productId); void setApproveIterations(Long productId, List<ApproveIterationJson> approveIterationJsonList); boolean checkForApprove(Long productId, Long receiptDateMillis, Long reportDateMillis) ; } <file_sep>package kz.bsbnb.usci.receiver.batch; import kz.bsbnb.usci.receiver.model.Batch; import kz.bsbnb.usci.receiver.model.BatchType; import kz.bsbnb.usci.receiver.queue.BatchQueueHolder; import kz.bsbnb.usci.sync.client.SyncClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParameter; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import static kz.bsbnb.usci.model.Constants.MAX_SYNC_QUEUE_SIZE; /** * Периодический добавляет батчи в очередь для обработки * @author <NAME> * @author <NAME> * @author <NAME> * */ @Component public class BatchSchedulingLauncher { private static final Logger logger = LoggerFactory.getLogger(BatchSchedulingLauncher.class); private static final int PERIOD = 1000; private final JobLauncher jobLauncher; private final SyncClient syncClient; private final BatchQueueHolder batchQueueHolder; private final Job batchJobEav; private final Job batchJobCr; private final Job batchJobMaintenance; private final Map<BatchType, Job> jobs = new HashMap<>(); @PostConstruct private void init() { jobs.put(BatchType.CREDIT_REGISTRY, batchJobCr); jobs.put(BatchType.USCI_OLD, batchJobEav); jobs.put(BatchType.USCI, batchJobEav); jobs.put(BatchType.MAINTENANCE, batchJobMaintenance); } public BatchSchedulingLauncher(JobLauncher jobLauncher, SyncClient syncClient, BatchQueueHolder batchQueueHolder, @Qualifier("batchJobEav") Job batchJobEav, @Qualifier("batchJobCr") Job batchJobCr, @Qualifier("batchJobMaintenance") Job batchJobMaintenance) { this.jobLauncher = jobLauncher; this.syncClient = syncClient; this.batchQueueHolder = batchQueueHolder; this.batchJobEav = batchJobEav; this.batchJobCr = batchJobCr; this.batchJobMaintenance = batchJobMaintenance; } @Scheduled(fixedDelay = PERIOD) public void run() { if (syncClient.getQueueSize() > MAX_SYNC_QUEUE_SIZE) { logger.info("Очеред SYNC заполнена, приостанавливаем добавление батчей в очередь"); return; } Set<Long> finishedBatchIds = syncClient.getFinishedBatches(); if (!finishedBatchIds.isEmpty()) logger.info("Получены батчи из SYNC как завершенные", finishedBatchIds); for (Long batchId : finishedBatchIds) { logger.info("Помечание батча из SYNC как завершенным id = {}", batchId); batchQueueHolder.batchFinished(batchId); } Optional<Batch> optNextBatch = batchQueueHolder.getNextBatch(); if (optNextBatch.isPresent()) { Batch nextBatch = optNextBatch.get(); logger.info("Отправка батча на обработку id = {}", nextBatch.getId()); JobParametersBuilder jobParams = new JobParametersBuilder() .addParameter("respondentId", new JobParameter(nextBatch.getRespondentId())) .addParameter("batchId", new JobParameter(nextBatch.getId())) .addParameter("userId", new JobParameter(nextBatch.getUserId())) .addParameter("reportId", new JobParameter(nextBatch.getConfirmId())) .addParameter("actualCount", new JobParameter(nextBatch.getActualEntityCount())) .addParameter("totalCount", new JobParameter(0L)) .addParameter("maintenance", new JobParameter((long)(nextBatch.isMaintenance()? 1: 0))); try { // по типу батча определяем какой job запускать: КР, EAV Job job = jobs.get(nextBatch.getBatchType()); jobLauncher.run(job, jobParams.toJobParameters()); } catch (Exception e) { logger.error(String.format("Ошибка запуска джоба по батчу %s", nextBatch.getId()), e); batchQueueHolder.batchFinished(nextBatch.getId()); } } else logger.debug("Нет файлов для отправки"); } } <file_sep>/** * @author <NAME> * @author <NAME> * @author <NAME> */ function showNewEntityWindow(metaClass, callback) { var loadMask = new Ext.LoadMask(Ext.getBody(), {msg: label_LOADING}); loadMask.show(); var form = Ext.create('Ext.form.Panel', { bodyPadding: '5 5 0', width: '100%', defaults: { anchor: '100%' }, height: 400, autoScroll: true }); var suffix = '_new_ent'; var windowId = 'windowNewEntity'; if (Ext.getCmp(windowId)) Ext.getCmp(windowId).destroy(); loadAttributes(metaClass.id, function(attributes) { // добавляем каждый атрибут в форму for (var i = 0; i < attributes.length; i++) { form.add(getFormField(attributes[i], null, suffix)); } var window = Ext.create("Ext.Window", { id: windowId, title: label_ADD_NOTE, bodyPadding: '2', width: 600, modal: true, closable: true, closeAction: 'hide', autoScroll: true, items: [form], tbar : [{ text : label_SAVE, handler: function() { if (!form.isValid()) return; // очищаем дерево и добавляем совершенно новую запись сущности var tree = Ext.getCmp('entityTreeView'); var rootNode = tree.getRootNode(); rootNode.removeAll(); rootNode.appendChild({ leaf: false, title: metaClass.title, name: metaClass.name, metaType: "META_CLASS", expanded: true }); var entityNode = rootNode.getChildAt(0); saveFormValues(entityNode, attributes, suffix); tree.getView().refresh(); window.close(); if (callback) callback(); } }] }); loadMask.hide(); window.show(); }); } // добавление атрибута или элемента сета function showAddEntityAttrWindow(node) { var metaClassId = null; var windowTitle = null; if (node.data.depth == 1) { metaClassId = Ext.getCmp('edMetaClass').value; windowTitle = Ext.getCmp('edMetaClass').getRawValue(); } else if (node.parentNode.data.array) { metaClassId = node.parentNode.data.refClassId; windowTitle = node.parentNode.data.title; } else { metaClassId = node.data.refClassId; windowTitle = node.data.title; } if (node.data.array) { if (node.data.simple) { showAddArrayAttrWindow(node, windowTitle, false, function(form) { editorAction.commitEdit(); Ext.getCmp('entityTreeView').getView().refresh(); }); } else if (node.data.dictionary){ showArrayNewDictElWindow(metaClassId, node, windowTitle, false, function() { editorAction.commitEdit(); Ext.getCmp('entityTreeView').getView().refresh(); }); } else { showArrayNewElWindow(metaClassId, node, windowTitle, false, function() { editorAction.commitEdit(); Ext.getCmp('entityTreeView').getView().refresh(); }); } } else { showAddAttrWindow(node, metaClassId, windowTitle, false, function(form) { editorAction.commitEdit(); Ext.getCmp('entityTreeView').getView().refresh(); }); } } // редактирование сущности function showEditEntityWindow(node, metaClassId, windowTitle, searching, callback) { var loadMask = new Ext.LoadMask(Ext.getBody(), {msg: label_LOADING}); loadMask.show(); var suffix = '_edit_ent'; var windowId = 'windowEditEntity'; if (Ext.getCmp(windowId)) Ext.getCmp(windowId).destroy(); var form = Ext.create('Ext.form.Panel', { bodyPadding: '5 5 0', width: '100%', defaults: { anchor: '100%' }, height: 400, autoScroll: true }); loadAttributes(metaClassId, function(attributes) { var editableAttrs = []; for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; // внимание!!! костыль для справочника ref_portfolio // атрибуты creditor, code не даем на редактирование if (attribute.id == 111 || attribute.id == 194) continue; if (attribute.array || (!attribute.dictionary && !attribute.simple)) continue; var editNode = null; for (var j = 0; j < node.childNodes.length; j++) { if (attribute.name === node.childNodes[j].data.name) { editNode = node.childNodes[j]; } } if (editNode) { editableAttrs.push(attribute); form.add(getFormField(attribute, editNode.data.value, suffix)); } } if (editableAttrs.length == 0) { loadMask.hide(); Ext.MessageBox.alert("", label_NO_AVA_ATTR); return; } var window = Ext.create("Ext.Window", { id: windowId, title: label_EDITING + windowTitle, bodyPadding: '2', width: 600, modal: true, closable: true, closeAction: 'hide', items: [form], tbar: [{ text: label_SAVE_CHANGES, handler: function() { if (!form.isValid()) return; saveFormValues(node, editableAttrs, suffix, searching, false); window.close(); if (callback) callback(form); } }] }); loadMask.hide(); window.show(); }); } function showAddAttrWindow(node, metaClassId, windowTitle, searching, callback) { var loadMask = new Ext.LoadMask(Ext.getBody(), {msg: label_LOADING}); loadMask.show(); var form = Ext.create('Ext.form.Panel', { bodyPadding: '5 5 0', width: '100%', defaults: { anchor: '100%' }, height: 400, autoScroll: true }); var windowId = 'windowAddEntityAttr'; var suffix = '_add_attr_ent'; if (Ext.getCmp(windowId)) Ext.getCmp(windowId).destroy(); loadAttributes(metaClassId, function(attributes) { // в форму добавляем только атрибуты которые отсутствуют у сущности // для этого берем из бэка все атрибуты сущности // если нечего добавить то форма закрывается и выводится окно что все атрибуты добавлены var editableAttrs = []; for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; // если делаем поиск то только выбираем только ключевые атрибуты if (searching && !attribute.key) continue; var alreadyHas = false; for (var j = 0; j < node.childNodes.length; j++) { if (attribute.name === node.childNodes[j].data.name) { alreadyHas = true; } } if (!alreadyHas) { editableAttrs.push(attribute); form.add(getFormField(attribute, null, suffix)); } } if (editableAttrs.length == 0) { loadMask.hide(); Ext.MessageBox.alert("", label_ALL_INFO + windowTitle + label_ALREADY_ADDED); return; } var window = Ext.create("Ext.Window", { id: windowId, title: label_ADD_TO + windowTitle, bodyPadding: '2', width: 600, modal: true, closable: true, closeAction: 'hide', items: [form], tbar: [{ text: label_SAVE_NEW_RECORD, handler: function() { if (!form.isValid()) return; loadMask.show(); saveFormValues(node, editableAttrs, suffix, searching, true); window.close(); callback(form); loadMask.hide(); } }] }); loadMask.hide(); window.show(); }); } // показывает окно ввода нового элемента сета function showArrayNewElWindow(metaClassId, arrayNode, windowTitle, searching, callback) { var loadMask = new Ext.LoadMask(Ext.getBody(), {msg: label_LOADING}); loadMask.show(); var windowId = 'windowArrayNewEl'; var suffix = '_add_array_el'; if (Ext.getCmp(windowId)) Ext.getCmp(windowId).destroy(); var form = Ext.create('Ext.form.Panel', { bodyPadding: '5 5 0', width: '100%', defaults: { anchor: '100%' }, height: 400, autoScroll: true }); loadAttributes(metaClassId, function(attributes) { var window = Ext.create("Ext.Window", { id: windowId, title: label_ADD_TO + windowTitle, bodyPadding: '2', width: 600, modal: true, closable: true, closeAction: 'destroy', items: [form], tbar: [{ text: label_SAVE_NEW_RECORD, handler: function() { if (!form.isValid()) return; // в значениях узла сета инкрементируем кол-вол записей arrayNode.data.value = arrayNode.childNodes.length + 1; // создаем новую ноду элемента сета var newNode = Ext.create('entityModel', { title: '[' + arrayNode.childNodes.length + ']', name: '[' + arrayNode.childNodes.length + ']', simple: false, array: false, value: arrayNode.childNodes.length + 1 }); saveFormValues(newNode, attributes, suffix, searching, true); arrayNode.appendChild(newNode); window.close(); if (callback) callback(); } }] }); for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; // если делаем поиск то выбираем только ключевые атрибуты if (searching && !attribute.key) continue; form.add(getFormField(attribute, null, suffix)); } loadMask.hide(); window.show(); }); } function showArrayNewDictElWindow(metaClassId, arrayNode, windowTitle, searching, callback) { var loadMask = new Ext.LoadMask(Ext.getBody(), {msg: label_LOADING}); loadMask.show(); var windowId = 'windowArrayNewDictEl'; var suffix = '_add_array_dictel'; if (Ext.getCmp(windowId)) Ext.getCmp(windowId).destroy(); var form = Ext.create('Ext.form.Panel', { bodyPadding: '5 5 0', width: '100%', defaults: { anchor: '100%' }, height: 400, autoScroll: true }); // в значениях узла сета инкрементируем кол-вол записей arrayNode.data.value = arrayNode.childNodes.length + 1; // создаем новую ноду элемента сета var newNode = Ext.create('entityModel', { title: '[' + arrayNode.childNodes.length + ']', name: '[' + arrayNode.childNodes.length + ']', simple: false, array: true, dictionary: true, refClassId: metaClassId, value: arrayNode.childNodes.length + 1 }); form.add(getFormField(newNode.data, null, suffix)); loadAttributes(metaClassId, function(attributes) { var window = Ext.create("Ext.Window", { id: windowId, title: label_ADD_TO + windowTitle, bodyPadding: '2', width: 600, modal: true, closable: true, closeAction: 'destroy', items: [form], tbar: [{ text: label_SAVE_NEW_RECORD, handler: function() { if (!form.isValid()) return; saveFormValues(newNode, [newNode.data], suffix, searching, true); arrayNode.appendChild(newNode); window.close(); if (callback) callback(); } }] }); loadMask.hide(); window.show(); }); } // открывает окно формы добавления // аттрибута для массива простых function showAddArrayAttrWindow(node, windowTitle, searching, callback) { var suffix = '_add_array_simplel'; var windowId = 'windowAddArraySimpleEl'; if (Ext.getCmp(windowId)) Ext.getCmp(windowId).destroy(); var form = Ext.create('Ext.form.Panel', { width: '100%', defaults: { anchor: '100%' }, autoScroll: true }); node.data.value = node.childNodes.length + 1; // создаем новую ноду элемента сета var newNode = Ext.create('entityModel', { title: '[' + node.childNodes.length + ']', name: '[' + node.childNodes.length + ']', simple: true, array: true, metaType: node.data.typeCode, value: node.childNodes.length + 1 }); form.add(getFormField(newNode.data, null, suffix)); var window = Ext.create("Ext.Window", { id: windowId, title: label_ADD_TO + windowTitle, width: 400, modal: true, closable: true, closeAction: 'destroy', items: [form], tbar: [{ text: label_SAVE_NEW_RECORD, handler: function() { if (!form.isValid()) return; saveFormValues(newNode, [newNode.data], suffix, searching, true); node.appendChild(newNode); window.close(); callback(); } }] }).show(); } function getFormField(attr, value, suffix, hideLabels = false) { var readOnly = false; var allowBlank = !(attr.required || attr.key); var formField = null; var fieldId = attr.name + "item" + suffix; var labelWidth = '60%', width = '40%'; var fieldLabel = (!allowBlank ? "<b style='color:red'>*</b> " : "") + attr.title; if (hideLabels) { labelWidth = '0%'; width = '100%'; fieldLabel = ''; } if (attr.array && suffix != '_add_array_simplel' && suffix != '_add_array_dictel') { formField = Ext.create("UsciCheckboxField", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, cls: 'checkBox', width: width, readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD, checked: (attr.key || attr.value) }); } else if (attr.metaType == "DATE") { formField = Ext.create("Ext.form.field.Date", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, format: 'd.m.Y', value: value? new Date(value.replace(/(\d{2})\.(\d{2})\.(\d{4})/,'$3-$2-$1')): null, readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD }); } else if (attr.metaType == "DATE_TIME") { formField = createDateTimePicker(fieldLabel, labelWidth, fieldId, width, value, allowBlank, readOnly); } else if (attr.metaType == "INTEGER" || attr.metaType == "DOUBLE") { formField = Ext.create("Ext.form.field.Number", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, value: value, allowDecimals: attr.metaType == "DOUBLE", readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD }); } else if (attr.metaType == "BOOLEAN") { formField = Ext.create("Ext.form.field.ComboBox", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD, editable: false, store: Ext.create('Ext.data.Store', { fields: ['value', 'title'], data: [ {value: true, title: label_YES}, {value: false, title: label_NO} ] }), displayField: 'title', valueField: 'value', value: value }); } else if (attr.dictionary) { // внимание!!! костыль для справочника ref_portfolio // в атрибут creditor вставляю id кредитора // значение кредитора беру из бэка, то есть определяю кредитора из пользователя // также делаю поле невидимым if (!isNb && attr.id === 194) { Ext.Ajax.request({ async: false, url: dataUrl + '/core/respondent/getRespondentByUserId', method: 'GET', params: { userId: userId, isNb: isNb }, failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); }, success: function (response) { var data = JSON.parse(response.responseText); formField = Ext.create("Ext.form.field.Text", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, value: data.id, readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD, hidden: true }); } }); } else { var edDictEntityId = Ext.create("Ext.form.field.Text", { id: fieldId, value: value, hidden: true }); var edDictRespondentId = Ext.create("Ext.form.field.Text", { id: fieldId+"RESP", value: value, hidden: true }); var edDictText = Ext.create("Ext.form.field.Text", { readOnly: true, width: '92%', value: value, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD }); var buttonDictPick = Ext.create('Ext.Button', { text: '...', width: 25, handler: function() { showDictPicker(attr.refClassId, attr.title, function(selData) { edDictEntityId.setValue(selData.entity_id); edDictRespondentId.setValue(selData.creditor_id); Ext.Ajax.request({ url: dataUrl + '/core/meta/getMetaClassData', method: 'GET', params: { metaClassId: attr.refClassId }, failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); }, success: function (response) { var data = JSON.parse(response.responseText); edDictText.setValue(selData[data.uiConfig.displayField]); } }); }); } }); var panelDict = Ext.create('Ext.form.FieldContainer', { fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, preventHeader: true, border: 0, layout: { type: 'hbox', align: 'stretch' }, items: [edDictText, buttonDictPick, edDictEntityId] }); formField = panelDict; } } else if (attr.metaType == "STRING") { formField = Ext.create("Ext.form.field.Text", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, value: value, readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD }); // внимание!!! костыль для справочника ref_portfolio // в поле код подставляю максимальный код из всего справочника // делаю поле невидимым if (attr.id === 111) { Ext.Ajax.request({ url: dataUrl + '/core/dict/getDictEntities', params: { metaId : 59, userId: userId, isNb: isNb, reportDate: new Date().toISOString().slice(0, 10) }, async: false, method: 'GET', failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); }, success: function(result) { var json = JSON.parse(result.responseText).data; maxId = 0; for (i = 0; i< json.length; i++) { maxId = Math.max(maxId, parseInt(json[i].code)); } maxId++; formField.hidden = true; formField.setValue(maxId); } }); } } else if (!attr.simple && (suffix == '_new_ent' || suffix == '_add_attr_ent' || suffix == '_add_array_el')) { // если идет создание новой сущности или добавление атрибутов // отображаем комплексные сущности как галочки formField = Ext.create("Ext.form.field.Checkbox", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, cls: 'checkBox', width: width, readOnly: false, checked: false }); } else if (suffix == '_add_array_simplel') { if (attr.typeCode == "DATE") { formField = Ext.create("Ext.form.field.Date", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, format: 'd.m.Y', value: value? new Date(value.replace(/(\d{2})\.(\d{2})\.(\d{4})/,'$3-$2-$1')): null, readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD }); } else if (attr.typeCode == "DATE_TIME") { formField = createDateTimePicker(fieldLabel, labelWidth, fieldId, width, value, allowBlank, readOnly); } else if (attr.typeCode == "INTEGER" || attr.typeCode == "DOUBLE") { formField = Ext.create("Ext.form.field.Number", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, value: value, allowDecimals: attr.metaType == "DOUBLE", readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD }); } else if (attr.typeCode == "BOOLEAN") { formField = Ext.create("Ext.form.field.ComboBox", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD, editable: false, store: Ext.create('Ext.data.Store', { fields: ['value', 'title'], data: [ {value: true, title: label_YES}, {value: false, title: label_NO} ] }), displayField: 'title', valueField: 'value', value: value }); } else if (attr.typeCode == "STRING") { formField = Ext.create("Ext.form.field.Text", { id: fieldId, fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, value: value, readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD }); // внимание!!! костыль для справочника ref_portfolio // в поле код подставляю максимальный код из всего справочника // делаю поле невидимым if (attr.id === 111) { Ext.Ajax.request({ url: dataUrl + '/core/dict/getDictEntities', params: { metaId : 59, userId: userId, isNb: isNb, reportDate: new Date().toISOString().slice(0, 10) }, async: false, method: 'GET', failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: 'Ошибка', msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); }, success: function(result) { var json = JSON.parse(result.responseText).data; maxId = 0; for (i = 0; i< json.length; i++) { maxId = Math.max(maxId, parseInt(json[i].code)); } maxId++; formField.hidden = true; formField.setValue(maxId); } }); } } } return formField; } // переносит значения из полей форм в дерево сущности // если идет добавление сущности или элемента в сет то создает новые узлы в дереве function saveFormValues(treeNode, attributes, suffix, searching = false, newNode = true) { var entityId = null; var tree = null; if (!searching) { tree = Ext.getCmp('entityTreeView'); var rootNode = tree.getRootNode(); entityId = rootNode.childNodes[0].data.value; } if (treeNode.data.array && treeNode.data.simple) { var attribute = attributes[0]; var field = Ext.getCmp(attribute.name + "item" + suffix); var fieldValue; if (attribute.metaType == "DATE") { fieldValue = field.getSubmitValue(); } else if (attribute.metaType == "DATE_TIME") { fieldValue = field.getValueAsString(); } else { fieldValue = field.getValue(); } var currNode; currNode = treeNode; var valueBefore = currNode.data.value; currNode.data.value = fieldValue; currNode.data.array = false; if (entityId && attribute.key) { currNode.data.oldValue = currNode.data.oldValue? currNode.data.oldValue: valueBefore; isMaintenance = true; } currNode.data.leaf = true; currNode.data.iconCls = 'file'; currNode.data.newNode = newNode; } else if (treeNode.data.array && treeNode.data.dictionary) { var attribute = attributes[0]; var field = Ext.getCmp(attribute.name + "item" + suffix); var fieldResp = Ext.getCmp(attribute.name + "item" + suffix + "RESP"); var fieldValue; var fieldRespValue = fieldResp.getValue(); if (attribute.metaType == "DATE") { fieldValue = field.getSubmitValue(); } else if (attribute.metaType == "DATE_TIME") { fieldValue = field.getValueAsString(); } else { fieldValue = field.getValue(); } var currNode; currNode = treeNode; var valueBefore = currNode.data.value; currNode.data.value = fieldValue; currNode.data.array = false; currNode.data.leaf = false; currNode.data.iconCls = 'folder'; currNode.data.newNode = newNode; if (fieldValue) dictChange(currNode, fieldValue, fieldRespValue, attribute.refClassId); } else { for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; var field = Ext.getCmp(attribute.name + "item" + suffix); if (!field) continue; var fieldValue; if (attribute.metaType == "DATE") { fieldValue = field.getSubmitValue(); } else if (attribute.metaType == "DATE_TIME") { fieldValue = field.getValueAsString(); } else { fieldValue = field.getValue(); } // если создаем новую сущность но значение отсутствует то // такое значение не отображаем в дереве if (!fieldValue && (suffix == '_new_ent' || suffix == '_add_attr_ent' || suffix == '_add_array_el')) continue; // получаем узел в дереве сущности чтобы обновить значение атрибута var existingAttrNode = treeNode.findChild('name', attribute.name); if (suffix == '_edit_ent_attr') existingAttrNode = treeNode; var currNode; // проверим если идет изменение то просто обновляем значение // если идет добавление то добавляем узел к родительскому узлу if (existingAttrNode) { currNode = existingAttrNode; } else { if (Ext.getCmp('entityTreeView').store.getNodeById(attribute.id)) { attribute.id = attribute.id + treeNode.id; } treeNode.appendChild(attribute); currNode = treeNode.getChildAt(treeNode.childNodes.length - 1); } var valueBefore = currNode.data.value; currNode.data.value = fieldValue; if (attribute.simple && !attribute.array) { // изменение ключей сущности; // по новым сущностям изменения не фиксируем // сохраняем старый ключ в переменной oldValue // помечаем переменную isMaintenance=true что означет батч пойдет как на сопровождение if (entityId && attribute.key) { currNode.data.oldValue = currNode.data.oldValue? currNode.data.oldValue: valueBefore; isMaintenance = true; } currNode.data.leaf = true; currNode.data.iconCls = 'file'; } else { currNode.data.leaf = false; currNode.data.iconCls = 'folder'; // подгружаем справочник if ((attribute.dictionary && attribute.metaType == "META_CLASS") /*|| (attribute.dictionary && attribute.metaType == "META_SET")*/) { var fieldResp = Ext.getCmp(attribute.name + "item" + suffix + "RESP"); var fieldRespValue = fieldResp.getValue(); // если не выбрали запись в справочнике if (fieldValue) dictChange(currNode, fieldValue, fieldRespValue, attribute.refClassId); } } currNode.data.newNode = newNode } } } // открывает окно формы редактирования // отображает только один атрибут function showEditAttrWindow(node, searching, callback) { var suffix = '_edit_ent_attr'; var windowId = 'windowEditEntityAttr'; if (Ext.getCmp(windowId)) Ext.getCmp(windowId).destroy(); var form = Ext.create('Ext.form.Panel', { width: '100%', defaults: { anchor: '100%' }, autoScroll: true }); var editField = getFormField(node.data, node.data.value, suffix, true); form.add(editField); var editorWindow = Ext.create("Ext.Window", { id: windowId, title: node.data.title, width: 400, modal: true, closable: true, closeAction: 'hide', items: [form], tbar: [{ text: label_UPDATE_RECORD, handler: function() { if (!form.isValid()) return; saveFormValues(node, [node.data], suffix, searching, false); editorWindow.close(); callback(); } }] }).show(); } // удаляет сущность или атрибут function showDeleteWindow(node) { var rootNode = Ext.getCmp('entityTreeView').getRootNode(); var entityId = rootNode.childNodes[0].data.value; var isNewNode = false; if (node.data.newNode !== null && node.data.newNode !== "undefined") isNewNode = node.data.newNode // существующая сущность то перед удалением запрашиваем подтверждение // также помечаем атрибут как удаленным if (entityId && !isNewNode) { Ext.MessageBox.alert({ title: label_APLLY_DELETE, msg: label_ARE_YOU_SURE_DELETE + node.data.title + label_MEAN + node.data.value, buttons: Ext.MessageBox.YESNO, buttonText: { yes: label_YES, no: label_NO }, fn: function(val) { if (val == 'yes') { node.data.markedAsDeleted = true; Ext.MessageBox.alert("", label_SUCC_OPERATION + label_DATA_SAVE); node.set('iconCls','deleted'); editorAction.commitEdit(); } } }); } else { // если новая сущность то можно удалять атрибуты без пометки node.parentNode.removeChild(node); } }<file_sep>package kz.bsbnb.usci.mail.dao; import kz.bsbnb.usci.mail.model.MailTemplate; import kz.bsbnb.usci.mail.model.UserMailTemplate; import java.util.List; /** * @author <NAME> * @author <NAME> */ public interface MailTemplateDao { MailTemplate getTemplate(String code); boolean isTemplateEnabledForUser(Long templateId, long userId); List<UserMailTemplate> getUserMailTemplateList(Long userId); void saveUserMailTemplateList(List<UserMailTemplate> userMailTemplateList); } <file_sep>package kz.bsbnb.usci.brms.controller; import kz.bsbnb.usci.brms.model.RulePackage; import kz.bsbnb.usci.brms.service.PackageService; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = "/package") public class PackageController { private final PackageService packageService; public PackageController(PackageService packageService) { this.packageService = packageService; } @GetMapping(value = "getAllPackages") public List<RulePackage> getAllPackages() { return packageService.getAllPackages(); } @GetMapping(value = "savePackage") public Long savePackage(@RequestParam(name = "rulePackageName") String rulePackageName) { return packageService.savePackage(rulePackageName); } } <file_sep>package kz.bsbnb.usci.receiver.validator.impl; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.receiver.model.exception.ReceiverException; import kz.bsbnb.usci.receiver.validator.XsdValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.IOException; import java.io.InputStream; /** * Вадидирует XML файл по правилам XSD * @author <NAME> */ @Service public class XsdValidatorImpl implements XsdValidator { private static final Logger logger = LoggerFactory.getLogger(XsdValidatorImpl.class); @Override public void validateSchema(InputStream xsdInputStream, InputStream xmlInputStream) { Source xsd = new StreamSource(xsdInputStream); Source xml = new StreamSource(xmlInputStream); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema; try { schema = schemaFactory.newSchema(xsd); } catch (SAXException e) { throw new UsciException(e.getMessage()); } Validator validator = schema.newValidator(); try { validator.validate(xml); } catch (SAXParseException e) { int line = e.getLineNumber(); int col = e.getColumnNumber(); logger.error(String.format("XML не прошёл проверку XSD: Line %d Column %d %s", line, col, e.getMessage())); throw new ReceiverException(String.format("Line %d Column %d %s", line, col, e.getMessage())); } catch (SAXException | IOException e) { logger.error("XML не прошёл проверку XSD: {}", e.getMessage()); throw new ReceiverException(e.getMessage()); } } } <file_sep>package kz.bsbnb.usci.mail.service; import kz.bsbnb.usci.mail.model.UserMailTemplate; import kz.bsbnb.usci.mail.model.dto.MailMessageDto; import java.util.List; public interface MailService { void sendMail(MailMessageDto mailMessageDto); List<UserMailTemplate> getUserMailTemplateList(Long userId); void saveUserMailTemplateList(List<UserMailTemplate> userMailTemplateList); } <file_sep>/** * @author <NAME> * @author <NAME> * @author <NAME> */ function createDictGrid(metaClassId, repDate, callback) { Ext.Ajax.request({ url: dataUrl + '/core/meta/getMetaClassAttributesList', params : { metaClassId: metaClassId }, method: 'GET', failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); }, success: function(response) { // получаем мета атрибуты у мета класса var attributes = JSON.parse(response.responseText); // обязательные поля сущности для модули var fields = [ {name: 'entity_id', type: 'number'}, {name: 'creditor_id', type: 'number'}, {name: 'open_date', type: 'date'}, {name: 'close_date', type: 'date'} ]; // добавляю мета атрибуты в поля модели attributes.forEach(function(element) { fields.push({name: element.name}); }); var dictModel = Ext.define('dictModel', { extend: 'Ext.data.Model', fields: fields }); // подгружаем записи справочника в хранилище // чтобы отобразить в гриде в табличной форме dictStore = Ext.create('Ext.data.Store', { model: 'dictModel', autoLoad: true, listeners: { load: function(me, records, options) { if (records.length > 0) dictGrid.getSelectionModel().select(0); } }, proxy: { type: 'ajax', url: dataUrl + '/core/dict/getDictEntities', extraParams: { metaId : metaClassId, userId: userId, isNb: isNb, reportDate: moment(repDate).local().format('YYYY-MM-DD'), }, method: 'GET', reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'entity_id', direction: 'asc' }] }); // создаем столбцы для грида справочника из мета атрибутов var columns = createColumns(attributes); // создаем грид чтобы отобразить данные справочника // передаем ему список столбцов var dictGrid = Ext.create('Ext.grid.Panel', { id: "dictGrid", height: 250, scrollable: true, store: dictStore, columns: columns, title: label_ITEMS, dockedItems: [{ xtype: 'toolbar', dock: 'top', items: [{ xtype: 'button', text: 'Найти по наименованию', listeners: { click: function () { grid = Ext.getCmp("dictGrid"); grid.store.clearFilter(); var newValue = Ext.getCmp("searchInGrid").getValue(); if (newValue) { var matcher = new RegExp(Ext.String.escapeRegex(newValue), "i"); grid.store.filter({ filterFn: function(record) { return matcher.test(record.get('name_ru')) || matcher.test(record.get('name_kz')) || matcher.test(record.get('code')); } }); } } } }, { xtype: 'textfield', id: 'searchInGrid' }] }] }); callback(dictGrid); } }); } // создает столбцы для грида справочника из мета атрибутов function createColumns(attributes) { var columns = []; // обязательные поля грида добавляем собственноручно columns.push({text: 'ID', dataIndex: 'entity_id'}); // добавляем столбцы для грида на основе справочника мета атрибутов for (var i = 0; i < attributes.length; i++) { columns.push({ text: attributes[i].title, dataIndex: attributes[i].name }); } columns.push({ text: label_OPEN_DATE, dataIndex: 'open_date', xtype: 'datecolumn', minWidth : 120, format: 'd.m.Y' }); columns.push({ text: label_CLOSE_DATE, dataIndex: 'close_date', xtype: 'datecolumn', minWidth : 120, format: 'd.m.Y' }); return columns; } function dictChange(node, entityId, respondentId, metaClassId, callback) { node.removeAll(); var spinner = new Ext.LoadMask(Ext.getBody(), {msg: label_LOADING}); spinner.show(); var tempEntityStore = Ext.getStore('tempEntityStore'); if (!tempEntityStore) { tempEntityStore = Ext.create('Ext.data.TreeStore', { model: 'entityModel', storeId: 'tempEntityStore', folderSort: true, proxy: { type: 'ajax', url: dataUrl + '/core/eav/getEntityData' } }); } tempEntityStore.load({ params: { entityId: entityId, respondentId: respondentId, metaClassId: metaClassId, date: new Date().toISOString().slice(0, 10), asRoot: false }, callback: function(records, operation, success) { node.data.value = records[0].data.value; while (records[0].childNodes.length > 0) { node.appendChild(records[0].childNodes[0]); } spinner.hide(); if (callback) callback(); } }); } function showDictPicker(classId, title, callback) { createDictGrid(classId, new Date(), function(dictGrid) { var window = new Ext.Window({ id: 'windowDictSelect', modal: 'true', title: label_REF_CHOOSE + title + '\"', items: [ Ext.create('Ext.form.Panel', { region: 'center', width: 600, height: 300, layout: 'border', items: [ { region: 'center', bodyStyle: 'padding: 5px', items: [ Ext.create('Ext.button.Button', { text: label_CHOOSE, handler: function() { var selected = dictGrid.getSelectionModel().getLastSelected(); if (!selected) { //TODO: показать ошибку чтобы выбрали запись return; } window.close(); callback(selected.data); } }), dictGrid ] } ] }) ] }); window.show(); }); }<file_sep>package kz.bsbnb.usci.sync; import kz.bsbnb.usci.sync.job.DataJob; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @Configuration @ComponentScan(basePackages = {"kz.bsbnb.usci"}) @EnableScheduling @EnableConfigurationProperties @EnableFeignClients(basePackages = {"kz.bsbnb.usci.receiver.client", "kz.bsbnb.usci.util.client"}) @EnableEurekaClient public class SyncApplication { public static void main(String[] args) { SpringApplication.run(SyncApplication.class, args); } @Bean public DataJob dataJob() { return new DataJob(); } @Bean public TaskExecutor taskExecutor() { return new SimpleAsyncTaskExecutor(); } /** * Запускаем DataJob асинхронно после запуска приложения */ @Bean public CommandLineRunner runner(TaskExecutor executor) { return args -> executor.execute(dataJob()); } } <file_sep>package kz.bsbnb.usci.report.service; import kz.bsbnb.usci.report.dao.ReportDao; import kz.bsbnb.usci.report.exception.ReportException; import kz.bsbnb.usci.report.model.*; import kz.bsbnb.usci.report.model.json.InputParametersJson; import net.sf.jasperreports.engine.*; import net.sf.jasperreports.engine.design.JasperDesign; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.xml.JRXmlLoader; import net.sf.jasperreports.export.SimpleExporterInput; import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput; import net.sf.jasperreports.export.SimpleXlsReportConfiguration; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.*; import java.sql.Date; import java.sql.*; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @Service public class ReportServiceImpl implements ReportService { @Value("${jasper.templatePath}") private String templatePath; @Value("${jasper.reportFilesFolder}") private String reportFilesFolder; @Value("${jasper.recordBySheet}") private int recordBySheet; private final ReportDao reportDao; private Integer headerBottom; private Properties reportProperties; private static final Logger logger = LoggerFactory.getLogger(ReportServiceImpl.class); public ReportServiceImpl(ReportDao reportDao) { this.reportDao = reportDao; } @Override public List<Report> loadReportList(String reportType) { return reportDao.loadReportList(reportType); } @Override public Report getReport(long reportId) { return reportDao.getReport(reportId); } @Override public List<ReportInputParameter> loadReportInputParameter(Long reportId) { return reportDao.loadReportInputParameter(reportId); } @Override public List<ExportType> loadExportType(Long reportId) { return reportDao.loadExportType(reportId); } @Override public List<ReportLoad> loadReportLoads(Long userId) { return reportDao.loadReportLoads(userId); } @Override public ClosableRS getDataFromProcudeure (long userId, String procedureName, List<InputParametersJson> parameterList) throws SQLException { return reportDao.getDataFromProcudeure(userId, procedureName, parameterList); } @Override public List<ValuePair> getValueListFromStoredProcedure(String procedureName, String tableName, long userId) { return reportDao.getValueListFromStoredProcedure(procedureName, tableName, userId); } @Override public Date loadInputDateValue(String procedureName, long userId) { return reportDao.loadInputDateValue(procedureName, userId); } public CustomDataSource getDataSourceFromStoredProcedure(long userId, String procedureName, List<InputParametersJson> parameterList) throws SQLException { ClosableRS rs = getDataFromProcudeure(userId, procedureName, parameterList); CustomDataSource customDataSource = new CustomDataSource(rs.getResultSet()); rs.close(); return customDataSource; } @Override public ReportLoad loadStarted(Long userId, Report report, List<InputParametersJson> parameterList) { ReportLoad load = new ReportLoad(); load.setPortalUserId(userId); load.setReport(report); load.setStartTime(LocalDateTime.now()); List<String> parameterCaptions = new ArrayList<>(); List<String> parameterValues = new ArrayList<>(); for (ReportInputParameter inParam : report.getInputParameters()) { parameterCaptions.add(inParam.getNameRu()); } for (InputParametersJson parameter : parameterList) { parameterValues.add(parameter.getDisplay()); } StringBuilder noteBuilder = new StringBuilder(); for (int i = 0; i < Math.min(parameterCaptions.size(), parameterValues.size()); i++) { if (i > 0) { noteBuilder.append(", "); } noteBuilder.append(parameterCaptions.get(i)); noteBuilder.append(" = "); noteBuilder.append(parameterValues.get(i)); } load.setNote(noteBuilder.toString()); return load; } @Override public void loadFinished(ReportLoad reportLoad) { reportLoad.setFinishTime(LocalDateTime.now()); reportDao.insertOrUpdateReportLoad(reportLoad); } public CustomDataSource loadData(long userId, Report report, List<InputParametersJson> parameterValues) throws SQLException { if(parameterValues == null) { return null; } return getDataSourceFromStoredProcedure(userId, report.getProcedureName(), parameterValues); } @Override public byte[] templateReportToXls (long userId, Report report, List<InputParametersJson> parameterValues) { try { ReportLoad reportLoad = loadStarted(userId, report, parameterValues); String confPath = templatePath + report.getName() + "/export.properties"; loadConfig(confPath); headerBottom = getIntegerProperty("header-bottom", 0); byte[] file = generatePageXlsx(report.getName(), 1, userId, report, parameterValues); if (file == null) reportLoad.setNote("Empty report"); loadFinished(reportLoad); return file; } catch (Exception e) { throw new ReportException("Ошибка формирования отчета: " + report.getName() + " message: " + e); } } protected byte[] generatePageXlsx(String exportFilePrefix, int sheetNumber, long userId, Report report, List<InputParametersJson> parameterValues) { ResultSet dataSource; ByteArrayOutputStream zbaos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ClosableRS closableRS = null; try { SXSSFWorkbook workbook = new SXSSFWorkbook(10000); workbook.setCompressTempFiles(true); CreationHelper createHelper = workbook.getCreationHelper(); Font font = workbook.createFont(); font.setFontName("Times New Roman"); font.setFontHeightInPoints((short) 12); CellStyle mainCellStyle = workbook.createCellStyle(); mainCellStyle.setFont(font); mainCellStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.TOP); mainCellStyle.setBorderBottom(BorderStyle.THIN); mainCellStyle.setBorderLeft(BorderStyle.THIN); mainCellStyle.setBorderTop(BorderStyle.THIN); mainCellStyle.setBorderRight(BorderStyle.THIN); mainCellStyle.setWrapText(true); CellStyle numberDoubleCellStyle = workbook.createCellStyle(); numberDoubleCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("# ### ### ###.###")); numberDoubleCellStyle.setFont(font); numberDoubleCellStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.TOP); numberDoubleCellStyle.setBorderBottom(BorderStyle.THIN); numberDoubleCellStyle.setBorderLeft(BorderStyle.THIN); numberDoubleCellStyle.setBorderTop(BorderStyle.THIN); numberDoubleCellStyle.setBorderRight(BorderStyle.THIN); numberDoubleCellStyle.setShrinkToFit(true); CellStyle numberIntegerCellStyle = workbook.createCellStyle(); numberIntegerCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("# ### ### ###")); numberIntegerCellStyle.setFont(font); numberIntegerCellStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.TOP); numberIntegerCellStyle.setBorderBottom(BorderStyle.THIN); numberIntegerCellStyle.setBorderLeft(BorderStyle.THIN); numberIntegerCellStyle.setBorderTop(BorderStyle.THIN); numberIntegerCellStyle.setBorderRight(BorderStyle.THIN); numberIntegerCellStyle.setShrinkToFit(true); CellStyle dateCellStyle = workbook.createCellStyle(); dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd.MM.yyyy")); dateCellStyle.setFont(font); dateCellStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.TOP); dateCellStyle.setBorderBottom(BorderStyle.THIN); dateCellStyle.setBorderLeft(BorderStyle.THIN); dateCellStyle.setBorderTop(BorderStyle.THIN); dateCellStyle.setBorderRight(BorderStyle.THIN); dateCellStyle.setShrinkToFit(true); int rowIndex = 1; int recordsBySheet = recordBySheet; int recordCounter = 0; int sheetCounter = 1; closableRS = getDataFromProcudeure(userId, report.getProcedureName(), parameterValues); dataSource = closableRS.getResultSet(); ResultSetMetaData rsmd = dataSource.getMetaData(); SXSSFSheet sheet = workbook.createSheet(String.format("Report-%d", sheetCounter)); sheet.trackAllColumnsForAutoSizing(); long startTime = System.currentTimeMillis(); logger.info("Start of creating excel (sheets,rows): {} ", startTime); while (dataSource.next()) { if (rowIndex == 1) { Row headerRow = sheet.createRow(rowIndex); for (int columnIndex = 1; columnIndex <= rsmd.getColumnCount(); columnIndex++) { Cell cell = headerRow.createCell(columnIndex); cell.setCellValue(rsmd.getColumnName(columnIndex)); cell.setCellStyle(mainCellStyle); } rowIndex++; } Row row = sheet.createRow(rowIndex); for (int columnIndex = 1; columnIndex <= rsmd.getColumnCount(); columnIndex++) { if (rsmd.getColumnType(columnIndex) == Types.INTEGER) { Cell cell = row.createCell(columnIndex); cell.setCellValue(dataSource.getInt(columnIndex)); cell.setCellStyle(numberIntegerCellStyle); } else if (rsmd.getColumnType(columnIndex) == Types.DOUBLE) { Cell cell = row.createCell(columnIndex); cell.setCellValue(dataSource.getDouble(columnIndex)); cell.setCellStyle(numberDoubleCellStyle); } else if (rsmd.getColumnType(columnIndex) == Types.TIMESTAMP && dataSource.getDate(columnIndex) != null) { Cell cell = row.createCell(columnIndex); cell.setCellValue(dataSource.getDate(columnIndex)); cell.setCellStyle(dateCellStyle); } else { Object value = dataSource.getObject(columnIndex); if (value == null) { value = ""; } Cell cell = row.createCell(columnIndex); cell.setCellValue(value.toString()); cell.setCellStyle(mainCellStyle); } } if (rowIndex == 500001) { sheetCounter ++; sheet = workbook.createSheet(String.format("Report-%d", sheetCounter)); sheet.trackAllColumnsForAutoSizing(); rowIndex = 0; } rowIndex++; recordCounter++; } logger.info("End of creating excel (sheets,rows): {} ", (System.currentTimeMillis() - startTime)); startTime = System.currentTimeMillis(); for(Sheet sh: workbook) { for(int i = 1; i <= rsmd.getColumnCount(); i++) { sh.autoSizeColumn(i); } } logger.info("End of autosizing columns in excel : {} ", (System.currentTimeMillis() - startTime)); workbook.write(baos); workbook.close(); workbook.dispose(); if (recordCounter > 0) { String cleanFilename = String.format("%s-%d.xlsx", exportFilePrefix, recordCounter); ZipOutputStream zos = new ZipOutputStream(zbaos); ZipEntry entry = new ZipEntry(cleanFilename); entry.setSize(baos.toByteArray().length); zos.putNextEntry(entry); zos.write(baos.toByteArray()); zos.closeEntry(); zos.close(); return zbaos.toByteArray(); } return null; } catch (SQLException | IOException e) { if(closableRS != null) { closableRS.close(); } logger.info("Connection closed generatePage"); if(baos!=null) { try { baos.close(); } catch(Exception ee) { throw new ReportException("Failed to close baos stream" + ee); } } if(zbaos!=null) { try { zbaos.close(); } catch(Exception ee) { throw new ReportException("Failed to close zbaos stream" + ee); } } } finally { if(closableRS != null) { closableRS.close(); } logger.info("Connection closed generatePage finally"); if(baos!=null) { try { baos.close(); } catch(Exception e) { throw new ReportException("Failed to close baos stream" + e); } } if(zbaos!=null) { try { zbaos.close(); } catch(Exception e) { throw new ReportException("Failed to close zbaos stream" + e); } } } return null; } @Override public byte[] jasperToXls(long userId, Report report, List<InputParametersJson> parameterValues) { try { ReportLoad reportLoad = loadStarted(userId, report, parameterValues); CustomDataSource dataSource = loadData(userId, report, parameterValues); String reportName = report.getName(); String path = templatePath + reportName + "//"; String jasperFilePath = path + reportName + ".jrxml"; String resourceFilePath = path + reportName + "_RU" +".properties"; JasperDesign design = JRXmlLoader.load(jasperFilePath); //JasperDesign jasperDesign = JRXmlLoader.load(jasperFilePath); JasperReport jasperReport = JasperCompileManager.compileReport(design); PropertyResourceBundle resourceBundle = new PropertyResourceBundle(new FileInputStream(resourceFilePath)); Enumeration<String> resourceEnumeration = resourceBundle.getKeys(); while (resourceEnumeration.hasMoreElements()) { String resourceStringName = resourceEnumeration.nextElement(); String resourceStringValue = resourceBundle.getString(resourceStringName); } HashMap<String, Object> reportParameters = new HashMap<String, Object>(); reportParameters.put("REPORT_RESOURCE_BUNDLE", resourceBundle); reportParameters.put("USERNAME", ""); List<ReportInputParameter> parameters = report.getInputParameters(); int parametersCount = parameters.size(); for (int parameterIndex = 0; parameterIndex < parametersCount; parameterIndex++) { ReportInputParameter parameter = parameters.get(parameterIndex); InputParametersJson value = parameterValues.get(parameterIndex); if (value != null) { String valueString; if (value.getType() == "DATE") { SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); valueString = sdf.format(value.getValue()); } else { valueString = value.toString(); } reportParameters.put(parameter.getParameterName(), valueString); } } JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, reportParameters, dataSource); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JRXlsExporter exporterXls = new JRXlsExporter(); exporterXls.setExporterInput(new SimpleExporterInput(jasperPrint)); exporterXls.setExporterOutput(new SimpleOutputStreamExporterOutput(baos)); SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration(); configuration.setOnePagePerSheet(true); configuration.setDetectCellType(true); configuration.setCollapseRowSpan(false); configuration.isRemoveEmptySpaceBetweenColumns(); configuration.isRemoveEmptySpaceBetweenRows(); configuration.setMaxRowsPerSheet(100000); configuration.isDetectCellType(); exporterXls.setConfiguration(configuration); exporterXls.exportReport(); byte[] bytes = baos.toByteArray(); loadFinished(reportLoad); return bytes; } catch (JRException jre) { throw new ReportException("Ошибка при формировании jasper файла: " + jre.getStackTrace()); } catch (IOException ioe) { throw new ReportException("Ошибка при загрузке файла: " + ioe.getMessage()); } catch (SQLException sqle) { throw new ReportException("Ошибка при формировании отчета: " + sqle.getMessage()); } } @Override public void callRunReport(long userId, long isEscape, List<InputParametersJson> parameterList) { reportDao.callRunReport(userId, isEscape, parameterList); } @Override public List<UserReport> getReportList(List<Long> respondentIds, List<Long> productIds) { return reportDao.getReportList(respondentIds,productIds); } @Override public byte[] getReportFile(Long id) { return reportDao.getReportFile(id); } protected void loadConfig(String configFilePath) { File configFile = new File(configFilePath); if (!configFile.exists()) { return; } FileInputStream configFileStream = null; try { configFileStream = new FileInputStream(configFile); reportProperties = new Properties(); reportProperties.load(configFileStream); } catch (IOException ioe) { } finally { if (configFileStream != null) { try { configFileStream.close(); } catch (Exception e) { } } } } protected int getIntegerProperty(String key, int defaultValue) { try { return Integer.valueOf(getReportProperty(key)); } catch (NumberFormatException nfe) { return defaultValue; } } private String getReportProperty(String key) { if (reportProperties == null) { return ""; } return reportProperties.getProperty(key, ""); } private boolean isConfigurationValid() { return headerBottom != null; } } <file_sep>group = 'kz.bsbnb.usci.mail' version = '0.1.0' dependencies { compile project(':model') compile project(':util:util-api') compile project(':util:util-core') compile project(':core:core-api') compile project(':mail:mail-api') compile('org.springframework.boot:spring-boot-starter-mail') compile("org.springframework.boot:spring-boot-starter-jdbc") compile('org.springframework.boot:spring-boot-starter-web') } jar { baseName = 'usci-mail-core' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>group = 'kz.bsbnb.usci.receiver' version = '0.1.0' dependencies { compile project(':eav:eav-api') compile('org.springframework.cloud:spring-cloud-starter-openfeign') } jar { baseName = 'usci-receiver-api' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>/** * @author <NAME> * @author <NAME> */ Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.button.*' ]); function showMetaAttrWindow(className, parentPath, classSync, attrPath, metaAttrData, callback) { var setKeyTypes = [ ['ALL', label_ALL], ['ANY', label_OFF] ]; var attributeTypes = [ [1, LABEL_SIMPLE], [2, LABEL_COMPLEX], [3, LABEL_SIMPLE_SET], [4, LABEL_COMPLEX_SET] ]; var attrSimpleTypes = [ ['INTEGER', LABEL_NUMBER], ['DATE', LABEL_DATE], ['DATE_TIME', label_DATE_AND_TIME], ['STRING', LABEL_STRING], ['BOOLEAN', LABEL_BOOLEAN], ['DOUBLE', LABEL_FLOAT] ]; var name = null; var attrPathPart = null; if (attrPath != null) { var pathArray = attrPath.split("."); // извлекаем наименование атрибута name = pathArray[pathArray.length - 1]; attrPathPart = attrPath.substring(0, attrPath.length -(name.length + 1)); } else { attrPathPart = parentPath; } var buttonSave = Ext.create('Ext.button.Button', { id: 'buttonSave', text: LABEL_SAVE, handler: function() { var form = Ext.getCmp('formMetaAttr').getForm(); if (form.isValid()) { var editMetaAttr = form.getValues(); if (metaAttrData) editMetaAttr.id = metaAttrData.id; editMetaAttr.keyType = editMetaAttr.isNullableKey? 2: (editMetaAttr.isKey? 1: 0); if (!editMetaAttr.keySet) editMetaAttr.keySet = 0; var loadMask = new Ext.LoadMask(Ext.getBody(), { msg: label_SAVING }); loadMask.show(); Ext.Ajax.request({ url: dataUrl + '/core/meta/saveMetaAttribute', method: 'POST', waitMsg: label_SAVING, jsonData: editMetaAttr, reader: { type: 'json', root: 'data' }, success: function(response, opts) { loadMask.hide(); Ext.getCmp('windowMetaAttr').destroy(); if (callback) callback(); }, failure: function(response, opts) { loadMask.hide(); Ext.getCmp('windowMetaAttr').destroy(); Ext.Msg.alert(label_ERROR, JSON.parse(response.responseText).errorMessage); } }); } else { Ext.Msg.alert(LABEL_ATTENTION, LABEL_ERROR_EXIST); } } }); var buttonClose = Ext.create('Ext.button.Button', { id: 'buttonClose', text: LABEL_CANCEL, handler : function() { Ext.getCmp('windowMetaAttr').destroy(); } }); Ext.define('metaClassModel', { extend: 'Ext.data.Model', fields: ['id','name', 'title'] }); var classesStore = Ext.create('Ext.data.Store', { model: 'metaClassModel', pageSize: 500, proxy: { type: 'ajax', url: dataUrl + '/core/meta/getMetaClasses', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } }, autoLoad: true, remoteSort: true }); var formMetaAttr = Ext.create('Ext.form.Panel', { id: 'formMetaAttr', region: 'center', width: 615, fieldDefaults: { msgTarget: 'side' }, defaults: { anchor: '100%' }, defaultType: 'textfield', bodyPadding: '5 5 0', items: [ { fieldLabel: LABEL_CLASS_CODE, name: 'className', value: className, readOnly: true }, { fieldLabel: LABEL_PARENT_CODE , name: 'parentPath', value: parentPath, readOnly: true }, { fieldLabel: LABEL_ATTRIBUTE_PUTH, name: 'attrPathPart', value: attrPathPart, readOnly: true }, { fieldLabel: LABEL_ATTRIBUTE_CODE + '*', id: 'edName', name: 'name', allowBlank: false, maskRe: /[_a-z]/, validator: function(v) { if (/^([_a-z])+$/.test(v)) { return true; } else { return 'Допускается ввод только строчных латинских букв и символа "_" !'; } }, //readOnly: metaAttrData && metaAttrData.id != null, value: name }, { fieldLabel: LABEL_ATTRIBUTE_TYPE + '*', id: 'comAttrType', name: 'type', xtype: 'combobox', allowBlank: false, //readOnly: classSync,//metaAttrData && metaAttrData.id != null, store: new Ext.data.SimpleStore({ id: 0, fields: ['id', 'title'], data: attributeTypes }), editable: false, valueField: 'id', displayField: 'title', queryMode: 'local', listeners: { change: function (field, newValue, oldValue) { onAttrTypeChange(newValue, metaAttrData); } } }, { fieldLabel: LABEL_ATTRIBUTE_CLASS + '*', id: 'comRefClass', name: 'refClassId', xtype: 'combobox', editable: false, store: classesStore, valueField: 'id', displayField: 'title' }, { fieldLabel: LABEL_ATTRIBUTE_TYPE + '*', id: 'comSimpleType', name: 'typeCode', xtype: 'combobox', store: new Ext.data.SimpleStore({ id: 0, fields:['id', 'text'], data: attrSimpleTypes }), editable: false, valueField: 'id', displayField: 'text', queryMode: 'local' }, { fieldLabel: LABEL_ARRTIBUTE_NAME + '*', id: 'edTitle', name: 'title', allowBlank: false }, { xtype: 'checkboxfield', cls: 'checkBox', boxLabel: label_MUST, //readOnly: classSync,//metaAttrData && metaAttrData.id != null, name: 'required', inputValue: true }, { xtype: 'checkboxfield', cls: 'checkBox', boxLabel: label_NOT_ACTIVE, name: 'deleted', inputValue: true }, { xtype: 'checkboxfield', cls: 'checkBox', id: 'cbReference', boxLabel: label_LINK, name: 'reference', inputValue: true }, { xtype: 'checkboxfield', cls: 'checkBox', boxLabel: label_NULLABLE, id: 'cbNullify', name: 'nullify', inputValue: true }, { xtype: 'checkboxfield', cls: 'checkBox', id: 'cbParentIsKey', boxLabel: label_DOCH, name: 'parentIsKey', inputValue: true }, { xtype : 'panel', title: label_MASS, bodyPadding: '5 5 0', items: [ { xtype: 'checkboxfield', cls: 'checkBox', id: 'cbCumulative', boxLabel: label_SOBIR, name: 'cumulative', inputValue: true }, { fieldLabel: label_TYPE_KEY, id: 'comSetKeyType', xtype: 'combobox', name: 'setKeyType', store: new Ext.data.SimpleStore({ id: 'ALL', fields: ['code', 'name'], data: setKeyTypes }), editable: false, valueField: 'code', displayField: 'name', queryMode: 'local' }] }, { xtype : 'panel', title: label_KEYS, bodyPadding: '5 5 0', items: [{ xtype: 'checkboxfield', cls: 'checkBox', boxLabel: label_KEYABLE, id: 'cbIsKey', name: 'isKey', inputValue: true, listeners: { change: function (checkbox, newVal, oldVal) { onIsKeyChange(newVal); } } }, { xtype: 'checkboxfield', cls: 'checkBox', boxLabel: label_EMPTY, id: 'cbIsNullableKey', name: 'isNullableKey', inputValue: true }, { xtype: 'numberfield', fieldLabel: label_GROUP_KEYS, id: 'numKeySet', name: 'keySet', value: 0 }] } ], buttons: [buttonSave, buttonClose] }); // если идет создание новой записи то простаюляю значения по умолчанию if (!metaAttrData) { Ext.getCmp('comAttrType').setValue(1); Ext.getCmp('comSimpleType').setValue('INTEGER'); onIsKeyChange(false); } var form = Ext.getCmp('formMetaAttr').getForm(); // загружаем инфу по мета атрибуту из бэка // затем присваиваем форме значения if (metaAttrData) { Ext.Ajax.request({ url: dataUrl + '/core/meta/getMetaAttribute', waitMsg: LABEL_LOADING, params: { metaClassId: metaAttrData.classId, attributeId: metaAttrData.id }, method: 'GET', success: function(response, opts) { json = JSON.parse(response.responseText); var tempMetaAttr = json.data; tempMetaAttr.isKey = tempMetaAttr.keyType === 1 || tempMetaAttr.keyType === 2; tempMetaAttr.isNullableKey = tempMetaAttr.keyType === 2; tempMetaAttr.attrPathPart = attrPathPart; form.setValues(tempMetaAttr); // поменяем доступность полей в зависимости от типа и ключа onAttrTypeChange(/*classSync, */tempMetaAttr.type, tempMetaAttr); onIsKeyChange(tempMetaAttr.isKey); }, failure: function(response, opts) { Ext.Msg.alert(label_ERROR, JSON.parse(response.responseText).errorMessage); } }); } var windowMetaAttr = new Ext.Window({ id: 'windowMetaAttr', layout: 'fit', title: LABEL_ATTRIBUTE, modal: true, maximizable: true, items:[formMetaAttr] }); windowMetaAttr.show(); } function onAttrTypeChange(/*classSync, */attrType, metaAttrData) { var edName = Ext.getCmp('edName'); var comAttrType = Ext.getCmp('comAttrType'); var comSimpleType = Ext.getCmp('comSimpleType'); var comRefClass = Ext.getCmp('comRefClass'); var comSetKeyType = Ext.getCmp('comSetKeyType'); var cbReference = Ext.getCmp('cbReference'); var cbNullify = Ext.getCmp('cbNullify'); var cbParentIsKey = Ext.getCmp('cbParentIsKey'); var cbCumulative = Ext.getCmp('cbCumulative'); var numKeySet = Ext.getCmp('numKeySet'); var cbIsKey = Ext.getCmp('cbIsKey'); var cbIsNullableKey = Ext.getCmp('cbIsNullableKey'); onIsKeyChange(cbIsKey.getValue()); // зарпрещаем изменять поля мета атрибута // потому что по настроенной логике уже могут быть совершены операций //if (metaAttrData && metaAttrData.id) { /*if (classSync == true) { edName.readOnly = true; comAttrType.readOnly = true; comSimpleType.readOnly = true; comRefClass.readOnly = true; comSetKeyType.readOnly = true; cbReference.readOnly = true; cbNullify.readOnly = true; cbParentIsKey.readOnly = true; cbCumulative.readOnly = true; cbIsKey.readOnly = true; cbIsNullableKey.readOnly = true; numKeySet.readOnly = true; return; }*/ // в зависимости от типа атрибута делаем поля не доступными if (attrType === 1) { comRefClass.clearValue(); comSimpleType.allowBlank = false; comRefClass.allowBlank = true; comSimpleType.setDisabled(false); comRefClass.setDisabled(true); cbReference.setDisabled(true); cbNullify.setDisabled(true); cbParentIsKey.setDisabled(true); cbCumulative.setDisabled(true); cbReference.setValue(false); cbNullify.setValue(false); cbParentIsKey.setValue(false); cbCumulative.setValue(false); } else if (attrType === 2) { comSimpleType.clearValue(); comSimpleType.allowBlank = true; comRefClass.allowBlank = false; comSimpleType.setDisabled(true); cbCumulative.setDisabled(true); cbCumulative.setValue(false); comRefClass.setDisabled(false); cbReference.setDisabled(false); cbNullify.setDisabled(false); cbParentIsKey.setDisabled(false); } else if (attrType === 3) { comRefClass.clearValue(); comSimpleType.allowBlank = false; comRefClass.allowBlank = true; comRefClass.setDisabled(true); cbReference.setDisabled(true); cbNullify.setDisabled(true); cbParentIsKey.setDisabled(true); cbCumulative.setDisabled(false); comSimpleType.setDisabled(false); cbReference.setValue(false); cbNullify.setValue(false); cbParentIsKey.setValue(false); } else if (attrType === 4) { comSimpleType.clearValue(); comSimpleType.allowBlank = true; comRefClass.allowBlank = false; comSimpleType.setDisabled(true); cbNullify.setDisabled(true); cbNullify.setValue(false); comRefClass.setDisabled(false); cbCumulative.setDisabled(false); cbReference.setDisabled(false); cbParentIsKey.setDisabled(false); } } function onIsKeyChange(isKey) { var comAttrType = Ext.getCmp('comAttrType'); var numKeySet = Ext.getCmp('numKeySet'); var cbIsNullableKey = Ext.getCmp('cbIsNullableKey'); var comSetKeyType = Ext.getCmp('comSetKeyType'); var attrType = comAttrType.getValue(); if (isKey) { if (numKeySet.value == 0) numKeySet.setValue(1); if (attrType == 1 || attrType == 2) { comSetKeyType.setDisabled(true); comSetKeyType.allowBlank = true; comSetKeyType.clearValue(); } else { comSetKeyType.setDisabled(false); comSetKeyType.allowBlank = false; } numKeySet.readOnly = false; cbIsNullableKey.setReadOnly(false); } else { numKeySet.setValue(0); numKeySet.readOnly = true; cbIsNullableKey.setValue(false); cbIsNullableKey.setReadOnly(true); comSetKeyType.clearValue(); comSetKeyType.allowBlank = true; comSetKeyType.setDisabled(true); } } <file_sep>package kz.bsbnb.usci.wsclient.client; import kz.bsbnb.usci.wsclient.config.HttpLoggingUtils; import kz.bsbnb.usci.wsclient.jaxb.ctr.Entities; import kz.bsbnb.usci.wsclient.jaxb.ctr.response.ProcessingStatus; import kz.bsbnb.usci.wsclient.jaxb.kgd.*; import kz.bsbnb.usci.wsclient.jaxb.test.AncInfo; import kz.bsbnb.usci.wsclient.model.ctrkgd.Request; import kz.bsbnb.usci.wsclient.model.ctrkgd.RequestStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.stereotype.Component; import org.springframework.ws.FaultAwareWebServiceMessage; import org.springframework.ws.WebServiceMessage; import org.springframework.ws.client.core.WebServiceMessageCallback; import org.springframework.ws.client.core.WebServiceMessageExtractor; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.soap.SoapMessage; import org.springframework.ws.soap.client.SoapFaultClientException; import org.springframework.ws.support.MarshallingUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.GregorianCalendar; import java.util.UUID; @Component public class KGDSOAPClient { private static final Logger logger = LoggerFactory.getLogger(KGDSOAPClient.class); private WebServiceTemplate kgdWebServiceTemplate; private Jaxb2Marshaller kgdJaxb2Marshaller; public KGDSOAPClient(WebServiceTemplate kgdWebServiceTemplate, Jaxb2Marshaller kgdJaxb2Marshaller) { this.kgdWebServiceTemplate = kgdWebServiceTemplate; this.kgdJaxb2Marshaller = kgdJaxb2Marshaller; } public ResponseMessage testResponseMessage() { ObjectFactory objectFactory = new ObjectFactory(); OperationType operationType = new OperationType(); operationType.setCode("ancInfo"); operationType.setDescription("Информация по валютному договору по экспорту или импорту с учетным номером"); RequestType requestType = new RequestType(); requestType.setCode("0"); requestType.setDescription("Запрос"); PackageType packageType = new PackageType(); packageType.setRequestId("132131321321321321323232321321"); //////////////// AncInfo ancInfo = new AncInfo(); AncInfo.Header header = new AncInfo.Header(); header.setGuid("{7b3Ca5DA-Ab9A-eeeB-Ceb6-9AaFEb1a4f1f}"); LocalDateTime localDateTime = LocalDateTime.now(); GregorianCalendar calendar = GregorianCalendar.from(localDateTime.atZone(ZoneId.of("Asia/Almaty"))); XMLGregorianCalendar xmlDate = null; try { xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { logger.error("Ошибка при обработке дат: ", e); } header.setCreationDateTime(xmlDate); AncInfo.Data ancInfoData = new AncInfo.Data(); AncInfo.Data.ContractRegistrationInfo contractRegistrationInfo = new AncInfo.Data.ContractRegistrationInfo(); AncInfo.Data.ContractPartiesInfo contractPartiesInfo = new AncInfo.Data.ContractPartiesInfo(); AncInfo.Data.ContractDetailsInfo contractDetailsInfo = new AncInfo.Data.ContractDetailsInfo(); AncInfo.Data.TerminationNoticeInfo terminationNoticeInfo = new AncInfo.Data.TerminationNoticeInfo(); AncInfo.Data.ContractClosureInfo contractClosureInfo = new AncInfo.Data.ContractClosureInfo(); contractRegistrationInfo.setAccountingNumber("string"); LocalDate localDate = LocalDate.now(); calendar = GregorianCalendar.from(localDate.atStartOfDay().atZone(ZoneId.of("Asia/Almaty"))); try { xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { logger.error("Ошибка при обработке дат: ", e); } contractRegistrationInfo.setDateOfRegistration(xmlDate); AncInfo.Data.ContractPartiesInfo.ResidentInfo residentInfo = new AncInfo.Data.ContractPartiesInfo.ResidentInfo(); AncInfo.Data.ContractPartiesInfo.NonResidentInfo nonResidentInfo = new AncInfo.Data.ContractPartiesInfo.NonResidentInfo(); residentInfo.setIin("157587093945"); residentInfo.setRegionCode("48"); nonResidentInfo.setName("string"); nonResidentInfo.setCountryCode("RT"); contractPartiesInfo.setResidentInfo(residentInfo); contractPartiesInfo.setNonResidentInfo(nonResidentInfo); contractDetailsInfo.setNumber("string"); contractDetailsInfo.setDateOfExecution(xmlDate); contractDetailsInfo.setSum(BigDecimal.valueOf(-1117169.77)); contractDetailsInfo.setCurrency("CTB"); contractDetailsInfo.setTermOfRepatriation("448.44"); terminationNoticeInfo.setNoticeSentDate(xmlDate); contractClosureInfo.setClosureDate(xmlDate); contractClosureInfo.setClosureBasis(BigDecimal.valueOf(18)); ancInfoData.setContractRegistrationInfo(contractRegistrationInfo); ancInfoData.setContractPartiesInfo(contractPartiesInfo); ancInfoData.setContractDetailsInfo(contractDetailsInfo); ancInfoData.setTerminationNoticeInfo(terminationNoticeInfo); ancInfoData.setContractClosureInfo(contractClosureInfo); ancInfoData.setNote("string"); ancInfo.setHeader(header); ancInfo.setData(ancInfoData); /////////////// String xml = null; try { xml = marshal(AncInfo.class, ancInfo); } catch (JAXBException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Document parsedDoc = parseStringToXMLDocument(xml); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document doc = builder.newDocument(); Element root = doc.createElement("data"); doc.appendChild(root); Node copy = doc.importNode(parsedDoc.getDocumentElement(), true); root.appendChild(copy); packageType.setData(doc.getDocumentElement()); RequestMessage.Sender sender = new RequestMessage.Sender(); sender.setFullName("<NAME>"); sender.setSystemName("eivk"); RequestMessage requestMessage = objectFactory.createRequestMessage(); requestMessage.setOperation(operationType); requestMessage.setRequestType(requestType); requestMessage.setSender(sender); requestMessage.setPackage(packageType); JAXBElement<RequestMessage> request = objectFactory.createSendMessageRequest(requestMessage); JAXBElement<ResponseMessage> response = null; response = (JAXBElement<ResponseMessage>) kgdWebServiceTemplate.marshalSendAndReceive(request); return response.getValue(); } public Request ctrRequest(Entities entities) { ObjectFactory objectFactory = new ObjectFactory(); OperationType operationType = new OperationType(); operationType.setCode("usciCtr"); operationType.setDescription("Информация о валютной операции"); RequestType requestType = new RequestType(); requestType.setCode("0"); requestType.setDescription("Запрос"); PackageType packageType = new PackageType(); UUID uuid = UUID.randomUUID(); String uuidStr = uuid.toString(); packageType.setRequestId(uuidStr); String xml = null; try { xml = marshal(Entities.class, entities); } catch (Exception e) { e.printStackTrace(); } Document parsedDoc = parseStringToXMLDocument(xml); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document doc = builder.newDocument(); Element root = doc.createElement("data"); doc.appendChild(root); Node copy = doc.importNode(parsedDoc.getDocumentElement(), true); root.appendChild(copy); packageType.setData(doc.getDocumentElement()); RequestMessage.Sender sender = new RequestMessage.Sender(); sender.setFullName("ESSP"); sender.setSystemName("essp"); RequestMessage requestMessage = objectFactory.createRequestMessage(); requestMessage.setOperation(operationType); requestMessage.setRequestType(requestType); requestMessage.setSender(sender); requestMessage.setPackage(packageType); Request ctrRequest = new Request(); ctrRequest.setRequestId(uuidStr); JAXBElement<RequestMessage> request = objectFactory.createSendMessageRequest(requestMessage); JAXBElement<ResponseMessage> response = null; try { response = (JAXBElement<ResponseMessage>) kgdWebServiceTemplate.sendAndReceive(message -> { MarshallingUtils.marshal(kgdJaxb2Marshaller, request, message); ctrRequest.setRequestBody(HttpLoggingUtils.getMessage(message)); logger.info(ctrRequest.getRequestBody()); }, message -> { ctrRequest.setResponseBody(HttpLoggingUtils.getMessage(message)); logger.info(ctrRequest.getResponseBody()); return MarshallingUtils.unmarshal(kgdJaxb2Marshaller, message); }); ProcessingStatus processingStatus = new ProcessingStatus(); try { processingStatus = unmarshal(ProcessingStatus.class, response.getValue().getPackage().getData()); } catch (Exception e) { e.printStackTrace(); } logger.info("Status is " + processingStatus.getDescription()); if (response.getValue() != null) { //TODO: на время теста смотрим на этот статус, в реале надо поменять на package.data.processStatus if (response.getValue().getStatus().getCode().equals("000")) { ctrRequest.setRequestStatus(RequestStatus.SUCCESS); } else { ctrRequest.setRequestStatus(RequestStatus.ERROR); } } } catch (SoapFaultClientException e) { ctrRequest.setResponseBody(HttpLoggingUtils.getMessage(e.getWebServiceMessage())); logger.info(ctrRequest.getResponseBody()); ctrRequest.setRequestStatus(RequestStatus.ERROR); return ctrRequest; } return ctrRequest; } private static <T> String marshal(Class<T> clazz, T instance) throws JAXBException, IOException { javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext.newInstance(clazz); javax.xml.bind.Marshaller m = jc.createMarshaller(); try (java.io.StringWriter writer = new java.io.StringWriter()) { m.marshal(instance, writer); return writer.toString().replaceAll(">\\s+<", "><"); } } private static <T> T unmarshal(Class<T> clazz, Object node) throws Exception { javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext.newInstance(clazz); javax.xml.bind.Unmarshaller m = jc.createUnmarshaller(); org.w3c.dom.Node nodeE = (org.w3c.dom.Node) node; return m.unmarshal(nodeE.getFirstChild(), clazz).getValue(); } public static Document parseStringToXMLDocument(String xmlString) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setCoalescing(false); dbf.setNamespaceAware(true); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); return documentBuilder.parse(new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8))); } catch (Exception e) { e.printStackTrace(); } return null; } } <file_sep>package kz.bsbnb.usci.report.model; import java.sql.ResultSet; public interface ClosableRS { ResultSet getResultSet(); void close(); }<file_sep>group = 'kz.bsbnb.usci' version = '0.1.0' dependencies { compile("org.springframework.boot:spring-boot-starter-jdbc") } jar { baseName = 'usci-model' version = '0.1.0' enabled = true } bootJar { enabled = false } <file_sep>package kz.bsbnb.usci.eav.model.meta.json; /** * @author <NAME> */ public class MetaAttributeJson { private Long id; private Long classId; private String name; private String title; private Byte type;//Тип атрибута: 0-simple, 1-complex,2-simple set,3-complex set private boolean array = false; private boolean simple = false; private boolean dictionary = false; private Byte keyType = 0; private Short keySet = 1; private boolean isKey = false; private boolean isRequired = false; private boolean isDeleted = false; private boolean parentIsKey = false; private boolean isReference = false; private boolean isCumulative = false; private boolean isNullify = false; private boolean nullableKey; private String setKeyType; private Long refClassId; private String refMetaType;// вид мета данных ссылки: META_CLASS, META_SET private String typeCode;// простые типы: DATE, DOUBLE, INTEGER, STRING private String metaType;// вид мета данных: META_CLASS, META_SET, DOUBLE, INTEGER, DATE private String attrPathPart; private boolean isSync = false; private boolean hidden = false; private String value; public Long getId() { return id; } public MetaAttributeJson setId(Long id) { this.id = id; return this; } public boolean isArray() { return array; } public MetaAttributeJson setArray(boolean array) { this.array = array; return this; } public boolean isSimple() { return simple; } public MetaAttributeJson setSimple(boolean simple) { this.simple = simple; return this; } public boolean isDictionary() { return dictionary; } public MetaAttributeJson setDictionary(boolean dictionary) { this.dictionary = dictionary; return this; } public Long getClassId() { return classId; } public MetaAttributeJson setClassId(Long classId) { this.classId = classId; return this; } public boolean isHidden() { return hidden; } public MetaAttributeJson setHidden(boolean hidden) { this.hidden = hidden; return this; } public String getMetaType() { return metaType; } public MetaAttributeJson setMetaType(String metaType) { this.metaType = metaType; return this; } public String getName() { return name; } public MetaAttributeJson setName(String name) { this.name = name; return this; } public String getTitle() { return title; } public MetaAttributeJson setTitle(String title) { this.title = title; return this; } public Byte getType() { return type; } public MetaAttributeJson setType(Byte type) { this.type = type; return this; } public Byte getKeyType() { return keyType; } public MetaAttributeJson setKeyType(Byte keyType) { this.keyType = keyType; return this; } public Short getKeySet() { return keySet; } public MetaAttributeJson setKeySet(Short keySet) { this.keySet = keySet; return this; } public boolean isKey() { return isKey; } public MetaAttributeJson setKey(boolean key) { isKey = key; return this; } public boolean isDeleted() { return isDeleted; } public MetaAttributeJson setDeleted(boolean deleted) { isDeleted = deleted; return this; } public boolean isParentIsKey() { return parentIsKey; } public MetaAttributeJson setParentIsKey(boolean parentIsKey) { this.parentIsKey = parentIsKey; return this; } public boolean isReference() { return isReference; } public MetaAttributeJson setReference(boolean reference) { isReference = reference; return this; } public boolean isCumulative() { return isCumulative; } public MetaAttributeJson setCumulative(boolean cumulative) { isCumulative = cumulative; return this; } public boolean isNullify() { return isNullify; } public MetaAttributeJson setNullify(boolean nullify) { isNullify = nullify; return this; } public boolean isRequired() { return isRequired; } public MetaAttributeJson setRequired(boolean required) { isRequired = required; return this; } public String getSetKeyType() { return setKeyType; } public void setSetKeyType(String setKeyType) { this.setKeyType = setKeyType; } public Long getRefClassId() { return refClassId; } public void setRefClassId(Long refClassId) { this.refClassId = refClassId; } public String getRefMetaType() { return refMetaType; } public void setRefMetaType(String refMetaType) { this.refMetaType = refMetaType; } public String getTypeCode() { return typeCode; } public void setTypeCode(String typeCode) { this.typeCode = typeCode; } public boolean isNullableKey() { return nullableKey; } public void setNullableKey(boolean nullableKey) { this.nullableKey = nullableKey; } public String getAttrPathPart() { return attrPathPart; } public void setAttrPathPart(String attrPathPart) { this.attrPathPart = attrPathPart; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public boolean isSync() { return isSync; } public MetaAttributeJson setSync(boolean sync) { isSync = sync; return this; } } <file_sep>package kz.bsbnb.usci.receiver.dao.impl; import kz.bsbnb.usci.receiver.dao.BatchStatusDao; import kz.bsbnb.usci.receiver.model.BatchStatus; import kz.bsbnb.usci.receiver.model.BatchStatusType; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.List; /** * @author <NAME> * @author <NAME> */ @Repository public class BatchStatusDaoImpl implements BatchStatusDao { private final NamedParameterJdbcTemplate npJdbcTemplate; private SimpleJdbcInsert batchStatusInsert; public BatchStatusDaoImpl(NamedParameterJdbcTemplate npJdbcTemplate) { this.npJdbcTemplate = npJdbcTemplate; this.batchStatusInsert = new SimpleJdbcInsert(npJdbcTemplate.getJdbcTemplate()) .withSchemaName("USCI_BATCH") .withTableName("BATCH_STATUS") .usingGeneratedKeyColumns("ID"); } @Override public void insert(BatchStatus batchStatus) { batchStatusInsert.execute(new MapSqlParameterSource() .addValue("BATCH_ID", batchStatus.getBatchId()) .addValue("STATUS_ID", batchStatus.getStatus().getId()) .addValue("RECEIPT_DATE", SqlJdbcConverter.convertToSqlTimestamp(batchStatus.getReceiptDate())) .addValue("DESCRIPTION", batchStatus.getText()) .addValue("EXCEPTION_TRACE", batchStatus.getExceptionTrace())); //batchStatus.setId(id.longValue()); //return batchStatus.getId(); } @Override public List<BatchStatus> getList(long batchId) { return getList(Collections.singletonList(batchId)); } @Override public List<BatchStatus> getList(List<Long> batchIds) { int orCount = (batchIds.size() -1) / 1000; String query = "select *\n" + "from USCI_BATCH.BATCH_STATUS\n" + "where "; MapSqlParameterSource params = new MapSqlParameterSource(); if (orCount > 0) { query+="BATCH_ID in (:BATCH_IDS0)\n"; params.addValue("BATCH_IDS0", batchIds.subList(0,1000)); for (int i = 1; i <= orCount; i++) { if (i == orCount) { query += "or BATCH_ID in (:BATCH_IDS" + i + ")\n"; params.addValue("BATCH_IDS" + i, batchIds.subList(i * 1000, batchIds.size())); } else { query += "or BATCH_ID in (:BATCH_IDS" + i + ")\n"; params.addValue("BATCH_IDS" + i, batchIds.subList(i * 1000, (i + 1) * 1000)); } } } else { query+="BATCH_ID in (:BATCH_IDS0)\n"; params.addValue("BATCH_IDS0", batchIds); } query+="order by RECEIPT_DATE desc, STATUS_ID"; return npJdbcTemplate.query(query,params,new BatchStatusMapper()); } private static class BatchStatusMapper implements RowMapper<BatchStatus> { public BatchStatus mapRow(ResultSet rs, int rowNum) throws SQLException { BatchStatus batchStatus = new BatchStatus(); batchStatus.setBatchId(rs.getLong("BATCH_ID")); batchStatus.setStatus(BatchStatusType.getBatchStatus(rs.getInt("STATUS_ID"))); batchStatus.setReceiptDate(SqlJdbcConverter.convertToLocalDateTime(rs.getTimestamp("RECEIPT_DATE"))); batchStatus.setText(rs.getString("DESCRIPTION")); return batchStatus; } } } <file_sep>Ext.onReady(function () { Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.selection.CellModel', 'Ext.grid.*', 'Ext.data.*' ]); Ext.define('AuditEvemt', { extend: 'Ext.data.Model', fields: ['id', 'userId', 'auditTime', 'tableName', 'content', 'eventName', 'userName'] }); var selStore = Ext.create('Ext.data.Store', { id: 'selStore', model: 'AuditEvemt', remoteSort: true, autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/audit/getAuditJson', actionMethods: { read: 'GET' }, extraParams: { userId: '10916' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } } }); var selCreditorsGrid = Ext.create('Ext.grid.Panel', { id: 'selCreditorsGrid', sortable: true, multiSelect: true, store: selStore, columns: [{ dataIndex: 'userName', flex: 1, text: 'Пользователь' }, { dataIndex: 'eventName', text: 'Действие', flex: 1 }, { dataIndex: 'tableName', text: 'Таблица', flex: 1 }, { dataIndex: 'content', text: 'Описание', flex: 1 }, { dataIndex: 'auditTime', text: 'Время аудита', renderer: Ext.util.Format.dateRenderer('d.m.Y H:i:s'), flex: 1 }] }); Ext.create('Ext.Panel', { width: 900, height: 600, padding: 10, title: 'Audit', layout: 'border', renderTo: Ext.getBody(), //'admin-content', items: [{ xtype: 'panel', region: 'north', margin: '0 0 0 0', autoScroll: true, height: 220, items: [{ xtype: 'panel', layout: 'hbox', border: false, items: [{ xtype: 'datefield', fieldLabel: 'Дата аудита не менее ', allowBlank: false, name: 'from_date', id: 'from_date', format: 'Y-m-d' }, { xtype: 'datefield', fieldLabel: 'Дата аудита не более ', allowBlank: false, name: 'to_date', id: 'to_date', format: 'Y-m-d', margin: '0 0 0 10', }] }, { xtype: 'textfield', id: 'table', fieldLabel: 'Название таблицы содержит ', allowBlank: false, name: 'name' }, { xtype: 'button', id: 'AddButton', flex: 1, text: 'Применить фильтр', listeners: { click: function (field, newValue, oldValue, options) { grid = Ext.getCmp("selCreditorsGrid"); val1 = Ext.getCmp("table"); grid.store.clearFilter(); grid.getView().refresh(); from_date = Ext.getCmp("from_date"); to_date = Ext.getCmp("to_date"); var dateFrom_formated = Ext.Date.format(from_date.getValue(), 'Y-m-d'); var dateTo_formated = Ext.Date.format(to_date.getValue(), 'Y-m-d'); if ((dateTo_formated == '') && (val1.rawValue == '')) { for (var i = 0; i < grid.getStore().data.length; i++) { var record = grid.getStore().getAt(i); grid.store.filter( new Ext.util.Filter({ filterFn: function (record) { grid.getView().refresh(); return (record.data.auditTime >= dateFrom_formated) } })); } } else { if ((dateFrom_formated == '') && (val1.rawValue == '')) { for (var i = 0; i < grid.getStore().data.length; i++) { var record = grid.getStore().getAt(i); grid.store.filter( new Ext.util.Filter({ filterFn: function (record) { grid.getView().refresh(); return (record.data.auditTime <= dateTo_formated) } })); } } else { if ((dateFrom_formated == '') && (dateTo_formated == '')) { grid.store.filter([{ property: "tableName", value: val1.rawValue, anyMatch: true, caseSensitive: false }]); } else { if (val1.rawValue == '') { for (var i = 0; i < grid.getStore().data.length; i++) { var record = grid.getStore().getAt(i); grid.store.filter( new Ext.util.Filter({ filterFn: function (record) { grid.getView().refresh(); return (record.data.auditTime >= dateFrom_formated && record.data.auditTime <= dateTo_formated ) } })); } } else { if (dateFrom_formated == '') { grid.store.filter([{ property: "tableName", value: val1.rawValue, anyMatch: true, caseSensitive: false }]); for (var i = 0; i < grid.getStore().data.length; i++) { var record = grid.getStore().getAt(i); grid.store.filter( new Ext.util.Filter({ filterFn: function (record) { grid.getView().refresh(); return ( record.data.auditTime <= dateTo_formated ) } })); } } else { if (dateTo_formated == '') { grid.store.filter([{ property: "tableName", value: val1.rawValue, anyMatch: true, caseSensitive: false }]); for (var i = 0; i < grid.getStore().data.length; i++) { var record = grid.getStore().getAt(i); grid.store.filter( new Ext.util.Filter({ filterFn: function (record) { grid.getView().refresh(); return ( record.data.auditTime >= dateFrom_formated ) } })); } } else { if ((dateFrom_formated == '') && (dateTo_formated == '') && (val1.rawValue == '')) { grid.store.clearFilter(); grid.getView().refresh(); } else { grid.store.filter([{ property: "tableName", value: val1.rawValue, anyMatch: true, caseSensitive: false }]); for (var i = 0; i < grid.getStore().data.length; i++) { var record = grid.getStore().getAt(i); grid.store.filter( new Ext.util.Filter({ filterFn: function (record) { grid.getView().refresh(); return (record.data.auditTime >= dateFrom_formated && record.data.auditTime <= dateTo_formated ) } })); } } } } } } } } } } }, { xtype: 'button', id: 'Button', flex: 1, text: 'Очистить фильтр', listeners: { click: function (field, newValue, oldValue, options) { val1 = Ext.getCmp("table"); val1.setValue(''); val2 = Ext.getCmp("from_date"); val2.setValue(''); val3 = Ext.getCmp("to_date"); val3.setValue(''); grid = Ext.getCmp("selCreditorsGrid"); grid.store.clearFilter(); grid.getView().refresh(); } } }] }, { xtype: 'panel', autoScroll: true, title: 'Таблица аудита', region: 'south', height: 430, items: [selCreditorsGrid] }], renderTo: Ext.getBody() }); }); <file_sep>package kz.bsbnb.usci.core.dao; import kz.bsbnb.usci.model.adm.Position; import java.util.List; /** * @author <NAME> */ public interface PositionDao { List<Position> getUserPosList(); List<Position> getUserPosListByProductId(Long userid, Long productId); Position getUserPosById(Long id); void addUserPosition(Long userId, Long productId, List<Long> positionIds); void delUserPosition(Long userId, Long productId, List<Long> positionIds); } <file_sep>package kz.bsbnb.usci.receiver.batch.service.impl; import kz.bsbnb.usci.core.client.RespondentClient; import kz.bsbnb.usci.eav.client.ProductClient; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.eav.repository.MetaClassRepository; import kz.bsbnb.usci.model.batch.Product; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.model.respondent.Respondent; import kz.bsbnb.usci.receiver.batch.service.BatchEntryService; import kz.bsbnb.usci.receiver.dao.BatchEntryDao; import kz.bsbnb.usci.receiver.model.BatchEntry; import kz.bsbnb.usci.receiver.model.BatchFile; import kz.bsbnb.usci.receiver.processor.BatchReceiver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author <NAME> */ @Service public class BatchEntryServiceImpl implements BatchEntryService { private static final Logger logger = LoggerFactory.getLogger(BatchEntryServiceImpl.class); private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd.MM.yyyy"); private final BatchEntryDao batchEntryDao; private final RespondentClient respondentClient; private final BatchReceiver batchReceiver; private final MetaClassRepository metaClassRepository; private final JdbcTemplate jdbcTemplate; private final ProductClient productClient; @Value("${batch.entryDir}") private String batchEntryDir; public BatchEntryServiceImpl(BatchEntryDao batchEntryDao, RespondentClient respondentClient, BatchReceiver batchReceiver, MetaClassRepository metaClassRepository, JdbcTemplate jdbcTemplate, ProductClient productClient) { this.batchEntryDao = batchEntryDao; this.respondentClient = respondentClient; this.batchReceiver = batchReceiver; this.metaClassRepository = metaClassRepository; this.jdbcTemplate = jdbcTemplate; this.productClient = productClient; } @Override public Long save(BatchEntry batch) { return batchEntryDao.save(batch); } @Override public BatchEntry load(Long batchId) { return batchEntryDao.load(batchId); } @Override public List<BatchEntry> getBatchEntriesByUserId(Long userId) { return batchEntryDao.getBatchEntriesByUserId(userId); } @Override public void delete(Long batchEntryId) { batchEntryDao.remove(batchEntryId); } @Override public void confirmBatchEntries(Long userId, boolean isNb) { List<BatchEntry> batchEntries = getBatchEntriesByUserId(userId); if (batchEntries.isEmpty()) throw new UsciException("Нет батчей для утверждения"); List<Long> batchEntryIds = new ArrayList<>(); Respondent respondent = respondentClient.getRespondentByUserId(userId, isNb); for (BatchEntry batchEntry : batchEntries) { String formattedReportDate = batchEntry.getRepDate().format(DATE_FORMAT); // определяю продукт; то есть необходимо наш батч отнести к продукту String productCode = null; MetaClass metaClass = metaClassRepository.getMetaClass(batchEntry.getMetaClassId()); /*if (metaClass.isDictionary()) { productCode = "DICT"; } else {*/ List<Long> products = productClient.getProductIdsByMetaClassId(metaClass.getId()); Product product = productClient.getProductById(products.get(0)); productCode = product.getCode(); //} // формируем manifest файл для каждого batchEntry String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<batch>\n" + "<entities xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"; xml += batchEntry.getValue() + "\n"; xml += "\n</entities>\n" + "</batch>"; String manifest = "<manifest>\n" + "\t<product>" + productCode + "</product>\n" + "\t<report_date>" + formattedReportDate + "</report_date>\n"; manifest += "\t<respondent>"+ respondent.getCode() + "</respondent>\n"; manifest += "</manifest>"; File tempBatchEntryFile = null; try { tempBatchEntryFile = File.createTempFile("tmp", ".zip", new File(batchEntryDir)); } catch (IOException e) { throw new UsciException(e); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ZipOutputStream zipFile = new ZipOutputStream(bos)) { ZipEntry zipEntryData = new ZipEntry("data.xml"); zipFile.putNextEntry(zipEntryData); zipFile.write(xml.getBytes()); // ZipEntry zipEntryManifest = new ZipEntry("usci_manifest.xml"); zipFile.putNextEntry(zipEntryManifest); zipFile.write(manifest.getBytes()); } catch (IOException e) { throw new UsciException(e); } byte[] zipBytes = bos.toByteArray(); try (FileOutputStream fileOutputStream = new FileOutputStream(tempBatchEntryFile)) { fileOutputStream.write(zipBytes); } catch (IOException e) { throw new UsciException(e); } logger.info("BatchEntry(id={}, userId={}, isNb={}) отправлен на обработку", batchEntry.getId(), userId, isNb); BatchFile batchFile = new BatchFile(userId, isNb, tempBatchEntryFile.getPath()); batchFile.setFileContent(zipBytes); batchFile.setFileName(tempBatchEntryFile.getName()); batchFile.setBatchEntryId(batchEntry.getId()); batchReceiver.receiveBatch(batchFile); batchEntryIds.add(batchEntry.getId()); } batchEntryDao.setProcessed(batchEntryIds); } } <file_sep>package kz.bsbnb.usci.util; import java.math.BigDecimal; import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; /** * @author <NAME> */ public class SqlJdbcConverter { public static Timestamp convertToSqlTimestamp(LocalDateTime date) { return date == null? null: Timestamp.valueOf(date); } public static java.sql.Date convertToSqlDate(LocalDate date) { return date == null? null: java.sql.Date.valueOf(date); } public static java.sql.Date convertToSqlDate(java.util.Date date) { return date == null? null: new java.sql.Date(date.getTime()); } public static java.sql.Date convertToSqlDate(String date) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); LocalDate localDate = LocalDate.parse(date,formatter); return (date == null || date.equals("")) ? null: java.sql.Date.valueOf(localDate); } public static Long convertToLong(Object value) { return value == null? null: (value instanceof BigDecimal)? ((BigDecimal)value).longValue() : (Long)value; } public static Integer convertToInt(Object value) { return value == null? null: (value instanceof BigDecimal)? ((BigDecimal)value).intValue() : (Integer)value; } public static Short convertToShort(Object value) { return value == null? null: (value instanceof BigDecimal)? ((BigDecimal)value).shortValue() : (Short)value; } public static Byte convertToByte(Object value) { return value == null? null: (value instanceof BigDecimal)? ((BigDecimal)value).byteValue() : (Byte)value; } public static Byte convertToByte(Boolean value) { return value ? Byte.valueOf("1") : 0; } public static Boolean convertToBoolean(Object value) { return value == null? null: convertToByte(value) == 1; } public static Double convertToDouble(Object value) { return value == null? null: (value instanceof BigDecimal)? ((BigDecimal)value).doubleValue() : (Double)value; } public static Byte convertBooleanToByte(Boolean value) { return value == null? null: value? (byte)1: (byte)0; } public static LocalDateTime convertToLocalDateTime(Timestamp timestamp) { return timestamp == null? null: timestamp.toLocalDateTime(); } public static LocalDateTime convertToLocalDateTime(Object timestamp) { return timestamp == null? null: convertToLocalDateTime((Timestamp) timestamp); } public static LocalDate convertToLocalDate(java.sql.Date date) { return date == null? null: date.toLocalDate(); } public static LocalDate convertToLocalDate(Object date) { return date == null? null: convertToLocalDate((Timestamp) date); } public static Date convertToDate(LocalDate localDate) { return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); } public static LocalDate convertToLocalDate(java.util.Date date) { return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } /** * Отдельный метод был добавлен так как String.valueOf возвращает "null" строку когда value = null */ public static String convertObjectToString(Object value) { return value == null? null: (String) value; } public static LocalDate convertToLocalDate(java.sql.Timestamp date) { return date == null? null: date.toLocalDateTime().toLocalDate(); } public static Boolean convertVarchar2ToBoolean(String string) { return string == null? null: (string.equals("1")? true: (string.equals("0")? false: null)); } public static Boolean convertVarchar2ToBoolean(Object string) { return string == null? null: (string.equals("1")? true: (string.equals("0")? false: null)); } public static String convertToString(LocalDate value) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); String formattedString = value.format(formatter); return value == null? null: formattedString; } public static LocalDate convertToLocalDate(String date) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); return date == null? null: LocalDate.parse(date, formatter); } } <file_sep>package kz.bsbnb.usci.brms.exception; import kz.bsbnb.usci.model.exception.UsciException; import java.util.List; import java.util.Set; /** * @author <NAME> */ public class BrmsException extends UsciException { public BrmsException(List<String> errorMessages) { super(errorMessages); } public BrmsException(Set<String> errorMessages) { super(errorMessages); } } <file_sep>package kz.bsbnb.usci.receiver.model.exception; import kz.bsbnb.usci.model.exception.UsciException; /** * @author <NAME> */ public class ReceiverException extends UsciException { public ReceiverException() { } public ReceiverException(String message) { super(message); } } <file_sep>package kz.bsbnb.usci.brms.service; import kz.bsbnb.usci.brms.dao.PackageDao; import kz.bsbnb.usci.brms.model.RulePackage; import org.springframework.stereotype.Service; import java.util.List; /** * @author <NAME> */ @Service public class PackageServiceImpl implements PackageService { private final PackageDao packageDao; public PackageServiceImpl(PackageDao packageDao) { super(); this.packageDao = packageDao; } @Override public long savePackage(String rulePackageName) { return packageDao.savePackage(rulePackageName); } @Override public RulePackage load(long id) { return packageDao.loadBatch(id); } @Override public List<RulePackage> getAllPackages() { return packageDao.getAllPackages(); } } <file_sep>package kz.bsbnb.usci.receiver.reader; import kz.bsbnb.usci.eav.model.meta.MetaDataType; import kz.bsbnb.usci.receiver.model.ManifestData; import kz.bsbnb.usci.receiver.model.exception.ReceiverException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.time.format.DateTimeParseException; /** * @author <NAME> */ public class ManifestParser extends MainReader { private final ManifestData manifestData = new ManifestData(); @Override public void startElement(XMLEvent event, StartElement startElement, String localName) { switch (localName) { case "manifest": break; case "product": break; case "respondent": break; case "report_date": break; } } @Override public boolean endElement(String localName) { switch (localName) { case "manifest": return true; case "respondent": manifestData.setRespondent(data.toString()); data.setLength(0); break; case "product": manifestData.setProduct(data.toString()); data.setLength(0); break; case "report_date": try { manifestData.setReportDate(MetaDataType.parseDate(data.toString())); } catch (DateTimeParseException e) { throw new ReceiverException(e.getMessage()); } data.setLength(0); break; } return false; } ManifestData getManifestData() { return manifestData; } } <file_sep>package kz.bsbnb.usci.model.util; import kz.bsbnb.usci.model.persistence.Persistable; /** * @author <NAME> */ public class Text extends Persistable { private static final long serialVersionUID = 1L; private String type; private String code; private String nameRu; private String nameKz; public Text() { super(); } public Text(Long id, String type, String code, String nameRu, String nameKz) { super(id); this.type = type; this.code = code; this.nameRu = nameRu; this.nameKz = nameKz; } @Override public Text setId(Long id) { super.setId(id); return this; } public String getType() { return type; } public Text setType(String type) { this.type = type; return this; } public String getCode() { return code; } public Text setCode(String code) { this.code = code; return this; } public String getNameRu() { return nameRu; } public Text setNameRu(String nameRu) { this.nameRu = nameRu; return this; } public String getNameKz() { return nameKz; } public Text setNameKz(String nameKz) { this.nameKz = nameKz; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Text text = (Text) o; if (!getType().equals(text.getType())) return false; if (!getCode().equals(text.getCode())) return false; return true; } @Override public int hashCode() { int result = getType().hashCode(); result = 31 * result + getCode().hashCode(); return result; } @Override public String toString() { return "Constant{" + "type='" + type + '\'' + ", code='" + code + '\'' + ", nameRu='" + nameRu + '\'' + ", nameKz='" + nameKz + '\'' + '}'; } } <file_sep>package kz.bsbnb.usci.receiver; import kz.bsbnb.usci.receiver.config.ReceiverConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.client.RestTemplate; @SpringBootApplication @Configuration @ComponentScan(basePackages = {"kz.bsbnb.usci.receiver", "kz.bsbnb.usci.sync", "kz.bsbnb.usci.eav", "kz.bsbnb.usci.brms"}) @EnableConfigurationProperties @EnableScheduling @EnableFeignClients(basePackages = {"kz.bsbnb.usci.sync.client", "kz.bsbnb.usci.core.client", "kz.bsbnb.usci.eav.client", "kz.bsbnb.usci.util.client", "kz.bsbnb.usci.mail.client"}) @EnableEurekaClient @RibbonClient(name = "receiver", configuration = ReceiverConfig.class) public class ReceiverApplication { public static void main(String[] args) { SpringApplication.run(ReceiverApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } } <file_sep>package kz.bsbnb.usci.portlet.batch_entry; import com.liferay.util.bridges.mvc.MVCPortlet; public class BatchEntryPortlet extends MVCPortlet { } <file_sep>package kz.bsbnb.usci.model.batch; import kz.bsbnb.usci.model.persistence.Persistable; import java.util.HashSet; import java.util.Set; /** * @author <NAME> * */ public class Product extends Persistable { private String code; private String name; private byte[] xsd; private Set<Long> confirmPositionIds = new HashSet<>(); private boolean confirmWithApproval = false; private boolean confirmWithSignature = false; private String crosscheckPackageName; public Product() { super(); } public Product(Long id) { super(id); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getXsd() { return xsd; } public void setXsd(byte[] xsd) { this.xsd = xsd; } public Set<Long> getConfirmPositionIds() { return confirmPositionIds; } public void setConfirmPositionIds(Set<Long> confirmPositionIds) { this.confirmPositionIds = confirmPositionIds; } public boolean isConfirmWithApproval() { return confirmWithApproval; } public void setConfirmWithApproval(boolean confirmWithApproval) { this.confirmWithApproval = confirmWithApproval; } public boolean isConfirmWithSignature() { return confirmWithSignature; } public void setConfirmWithSignature(boolean confirmWithSignature) { this.confirmWithSignature = confirmWithSignature; } public String getCrosscheckPackageName() { return crosscheckPackageName; } public void setCrosscheckPackageName(String crosscheckPackageName) { this.crosscheckPackageName = crosscheckPackageName; } @Override public String toString() { return "Product{" + "code='" + code + '\'' + ", name='" + name + '\'' + ", crosscheckPackageName='" + crosscheckPackageName + '\'' + ", confirmPositionIds=" + confirmPositionIds + ", confirmWithApproval=" + confirmWithApproval + ", confirmWithSignature=" + confirmWithSignature + ", id=" + id + '}'; } } <file_sep>package kz.bsbnb.usci.core.dao; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.model.respondent.*; import kz.bsbnb.usci.util.SqlJdbcConverter; import oracle.jdbc.OracleTypes; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.jdbc.core.support.SqlLobValue; import org.springframework.jdbc.support.lob.DefaultLobHandler; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.io.ByteArrayInputStream; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ @Repository public class ConfirmDaoImpl implements ConfirmDao { private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; private SimpleJdbcInsert confirmInsert; private SimpleJdbcInsert confirmMessageInsert; private SimpleJdbcInsert confirmMessageFileInsert; public ConfirmDaoImpl(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) { this.jdbcTemplate = jdbcTemplate; this.npJdbcTemplate = npJdbcTemplate; this.confirmInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_RSPDENT") .withTableName("CONFIRM") .usingGeneratedKeyColumns("ID"); this.confirmMessageInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_RSPDENT") .withTableName("CONFIRM_MESSAGE") .usingGeneratedKeyColumns("ID"); this.confirmMessageFileInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_RSPDENT") .withTableName("CONFIRM_MSG_FILE") .usingGeneratedKeyColumns("ID"); } @Override public long insertConfirm(Confirm confirm) { Number id = confirmInsert.executeAndReturnKey(new MapSqlParameterSource() .addValue("USER_ID", confirm.getUserId()) .addValue("CHANGE_DATE", SqlJdbcConverter.convertToSqlTimestamp(confirm.getChangeDate())) .addValue("CREDITOR_ID", confirm.getRespondentId()) .addValue("REPORT_DATE", SqlJdbcConverter.convertToSqlDate(confirm.getReportDate())) .addValue("STATUS_ID", confirm.getStatus().getId()) .addValue("BEG_DATE", SqlJdbcConverter.convertToSqlTimestamp(confirm.getFirstBatchLoadTime())) .addValue("END_DATE", SqlJdbcConverter.convertToSqlTimestamp(confirm.getLastBatchLoadTime())) .addValue("PRODUCT_ID", SqlJdbcConverter.convertToLong(confirm.getProductId())) .addValue("IS_RECONFIRM", confirm.isReconfirm()? 1: 0)); confirm.setId(id.longValue()); return id.longValue(); } @Override public Optional<Confirm> getConfirm(long respondentId, LocalDate reportDate, long productId) { try { List<Map<String, Object>> rows = npJdbcTemplate.queryForList("select * " + " from USCI_RSPDENT.CONFIRM\n" + " where CREDITOR_ID = :CREDITOR_ID\n" + " and REPORT_DATE = :REPORT_DATE" + " and PRODUCT_ID = :PRODUCT_ID", new MapSqlParameterSource("CREDITOR_ID", respondentId) .addValue("REPORT_DATE", SqlJdbcConverter.convertToSqlDate(reportDate)) .addValue("PRODUCT_ID", productId)); if (rows.isEmpty()) return Optional.empty(); if (rows.size() > 1) throw new UsciException("Ошибка нахождения записи в таблице USCI_RSPDENT.CONFIRM"); return Optional.of(getConfirmFromJdbcMap(rows).get(0)); } catch(EmptyResultDataAccessException e) { return Optional.empty(); } } @Override public Confirm getConfirm(long confirmId) { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from USCI_RSPDENT.CONFIRM where ID = ?", new Object[] {confirmId}); if (rows.size() != 1) throw new UsciException("Ошибка нахождения записи в таблице USCI_RSPDENT.CONFIRM"); return getConfirmFromJdbcMap(rows).get(0); } @Override @Transactional public void addConfirmMessage(ConfirmMessage message) { Number messageId = confirmMessageInsert.executeAndReturnKey(new MapSqlParameterSource() .addValue("CONFIRM_ID", message.getConfirmId()) .addValue("USER_ID", message.getUserId()) .addValue("SEND_DATE", SqlJdbcConverter.convertToSqlTimestamp(message.getSendDate())) .addValue("TEXT", message.getText())); message.setId(messageId.longValue()); for (ConfirmMessageFile attachment : message.getFiles()) { Number attId = confirmMessageFileInsert.executeAndReturnKey(new MapSqlParameterSource() .addValue("CONFIRM_MSG_ID", message.getId()) .addValue("FILE_NAME",attachment.getFileName()) .addValue("CONTENT", new SqlLobValue(new ByteArrayInputStream(attachment.getContent()), attachment.getContent().length, new DefaultLobHandler()), OracleTypes.BLOB)); attachment.setId(attId.longValue()); } } @Override public void updateConfirm(Confirm confirm) { MapSqlParameterSource params = new MapSqlParameterSource() .addValue("ID", confirm.getId()) .addValue("USER_ID", confirm.getUserId()) .addValue("STATUS_ID", confirm.getStatus().getId()) .addValue("IS_RECONFIRM", confirm.isReconfirm()? 1: 0) .addValue("END_DATE", SqlJdbcConverter.convertToSqlTimestamp(confirm.getLastBatchLoadTime())); int count = npJdbcTemplate.update("update USCI_RSPDENT.CONFIRM\n" + " set STATUS_ID = :STATUS_ID,\n" + " END_DATE = :END_DATE,\n" + " IS_RECONFIRM = :IS_RECONFIRM,\n" + " USER_ID = :USER_ID\n" + "where ID = :ID", params); if (count != 1) throw new UsciException("Ошибка update записи в таблице USCI_RSPDENT.CONFIRM"); } @Override public List<ConfirmMessageJson> getMessagesByConfirmId(long confirmId) { List<ConfirmMessageJson> list = new ArrayList<>(); List<Map<String, Object>> rows = jdbcTemplate.queryForList( "select cf.*, u.FIRST_NAME || ' ' || u.LAST_NAME || ' ' || u.MIDDLE_NAME as USER_NAME\n" + " from USCI_RSPDENT.CONFIRM_MESSAGE cf, USCI_ADM.USERS u\n" + " where cf.CONFIRM_ID = ?\n" + " and cf.USER_ID = u.USER_ID", new Object[]{confirmId}); for (Map<String, Object> row : rows) { ConfirmMessageJson confirmMessage = new ConfirmMessageJson(); confirmMessage.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); confirmMessage.setSendDate(SqlJdbcConverter.convertToLocalDateTime(row.get("SEND_DATE"))); confirmMessage.setText(SqlJdbcConverter.convertObjectToString(row.get("TEXT"))); confirmMessage.setUserId(SqlJdbcConverter.convertToLong(row.get("USER_ID"))); confirmMessage.setUserName(SqlJdbcConverter.convertObjectToString(row.get("USER_NAME"))); // прикрепляемых данных очень мало вцелом посему можем файлы извлекать по отдельности для каждого сообщения confirmMessage.setFiles(getFilesByMessage(confirmMessage.getId())); list.add(confirmMessage); } return list; } @Override public List<ConfirmMsgFileJson> getFilesByMessage(long confirmId) { ArrayList<ConfirmMsgFileJson> attachments = new ArrayList<>(); List<Map<String, Object>> rows = jdbcTemplate.queryForList("select *\n" + "from USCI_RSPDENT.CONFIRM_MSG_FILE\n" + "where CONFIRM_MSG_ID = ?\n", new Object[]{confirmId}); for (Map<String, Object> row : rows) { ConfirmMsgFileJson file = new ConfirmMsgFileJson(); file.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); file.setContent((byte[]) row.get("CONTENT")); file.setFileName(SqlJdbcConverter.convertObjectToString(row.get("FILE_NAME"))); file.setMessageId(SqlJdbcConverter.convertToLong(row.get("CONFIRM_MSG_ID"))); attachments.add(file); } return attachments; } @Override public byte[] getMessageFileContent(long fileId) { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select CONTENT\n" + "from USCI_RSPDENT.CONFIRM_MSG_FILE\n" + "where ID = ?", new Object[] {fileId}); if (rows.size() != 1) throw new UsciException("Ошибка получение записи ищ таблицы USCI_RSPDENT.CONFIRM_MSG_FILE"); return (byte[])rows.get(0).get("CONTENT"); } private List<Confirm> getConfirmFromJdbcMap(List<Map<String, Object>> rows) { List<Confirm> list = new ArrayList<>(); for (Map<String, Object> row : rows) { Confirm confirm = new Confirm(); confirm.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); confirm.setFirstBatchLoadTime(SqlJdbcConverter.convertToLocalDateTime(row.get("BEG_DATE"))); confirm.setLastBatchLoadTime(SqlJdbcConverter.convertToLocalDateTime(row.get("END_DATE"))); confirm.setProductId(SqlJdbcConverter.convertToLong(row.get("PRODUCT_ID"))); confirm.setRespondentId(SqlJdbcConverter.convertToLong(row.get("CREDITOR_ID"))); confirm.setUserId(SqlJdbcConverter.convertToLong(row.get("USER_ID"))); confirm.setChangeDate(SqlJdbcConverter.convertToLocalDateTime(row.get("CHANGE_DATE"))); confirm.setReconfirm(SqlJdbcConverter.convertToBoolean(row.get("IS_RECONFIRM"))); confirm.setStatus(row.get("STATUS_ID") != null? ConfirmStatus.getApprovalStatus(SqlJdbcConverter.convertToLong(row.get("STATUS_ID"))): null); confirm.setReportDate(SqlJdbcConverter.convertToLocalDate(row.get("REPORT_DATE"))); list.add(confirm); } return list; } } <file_sep>var label_ERROR = 'Қате'; var label_SAVE = 'Сақтау'; var label_FIELDS = 'Қажетті жолақты толтырыңыз '; var label_SAVING = 'Сақтау орындалуда '; var label_CANCEL = 'Болдырмау'; var label_NAME = 'Атауы'; var label_PRODUCT = 'Өнім'; var label_DOWN = 'XSD файлды жүктеу'; var label_XSD = 'Барлық өнімдер үшін xsd өндіру'; var label_XSDING = 'xsd өнімдерін өндіру орындалуда'; var label_INFO = 'Ақпарат'; var label_XSD_END = 'xsd өнімдерін өндіру аяқталды'; var label_CODE = 'Код'; var label_ADD = 'Қосу'; var label_NO_DATA = 'Бейнелеу үшін деректер жоқ'; var label_DELETE = 'Жою'; var label_PRODUCTS = 'Өнім'; var label_META = 'Мета класстар таңдалынды'; var label_AVA_META = 'Қолжетімді мета класстар '; <file_sep>package kz.bsbnb.usci.receiver.queue.impl; import kz.bsbnb.usci.receiver.model.Batch; import kz.bsbnb.usci.receiver.queue.BatchQueueOrder; import java.util.List; /** * @author <NAME> */ public abstract class AbstractQueueOrder implements BatchQueueOrder { @Override public Batch getNextBatch(List<Batch> batches) { Batch result = null; for (Batch file : batches) { if (result == null || compare(result, file) > 0) result = file; } return result; } } <file_sep>package kz.bsbnb.usci.eav.meta.dao; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import kz.bsbnb.usci.eav.dao.ProductDao; import kz.bsbnb.usci.model.adm.Position; import kz.bsbnb.usci.model.batch.Product; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.model.json.ApproveIterationJson; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.lang.reflect.Type; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; /** * @author <NAME> * @author <NAME> */ @Repository public class ProductDaoImpl implements ProductDao { private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; private final SimpleJdbcInsert productMetaInsert; private final SimpleJdbcInsert productInsert; private static final Gson gson = new Gson(); public ProductDaoImpl(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) { this.jdbcTemplate = jdbcTemplate; this.npJdbcTemplate = npJdbcTemplate; this.productInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("EAV_CORE") .withTableName("EAV_M_PRODUCT") .usingGeneratedKeyColumns("ID"); this.productMetaInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("EAV_CORE") .withTableName("EAV_M_PRODUCT_CLASS") .usingColumns("PRODUCT_ID", "META_CLASS_ID") .usingGeneratedKeyColumns("ID"); } @Override public List<Product> getProducts() { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from EAV_CORE.EAV_M_PRODUCT"); return getProductFromJdbcMap(rows); } @Override public Product getProductById(Long id) { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from EAV_CORE.EAV_M_PRODUCT where ID = ?", id); if (rows.size() != 1) throw new UsciException("Ошибка нахождения записи в таблице EAV_CORE.EAV_M_PRODUCT"); return getProductFromJdbcMap(rows).get(0); } @Override public Optional<Product> findProductByCode(String code) { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select *\n" + "from EAV_CORE.EAV_M_PRODUCT\n" + "where CODE = ?\n", code); if (rows.size() == 0) return Optional.empty(); if (rows.size() > 1) throw new UsciException("Ошибка нахождения записи в таблице EAV_CORE.EAV_M_PRODUCT"); Product product = getProductFromJdbcMap(rows).get(0); return Optional.of(product); } @Override public List<Long> getProductMetaClassIds(Long productId) { return jdbcTemplate.queryForList("select META_CLASS_ID\n" + "from EAV_CORE.EAV_M_PRODUCT_CLASS\n" + "where PRODUCT_ID = ?", new Object[]{productId}, Long.class); } @Override public long createProduct(Product product) { Number id = this.productInsert.executeAndReturnKey(new MapSqlParameterSource() .addValue("CODE", product.getCode()) .addValue("NAME", product.getName()) .addValue("XSD", product.getXsd() != null? new String(product.getXsd()): null) .addValue("CONFIRM_WITH_APRV", SqlJdbcConverter.convertBooleanToByte(product.isConfirmWithApproval())) .addValue("CONFIRM_WITH_SIGN", SqlJdbcConverter.convertBooleanToByte(product.isConfirmWithSignature())) .addValue("CONFIRM_POS_IDS", product.getConfirmPositionIds()) .addValue("CROSSCHECK_PACKAGENAME", product.getCrosscheckPackageName())); product.setId(id.longValue()); return id.longValue(); } @Override public void updateProduct(Product product) { int count = npJdbcTemplate.update("update EAV_CORE.EAV_M_PRODUCT\n" + "set NAME = :NAME,\n" + " XSD = :XSD,\n" + " CROSSCHECK_PACKAGENAME = :CROSSCHECK_PACKAGENAME,\n" + " CONFIRM_WITH_APRV = :CONFIRM_WITH_APRV,\n" + " CONFIRM_WITH_SIGN = :CONFIRM_WITH_SIGN,\n" + " CONFIRM_POS_IDS = :CONFIRM_POS_IDS\n" + " where ID = :ID", new MapSqlParameterSource("ID", product.getId()) .addValue("NAME", product.getName()) .addValue("XSD", product.getXsd() != null? new String(product.getXsd()): null) .addValue("CROSSCHECK_PACKAGENAME", product.getCrosscheckPackageName()) .addValue("CONFIRM_WITH_APRV", SqlJdbcConverter.convertBooleanToByte(product.isConfirmWithApproval())) .addValue("CONFIRM_WITH_SIGN", SqlJdbcConverter.convertBooleanToByte(product.isConfirmWithSignature())) .addValue("CONFIRM_POS_IDS", product.getConfirmPositionIds().isEmpty()? null: gson.toJson(product.getConfirmPositionIds()))); if (count != 1) throw new UsciException("Ошибка update записи в таблице EAV_CORE.EAV_M_PRODUCT"); } @Override public void addProductMetaClass(Long productId, List<Long> metaIds) { List<MapSqlParameterSource> params = new ArrayList<>(); for (Long metaId : metaIds) params.add(new MapSqlParameterSource("META_CLASS_ID", metaId) .addValue("PRODUCT_ID", productId)); if (metaIds.size() > 1) { int counts[] = productMetaInsert.executeBatch(params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException("Ошибка insert записей в таблицу EAV_COR.EAV_M_PRODUCT_CLASS"); } else { int count = productMetaInsert.execute(params.get(0)); if (count != 1) throw new UsciException("Ошибка insert записей в таблицу EAV_COR.EAV_M_PRODUCT_CLASS"); } } @Override public void deleteProductMetaClass(Long productId, List<Long> metaIds) { List<MapSqlParameterSource> params = new ArrayList<>(); for (Long metaId : metaIds) { params.add(new MapSqlParameterSource("META_ID", metaId) .addValue("PRODUCT_ID", productId)); } String delete = "delete from EAV_CORE.EAV_M_PRODUCT_CLASS\n" + " where META_CLASS_ID = :META_ID\n" + " and PRODUCT_ID = :PRODUCT_ID"; if (metaIds.size() > 1) { int counts[] = npJdbcTemplate.batchUpdate(delete, params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException("Ошибка delete записей из таблицы EAV_CORE.EAV_M_PRODUCT_CLASS"); } else { int count = npJdbcTemplate.update(delete, params.get(0)); if (count != 1) throw new UsciException("Ошибка delete записей из таблицы EAV_CORE.EAV_M_PRODUCT_CLASS"); } } @Override public List<Long> getProductIdsByMetaClassId(Long metaClassId) { List<Long> products = jdbcTemplate.queryForList("select PRODUCT_ID\n" + "from EAV_CORE.EAV_M_PRODUCT_CLASS\n" + "where META_CLASS_ID = ?", new Object[] {metaClassId}, Long.class); if (products.size() != 1) throw new UsciException("Ошибка определения принадлежности класса к продукту"); return products; } @Override public List<Position> getPositions(Long productId, boolean available) { List<Position> positionList = new ArrayList<>(); ArrayList<Long> posIds = new ArrayList<>(); String confirmPositionIds = jdbcTemplate.queryForObject("select CONFIRM_POS_IDS from EAV_CORE.EAV_M_PRODUCT where ID = ?", new Object[]{productId}, String.class); String query = "select ID, NAME_RU from USCI_ADM.REF_POS\n"; MapSqlParameterSource params = new MapSqlParameterSource(); if (confirmPositionIds != null) { Type type = new TypeToken<ArrayList<Long>>(){}.getType(); posIds = gson.fromJson(confirmPositionIds, type); if (!available) query += "where ID in (:POSITION_IDS) \n"; else query += "where ID not in (:POSITION_IDS) \n"; params.addValue("POSITION_IDS", posIds); } else { if (!available) return Collections.emptyList(); } query += "order by ID desc"; List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); for (Map<String, Object> row : rows) { Position position = new Position(); position.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); position.setNameRu(SqlJdbcConverter.convertObjectToString(row.get("NAME_RU"))); positionList.add(position); } return positionList; } @Override public void addProductPosition(Long productId, List<Long> posIds) { String confirmPositionIds = jdbcTemplate.queryForObject("select CONFIRM_POS_IDS from EAV_CORE.EAV_M_PRODUCT where ID = ?", new Object[]{productId}, String.class); Set<Long> positionIds = new HashSet<>(); if (confirmPositionIds != null) { Type type = new TypeToken<Set<Long>>(){}.getType(); positionIds = gson.fromJson(confirmPositionIds, type); positionIds.addAll(posIds); } else { positionIds.addAll(posIds); } int count = npJdbcTemplate.update("update EAV_CORE.EAV_M_PRODUCT\n" + " set CONFIRM_POS_IDS = :CONFIRM_POS_IDS\n" + " where ID = :ID", new MapSqlParameterSource("ID", productId) .addValue("CONFIRM_POS_IDS", gson.toJson(positionIds))); if (count != 1) throw new UsciException("Ошибка update записи в таблице EAV_CORE.EAV_M_PRODUCT"); } @Override public void deleteProductPosition(Long productId, List<Long> posIds) { String confirmPositionIds = jdbcTemplate.queryForObject("select CONFIRM_POS_IDS from EAV_CORE.EAV_M_PRODUCT where ID = ?", new Object[]{productId}, String.class); Set<Long> positionIds = new HashSet<>(); Type type = new TypeToken<Set<Long>>(){}.getType(); positionIds = gson.fromJson(confirmPositionIds, type); positionIds.removeAll(posIds); int count = npJdbcTemplate.update("update EAV_CORE.EAV_M_PRODUCT\n" + " set CONFIRM_POS_IDS = :CONFIRM_POS_IDS\n" + " where ID = :ID", new MapSqlParameterSource("ID", productId) .addValue("CONFIRM_POS_IDS", positionIds.isEmpty()? null: gson.toJson(positionIds))); if (count != 1) throw new UsciException("Ошибка update записи в таблице EAV_CORE.EAV_M_PRODUCT"); } @Override public List<ApproveIterationJson> getApproveIterations(Long productId) { String approveIterations = jdbcTemplate.queryForObject("select APPROVE_ITERATIONS from EAV_CORE.EAV_M_PRODUCT where ID = ?", new Object[]{productId}, String.class); if (approveIterations != null) { Type type = new TypeToken<ArrayList<ApproveIterationJson>>(){}.getType(); List<ApproveIterationJson> approveIterationJsonList = gson.fromJson(approveIterations, type); approveIterationJsonList.sort(Comparator.comparing(o -> o.getIterationNumber())); return approveIterationJsonList; } else { return Collections.emptyList(); } } @Override public void setApproveIterations(Long productId, List<ApproveIterationJson> approveIterationJsonList) { int count = npJdbcTemplate.update("update EAV_CORE.EAV_M_PRODUCT\n" + " set APPROVE_ITERATIONS = :APPROVE_ITERATIONS\n" + " where ID = :ID", new MapSqlParameterSource("ID", productId) .addValue("APPROVE_ITERATIONS", approveIterationJsonList.isEmpty()? null: gson.toJson(approveIterationJsonList))); if (count != 1) throw new UsciException("Ошибка update записи в таблице EAV_CORE.EAV_M_PRODUCT"); } @Override public List<LocalDate> getHolidayDays() { String query = "select HOLIDAY_DATE from USCI_WS.NSI_HOLIDAY order by HOLIDAY_DATE asc"; List<LocalDate> rows = jdbcTemplate.queryForList(query, LocalDate.class); return rows; } public static List<Product> getProductFromJdbcMap(List<Map<String, Object>> rows) { List<Product> list = new ArrayList<>(); for (Map<String, Object> row : rows) { Product product = new Product(SqlJdbcConverter.convertToLong(row.get("ID"))); product.setCode(SqlJdbcConverter.convertObjectToString(row.get("CODE"))); product.setName(SqlJdbcConverter.convertObjectToString(row.get("NAME"))); product.setCrosscheckPackageName(SqlJdbcConverter.convertObjectToString(row.get("CROSSCHECK_PACKAGENAME"))); product.setConfirmWithApproval(SqlJdbcConverter.convertToBoolean(row.get("CONFIRM_WITH_APRV"))); product.setConfirmWithSignature(SqlJdbcConverter.convertToBoolean(row.get("CONFIRM_WITH_SIGN"))); String confirmPositionIds = SqlJdbcConverter.convertObjectToString(row.get("CONFIRM_POS_IDS")); if (confirmPositionIds != null) { Type type = new TypeToken<Set<Long>>(){}.getType(); product.setConfirmPositionIds(gson.fromJson(confirmPositionIds, type)); } String xsd = SqlJdbcConverter.convertObjectToString(row.get("XSD")); if (xsd != null) { product.setXsd(xsd.getBytes()); } list.add(product); } return list; } } <file_sep>package kz.bsbnb.usci.util; /** * @author <NAME> */ public class Constants { public static final String DIGITAL_SIGNING_ORG_IDS_CONFIG_CODE = "DIGITAL_SIGNING_ORG_IDS"; } <file_sep>package kz.bsbnb.usci.util.service; import kz.bsbnb.usci.model.util.Text; import java.util.List; public interface TextService { Text getText(Text text); Text getText(Long id); void updateText(Text global); List<Text> getTextListByType(List<String> types); } <file_sep>package kz.bsbnb.usci.eav.model.base; import com.fasterxml.jackson.annotation.JsonIgnore; import kz.bsbnb.usci.eav.model.meta.*; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.model.persistence.Persistable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import static kz.bsbnb.usci.model.Constants.NBK_AS_RESPONDENT_ID; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ public class BaseEntity extends Persistable implements BaseContainer, Cloneable { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory.getLogger(BaseEntity.class); private UUID uuid = UUID.randomUUID(); private MetaClass metaClass; private LocalDate reportDate; private LocalDate oldReportDate; private LocalDateTime batchReceiptDate; private Long respondentId; private Long batchId; private Long productId; private OperType operation; private String oldEntityKey; private Map<String, BaseValue> values = new HashMap<>(); private Boolean mock = Boolean.FALSE; private Long userId; private BaseEntityInfo info; private Long index; private Set<String> received = new HashSet<>(); private Set<String> validationErrors = new HashSet<>(); private boolean keyElementsInstalled = false; private boolean maintenance = false; private boolean approved = false; private Long eavXmlId; @JsonIgnore private final List<BaseEntity> keyElements = new ArrayList<>(); public BaseEntity() { /*Пустой конструктор*/ } public BaseEntity(MetaClass metaClass) { this.metaClass = metaClass; } public BaseEntity(MetaClass metaClass, LocalDate reportDate) { this.metaClass = metaClass; this.reportDate = reportDate; this.respondentId = NBK_AS_RESPONDENT_ID; } public BaseEntity(MetaClass metaClass, LocalDate reportDate, Long respondentId) { this.metaClass = metaClass; this.reportDate = reportDate; this.respondentId = respondentId; } public BaseEntity(Long id, MetaClass metaClass, Long respondentId) { super(id); this.metaClass = metaClass; this.respondentId = respondentId; } public BaseEntity(Long id, MetaClass metaClass, Long respondentId, LocalDate reportDate) { super(id); this.metaClass = metaClass; this.reportDate = reportDate; this.respondentId = respondentId; } public BaseEntity(Long id, MetaClass metaClass, Long respondentId, LocalDate reportDate, Long batchId) { super(id); this.metaClass = metaClass; this.reportDate = reportDate; this.respondentId = respondentId; this.batchId = batchId; } public BaseEntity(MetaClass metaClass, Long respondentId, LocalDate reportDate, Long batchId) { this.metaClass = metaClass; this.reportDate = reportDate; this.respondentId = respondentId; this.batchId = batchId; } public BaseEntity(MetaClass metaClass, Long respondentId, LocalDate reportDate, Long batchId, LocalDateTime batchReceiptDate) { this.metaClass = metaClass; this.reportDate = reportDate; this.respondentId = respondentId; this.batchId = batchId; this.batchReceiptDate = batchReceiptDate; } public BaseEntity(BaseEntity baseEntity) { this.id = baseEntity.getId(); this.metaClass = baseEntity.getMetaClass(); this.respondentId = baseEntity.getRespondentId(); this.reportDate = baseEntity.getReportDate(); this.batchId = baseEntity.getBatchId(); this.operation = baseEntity.getOperation(); this.info = baseEntity.getInfo(); this.approved = baseEntity.isApproved(); this.maintenance = baseEntity.isMaintenance(); this.batchReceiptDate = baseEntity.getBatchReceiptDate(); this.productId = baseEntity.getProductId(); } public BaseEntity(BaseEntity baseEntity, LocalDate reportDate) { this.id = baseEntity.getId(); this.metaClass = baseEntity.getMetaClass(); this.respondentId = baseEntity.getRespondentId(); this.reportDate = reportDate; this.maintenance = baseEntity.isMaintenance(); } public boolean isClosed() { return operation == OperType.CLOSE; } public LocalDate getReportDate() { return reportDate; } public void setReportDate(LocalDate reportDate) { this.reportDate = reportDate; } public LocalDate getOldReportDate() { return oldReportDate; } public void setOldReportDate(LocalDate oldReportDate) { this.oldReportDate = oldReportDate; } public LocalDateTime getBatchReceiptDate() { return batchReceiptDate; } public void setBatchReceiptDate(LocalDateTime batchReceiptDate) { this.batchReceiptDate = batchReceiptDate; } public OperType getOperation() { return operation; } public void setOperation(OperType operation) { this.operation = operation; } public MetaClass getMetaClass() { return metaClass; } public void setMetaClass(MetaClass metaClass) { this.metaClass = metaClass; } public void addValidationError(String errorMsg) { validationErrors.add(errorMsg); } public void clearValidationErrors() { validationErrors.clear(); } public Set<String> getValidationErrors() { return validationErrors; } public UUID getUuid() { return uuid; } public Boolean getMock() { return mock; } public void setMock(Boolean mock) { this.mock = mock; } public void put(final String attribute, BaseValue baseValue) { MetaAttribute metaAttribute = metaClass.getMetaAttribute(attribute); MetaType metaType = metaAttribute.getMetaType(); if (metaType == null) throw new IllegalArgumentException(String.format("Тип %s , не найден в классе: %s", attribute, metaClass.getClassName())); if (baseValue == null) throw new IllegalArgumentException("Значение не может быть пустым"); // пустые теги <tag/> и null значения не проверяем if (baseValue.getValue() != null) { Class<?> valueClass = baseValue.getValue().getClass(); Class<?> expValueClass; if (baseValue.getValue() != null) { if (metaType.isComplex()) if (metaType.isSet()) expValueClass = BaseSet.class; else expValueClass = BaseEntity.class; else { if (metaType.isSet()) { expValueClass = BaseSet.class; valueClass = baseValue.getValue().getClass(); } else { MetaValue metaValue = (MetaValue) metaType; expValueClass = metaValue.getMetaDataType().getDataTypeClass(); } } if (expValueClass == null || !expValueClass.isAssignableFrom(valueClass)) throw new IllegalArgumentException(String.format("Несоответствие типов в классе: %s . Нужный %s , получен: %s", metaClass.getClassName(), expValueClass, valueClass)); } } baseValue.setMetaAttribute(metaAttribute); values.put(attribute, baseValue); } public void setParentInfo(BaseEntity parentEntity, MetaAttribute metaAttribute) { if (info == null) info = new BaseEntityInfo(); info.setParent(parentEntity); info.setAttribute(metaAttribute); } public BaseValue getBaseValue(String attribute) { if (attribute.contains(".")) { int index = attribute.indexOf("."); String parentAttribute = attribute.substring(0, index); String childAttribute = attribute.substring(index, attribute.length() - 1); MetaType metaType = metaClass.getMetaAttribute(parentAttribute).getMetaType(); if (metaType == null) throw new IllegalArgumentException(String.format("Мета класс %s не содержит атрибут %s", metaClass.getClassName(), parentAttribute)); if (metaType.isComplex() && !metaType.isSet()) { BaseValue baseValue = values.get(parentAttribute); if (baseValue == null) return null; BaseEntity baseEntity = (BaseEntity) baseValue.getValue(); if (baseEntity == null) return null; else return baseEntity.getBaseValue(childAttribute); } else { return null; } } else { MetaType metaType = metaClass.getMetaAttribute(attribute).getMetaType(); if (metaType == null) throw new IllegalArgumentException(String.format("Мета класс %s не содержит атрибут %s", metaClass.getClassName(), attribute)); return values.get(attribute); } } public Object getEl(String path) { if (path.equals("ROOT")) return getId(); StringTokenizer tokenizer = new StringTokenizer(path, "."); BaseEntity entity = this; MetaClass theMeta = metaClass; Object valueOut = null; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); String arrayIndexes = null; if (token.contains("[")) { arrayIndexes = token.substring(token.indexOf("[") + 1, token.length() - 1); token = token.substring(0, token.indexOf("[")); } MetaAttribute attribute = theMeta.getMetaAttribute(token); MetaType type = null; try { type = attribute.getMetaType(); } catch (Exception e) { e.printStackTrace(); } if (entity == null) return null; BaseValue value = entity.getBaseValue(token); if (value == null || value.getValue() == null) { valueOut = null; break; } valueOut = value.getValue(); if (type == null) throw new IllegalStateException("MetaType не может быть null"); if (type.isSet()) { if (arrayIndexes != null) { valueOut = ((BaseSet) valueOut).getEl(arrayIndexes.replaceAll("->", ".")); type = ((MetaSet) type).getMetaType(); } else { return valueOut; } } if (type.isComplex()) { entity = (BaseEntity) valueOut; theMeta = (MetaClass) type; } else { if (tokenizer.hasMoreTokens()) { throw new IllegalArgumentException("Путь не может иметь промежуточные простые значения"); } } } return valueOut; } public Object getEls(String path) { Queue<Object> queue = new LinkedList<>(); StringBuilder str = new StringBuilder(); String[] operations = new String[500]; boolean[] isFilter = new boolean[500]; String function = null; if (!path.startsWith("{")) throw new RuntimeException("Функция должна быть указана"); for (int i = 0; i < path.length(); i++) { if (path.charAt(i) == '}') { function = path.substring(1, i); path = path.substring(i + 1); break; } } if (function == null) throw new RuntimeException("Нет функций"); Set<Object> allowedSet = new TreeSet<>(); if (function.startsWith("set")) { String[] elems = function.substring(function.indexOf('(') + 1, function.indexOf(')')).split(","); if (function.startsWith("setInt")) { allowedSet = new TreeSet<>(); for (String e : elems) allowedSet.add(Integer.parseInt(e.trim())); } else if (function.startsWith("setLong")) { allowedSet = new TreeSet<>(); for (String e : elems) allowedSet.add(Long.parseLong(e.trim())); } else if (function.startsWith("setString")) { allowedSet = new TreeSet<>(); for (String e : elems) allowedSet.add(e.trim()); } } if (function.startsWith("hasDuplicates")) { String pattern = "hasDuplicates\\((\\S+)\\)"; Matcher m = Pattern.compile(pattern).matcher(function); String downPath; boolean ret = false; if (m.find()) { downPath = m.group(1); } else { throw new RuntimeException("Функциональные дубликаты не правильные: пример {hasDuplicates(subjects)}ref_doc_type.code,date"); } LinkedList list = (LinkedList) getEls("{get}" + downPath); String[] fields = path.split(","); Set<Object> controlSet; if (fields.length == 1) controlSet = new HashSet<>(); else if (fields.length == 2) controlSet = new HashSet<>(); else throw new RuntimeException("Бизнес правила пока не реализована"); for (Object o : list) { BaseEntity entity = (BaseEntity) o; Object entry; if (fields.length == 1) entry = entity.getEl(fields[0]); else { // fields.length == 2 entry = new AbstractMap.SimpleEntry<>(entity.getEl(fields[0]), entity.getEl(fields[1])); } if (controlSet.contains(entry)) { ret = true; } else { controlSet.add(entry); } } return ret; } int yk = 0; int open = 0; int eqCnt = 0; for (int i = 0; i <= path.length(); i++) { if (i == path.length()) { if (open != 0) throw new RuntimeException("Не правильная открывающая скобка"); break; } if (path.charAt(i) == '=') eqCnt++; if (path.charAt(i) == '!' && (i + 1 == path.length() || path.charAt(i + 1) != '=')) throw new RuntimeException("Нет знака равенства\\Знак равенства должна присутствовать после '!'"); if (path.charAt(i) == '[') open++; if (path.charAt(i) == ']') { open--; if (eqCnt != 1) throw new RuntimeException("Не правильный знак равенства\\Только один знак равенства в фильтре и только в фильтр"); eqCnt = 0; } if (open < 0 || open > 1) throw new RuntimeException("Не правильные скобки"); } for (int i = 0; i <= path.length(); i++) { if (i == path.length()) { if (str.length() > 0) { String[] arr = str.toString().split("\\."); for (String anArr : arr) { operations[yk] = anArr; isFilter[yk] = false; yk++; } } break; } char c = path.charAt(i); if (c == '[' || c == ']') { if (str.length() > 0) { if (c == ']') { operations[yk] = str.toString(); isFilter[yk] = true; yk++; } else { String[] arr = str.toString().split("\\."); for (String anArr : arr) { operations[yk] = anArr; isFilter[yk] = false; yk++; } } str.setLength(0); } } else { str.append(c); } } List<Object> ret = new LinkedList<>(); queue.add(this); queue.add(0); int retCount = 0; while (queue.size() > 0) { Object curO = queue.poll(); int step = (Integer) queue.poll(); if (curO == null) continue; if (step == yk) { if (function.startsWith("count")) { retCount++; } else if (function.startsWith("set")) if (allowedSet.contains(curO)) retCount++; ret.add(curO); continue; } //noinspection ConstantConditions BaseEntity curBE = (BaseEntity) curO; MetaClass curMeta = curBE.getMetaClass(); if (!isFilter[step]) { MetaAttribute nextAttribute = curMeta.getMetaAttribute(operations[step]); if (!nextAttribute.getMetaType().isComplex()) { // transition to BASIC type queue.add(curBE.getEl(operations[step])); queue.add(step + 1); } else if (nextAttribute.getMetaType().isSet()) { //transition to array BaseSet next = (BaseSet) curBE.getEl(operations[step]); if (next != null) { for (Object o : next.getValues()) { { queue.add(((BaseValue) o).getValue()); queue.add(step + 1); } } } } else { //transition to simple BaseEntity next = (BaseEntity) curBE.getEl(operations[step]); queue.add(next); queue.add(step + 1); } } else { String[] parts; boolean inv = false; if (operations[step].contains("!")) { parts = operations[step].split("!="); inv = true; } else parts = operations[step].split("="); Object o = curBE.getEl(parts[0]); boolean expr = (o == null && parts[1].equals("null")) || (o != null && o.toString().equals(parts[1])); if (inv) expr = !expr; if (expr) { queue.add(curO); queue.add(step + 1); } } } if (function.startsWith("get")) return ret; return retCount; } boolean equalsToString(HashMap<String, String> params) { for (String fieldName : params.keySet()) { String ownFieldName; String innerPath = null; if (fieldName.contains(".")) { ownFieldName = fieldName.substring(0, fieldName.indexOf(".")); innerPath = fieldName.substring(fieldName.indexOf(".") + 1); } else { ownFieldName = fieldName; } MetaType metaType = metaClass.getAttributeType(ownFieldName); if (metaType == null) throw new IllegalArgumentException(String.format("Нет такого поля: %s", fieldName)); if (metaType.isSet()) throw new IllegalArgumentException(String.format("Не можете работать с массивами %s", fieldName)); BaseValue baseValue = getBaseValue(ownFieldName); if (metaType.isComplex()) { baseValue = ((BaseEntity) (baseValue.getValue())).getBaseValue(innerPath); metaType = ((MetaClass) metaType).getAttributeType(innerPath); } if (!baseValue.equalsToString(params.get(fieldName), ((MetaValue) metaType).getMetaDataType())) return false; } return true; } public List<BaseEntity> getKeyElements() { if (!keyElementsInstalled) { boolean containsComplexKey = metaClass.getAttributes().stream() .anyMatch(metaAttribute -> metaAttribute.getMetaType().isComplex() && metaAttribute.isKey() && !metaAttribute.isReference()); if (!containsComplexKey && metaClass.isSearchable()) keyElements.add(this); for (String name : metaClass.getAttributeNames()) { MetaAttribute metaAttribute = metaClass.getMetaAttribute(name); MetaType metaType = metaAttribute.getMetaType(); if (metaAttribute.isReference()) continue; if (metaType.isComplex()) { BaseValue baseValue = getBaseValue(name); if (baseValue == null || baseValue.getValue() == null) continue; if (!metaType.isSet()) { keyElements.addAll(((BaseEntity) baseValue.getValue()).getKeyElements()); } else { BaseSet baseSet = (BaseSet) baseValue.getValue(); for (BaseValue childBaseValue : baseSet.getValues()) keyElements.addAll(((BaseEntity) childBaseValue.getValue()).getKeyElements()); } } } keyElementsInstalled = true; } return keyElements; } // метод предназначен для сверки двух сущностей по ключевым полям (все значения ключей должны совпадать) // сверка сетов в качестве ключей не предусмотрена // сущности должны быть одного мета класса и респондента public boolean equalsByKey(BaseEntity baseEntity) { if (this == baseEntity) return true; if (baseEntity == null || getClass() != baseEntity.getClass()) return false; if (!this.getMetaClass().equals(baseEntity.getMetaClass())) return false; if (!this.respondentId.equals(baseEntity.getRespondentId())) return false; for (String name : this.metaClass.getAttributeNames()) { MetaAttribute metaAttribute = this.metaClass.getMetaAttribute(name); MetaType metaType = metaAttribute.getMetaType(); if (metaAttribute.isKey()) { BaseValue thisBaseValue = this.getBaseValue(name); BaseValue thatBaseValue = baseEntity.getBaseValue(name); if (metaType.isComplex()) { if (metaType.isSet()) { BaseSet thisBaseSet = (BaseSet)thisBaseValue.getValue(); BaseSet thatBaseSet = (BaseSet)thatBaseValue.getValue(); /* if (thisBaseSet.getValueCount() != thatBaseSet.getValueCount()) return false;*/ boolean result = false; for (BaseValue childThisBaseValue : thisBaseSet.getValues()) { result = thatBaseSet.getValues().stream() .anyMatch(baseValue -> ((BaseEntity) baseValue.getValue()).equalsByKey((BaseEntity) childThisBaseValue.getValue())); } return result; } else { try { if (!((BaseEntity) thisBaseValue.getValue()).equalsByKey((BaseEntity) thatBaseValue.getValue())) return false; } catch (NullPointerException ex) { logger.debug("NullPointerException baseEntityId=" + baseEntity.getId() + " , batchId=" + baseEntity.getBatchId() + ", attributeName=" + name); return false; } } } else { try { if (!thisBaseValue.getValue().equals(thatBaseValue.getValue())) return false; } catch (NullPointerException ex) { throw new UsciException("NullPointerException baseEntityId=" + baseEntity.getId() + " , batchId=" + baseEntity.getBatchId() + ", attributeName=" + name); } } } if (metaAttribute.isNullableKey()) { if (!metaType.isComplex()) { BaseValue thisBaseValue = this.getBaseValue(name); BaseValue thatBaseValue = baseEntity.getBaseValue(name); if ((thisBaseValue == null && thatBaseValue != null) || (thisBaseValue != null && thatBaseValue == null)) return false; if (thisBaseValue != null && thatBaseValue != null) { if ((thisBaseValue.getValue() == null && thatBaseValue.getValue() != null) || (thisBaseValue.getValue() != null && thatBaseValue.getValue() == null)) return false; if (thisBaseValue.getValue() != null && thatBaseValue.getValue() != null) if (!thisBaseValue.getValue().equals(thatBaseValue.getValue())) return false; } } else throw new IllegalStateException("isComplex isNullableKey not supported"); } } if (this.parentIsKey()) { if ((this.getInfo() != null && baseEntity.getInfo() == null) || (this.getInfo() == null && baseEntity.getInfo() != null)) return false; return this.getInfo() == null || this.getInfo().equals(baseEntity.getInfo()); } return true; } @Override public Collection<BaseValue> getValues() { return values.values(); } // проверяет на соответсвие атрибутов @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; BaseEntity that = (BaseEntity) obj; if (!this.getMetaClass().getId().equals(that.getMetaClass().getId())) return false; int thisValueCount = this.getValueCount(); int thatValueCount = that.getValueCount(); if (thisValueCount != thatValueCount) return false; for (String attributeName : metaClass.getAttributeNames()) { MetaAttribute metaAttribute = metaClass.getMetaAttribute(attributeName); MetaType metaType = metaAttribute.getMetaType(); BaseValue thisBaseValue = this.getBaseValue(attributeName); BaseValue thatBaseValue = that.getBaseValue(attributeName); if (thisBaseValue == null && thatBaseValue == null) continue; if (thisBaseValue == null || thatBaseValue == null) return false; if (metaType.isSet()) { BaseSet thisBaseSet = (BaseSet) thisBaseValue.getValue(); BaseSet thatBaseSet = (BaseSet) thatBaseValue.getValue(); if (thisBaseSet == null && thatBaseSet == null) continue; if (thisBaseSet == null || thatBaseSet == null) return false; if (thisBaseSet.getValueCount() != thatBaseSet.getValueCount()) return false; for (BaseValue thisChildBaseValue : thisBaseSet.getValues()) { Object thisChildValue = thisChildBaseValue.getValue(); boolean childValueFound = false; for (BaseValue thatChildBaseValue : thatBaseSet.getValues()) { Object thatChildValue = thatChildBaseValue.getValue(); if (metaType.isComplex() && metaAttribute.isReference()) { try { if (!((BaseEntity) thisChildValue).getId().equals(((BaseEntity) thatChildValue).getId())) return false; } catch (NullPointerException ex) { logger.debug("NullPointerException baseEntityId=" + that.getId() + " , batchId=" + that.getBatchId() + ", attributeName=" + attributeName); return false; } continue; } if (thisChildValue.equals(thatChildValue)) childValueFound = true; } if (!childValueFound) return false; } } else { Object thisValue = thisBaseValue.getValue(); Object thatValue = thatBaseValue.getValue(); if (thisValue == null && thatValue == null) continue; if (thisValue == null || thatValue == null) return false; if (metaType.isComplex() && metaAttribute.isReference()) { if (!((BaseEntity) thisValue).getId().equals(((BaseEntity) thatValue).getId())) return false; continue; } if (!thisValue.equals(thatValue)) return false; // Проверка на изменение ключевых полей if (!metaType.isComplex() && (thisBaseValue.getNewBaseValue() != null || thatBaseValue.getNewBaseValue() != null)) return false; } } return true; } @Override public String toString() { return BaseEntityOutput.toString(this, true); } @Override public int hashCode() { int result = super.hashCode(); result += 31 * result + metaClass.hashCode(); result += 31 * result + (int) (respondentId ^ (respondentId >>> 32)); result += 31 * result + values.hashCode(); return result; } @Override public BaseEntity clone() { BaseEntity baseEntityCloned; try { baseEntityCloned = (BaseEntity) super.clone(); Map<String, BaseValue> valuesCloned = new HashMap<>(); for (String attribute : values.keySet()) { BaseValue baseValue = values.get(attribute); BaseValue baseValueCloned = baseValue.clone(); baseValueCloned.setMetaAttribute(getMetaAttribute(attribute)); valuesCloned.put(attribute, baseValueCloned); } baseEntityCloned.values = valuesCloned; } catch (CloneNotSupportedException ex) { throw new RuntimeException("BaseEntity класс не реализует интерфейс Cloneable"); } return baseEntityCloned; } @Override public MetaClass getMetaType() { return metaClass; } public MetaType getAttributeType(String attribute) { if (attribute.contains(".")) { int index = attribute.indexOf("."); String parentIdentifier = attribute.substring(0, index); MetaType metaType = metaClass.getAttributeType(parentIdentifier); if (metaType.isComplex() && !metaType.isSet()) { MetaClass childMeta = (MetaClass) metaType; String childIdentifier = attribute.substring(index, attribute.length() - 1); return childMeta.getAttributeType(childIdentifier); } else { return null; } } else { return metaClass.getAttributeType(attribute); } } public MetaAttribute getMetaAttribute(String attribute) { return metaClass.getMetaAttribute(attribute); } public Long getRespondentId() { return respondentId; } public void setRespondentId(Long respondentId) { this.respondentId = respondentId; } public String getOldEntityKey() { return oldEntityKey; } public void setOldEntityKey(String oldEntityKey) { this.oldEntityKey = oldEntityKey; } public Long getBatchId() { return batchId; } public void setBatchId(Long batchId) { this.batchId = batchId; } public Long getBatchIndex() { return index; } public void setBatchIndex(Long index) { this.index = index; } public Set<String> getReceived() { return received; } public void setReceived(Set<String> received) { this.received = received; } public Set<String> getAttributeNames() { return values.keySet(); } public Stream<MetaAttribute> getAttributes() { return values.keySet().stream().map(metaClass::getMetaAttribute); } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public BaseEntityInfo getInfo() { return info; } public void setInfo(BaseEntityInfo info) { this.info = info; } public BaseEntity getParentEntity() { return parentIsKey()? info.getParent(): null; } /** * Метод добавлен так как из BRMS идет вызов getCreditorId по старой логике */ public Long getCreditorId() { return respondentId; } @Override public boolean isSet() { return false; } @Override public boolean isComplex() { return true; } public boolean parentIsKey() { return info != null && info.getAttribute() != null && info.getAttribute().isParentIsKey(); } @Override public int getValueCount() { return values.size(); } public boolean isMaintenance() { return maintenance; } public void setMaintenance(boolean maintenance) { this.maintenance = maintenance; } public boolean isApproved() { return approved; } public void setApproved(boolean approved) { this.approved = approved; } public Long getEavXmlId() { return eavXmlId; } public void setEavXmlId(Long eavXmlId) { this.eavXmlId = eavXmlId; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } } <file_sep>package kz.bsbnb.usci.model.respondent; /** * @author <NAME> */ public class ConfirmMsgFileJson { private Long id; private Long messageId; private String fileName; private byte[] content; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getMessageId() { return messageId; } public void setMessageId(Long messageId) { this.messageId = messageId; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } } <file_sep>package kz.bsbnb.usci.eav.dao; import kz.bsbnb.usci.eav.model.core.BaseEntityStatus; import kz.bsbnb.usci.eav.model.core.EntityStatusType; import java.util.List; public interface BaseEntityStatusDao { BaseEntityStatus insert(BaseEntityStatus baseEntityStatus); BaseEntityStatus insertBatchMethod(BaseEntityStatus baseEntityStatus); void update(BaseEntityStatus baseEntityStatus); Object[] getStatusList(Long batchId, List<EntityStatusType> statuses); int getErrorEntityCount(long batchId); int getSuccessEntityCount(long batchId); } <file_sep>package kz.bsbnb.usci.receiver.batch.service.impl; import kz.bsbnb.usci.core.client.RespondentClient; import kz.bsbnb.usci.eav.client.ProductClient; import kz.bsbnb.usci.eav.dao.BaseEntityStatusDao; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.receiver.batch.service.BatchService; import kz.bsbnb.usci.receiver.dao.BatchDao; import kz.bsbnb.usci.receiver.dao.BatchStatusDao; import kz.bsbnb.usci.receiver.model.Batch; import kz.bsbnb.usci.receiver.model.BatchStatus; import kz.bsbnb.usci.receiver.model.BatchStatusType; import kz.bsbnb.usci.receiver.model.BatchType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.DigestUtils; import org.springframework.util.FileCopyUtils; import java.io.File; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; /** * @author <NAME> * @author <NAME> * @author <NAME> */ @Service public class BatchServiceImpl implements BatchService { private static final Logger logger = LoggerFactory.getLogger(BatchServiceImpl.class); private static final DateTimeFormatter DATE_FORMAT_BATCH = DateTimeFormatter.ofPattern("dd.MM.yyyy"); private final BatchDao batchDao; private final BatchStatusDao batchStatusDao; private final RespondentClient respondentClient; private final BaseEntityStatusDao baseEntityStatusDao; private final ProductClient productClient; @Value("${batch.save.dir}") private String batchSaveDir = ""; public BatchServiceImpl(BatchDao batchDao, BatchStatusDao batchStatusDao, RespondentClient respondentClient, BaseEntityStatusDao baseEntityStatusDao, ProductClient productClient) { this.batchDao = batchDao; this.batchStatusDao = batchStatusDao; this.respondentClient = respondentClient; this.baseEntityStatusDao = baseEntityStatusDao; this.productClient = productClient; } @Override public Long save(Batch batch) { return batchDao.save(batch); } @Override public Batch getBatch(long batchId) { Batch batch = batchDao.load(batchId); // batchDao подгружает только id продукта, посему подгрузим сам продукт полностью if (batch.getProduct() != null) batch.setProduct(productClient.getProductById(batch.getProduct().getId())); if (batch.getRespondentId() != null) batch.setRespondent(respondentClient.getRespondentById(batch.getRespondentId())); // если файл не удалось распарсить и вытянуть параметры небходимые для его сохранения на файловом сервере // значит его не сможем достать if (batch.getReportDate() == null || batch.getRespondentId() == null || batch.getHash() == null) { return batch; } //замечание!!! каталог где расположены батчи формируем программно //то есть batch.getFileName это путь где он расположен изначально когда загружался File file = new File(getFullFilePath(batch)); try { byte[] bytes = FileCopyUtils.copyToByteArray(file); batch.setContent(bytes); } catch (IOException e) { throw new UsciException(e); } return batch; } @Override public Batch uploadBatch(Batch batch) { batch.setHash(DigestUtils.md5DigestAsHex(batch.getContent())); saveBatchFile(batch); batchDao.save(batch); return batch; } private void saveBatchFile(Batch batch) { // создаем директорию для файла в формате кредитор->отчетная дата File repDateDir = new File(getRespondentDirPath(batch)); if (!repDateDir.exists()) { repDateDir.mkdirs(); } File outputFile = new File(getFullFilePath(batch)); try { if (!outputFile.exists()) { outputFile.createNewFile(); } // копируем непосредственно сам батч в файл FileCopyUtils.copy(batch.getContent(), outputFile); } catch (IOException e) { logger.error("Ошибка создания файла батча на сервере", e); throw new UsciException(e); } } private String getFullFilePath(Batch batch) { if (batch.getReportDate() == null || batch.getRespondentId() == null || batch.getHash() == null) throw new UsciException("RepDate, respondentId и хэш необходимы для пути к файлу"); return batchSaveDir + "/" + batch.getReportDate().format(DATE_FORMAT_BATCH) + "/" + batch.getRespondentId() + "/" + batch.getHash() + ".zip"; } private String getRespondentDirPath(Batch batch) { if (batch.getReportDate() == null || batch.getRespondentId() == null) throw new UsciException("RepDate, respondentId и хэш необходимы для пути к файлу"); return batchSaveDir + "/" + batch.getReportDate().format(DATE_FORMAT_BATCH) + "/" + batch.getRespondentId(); } @Override @Transactional public void addBatchStatus(BatchStatus batchStatus) { // обновляю статус батча batchDao.updateBatchStatus(batchStatus.getBatchId(), batchStatus.getStatus()); batchStatusDao.insert(batchStatus); } /** * вызывается из SYNC чтобы завершить загрузку батча, * также вызывается из receiver если есть ошибки во время парсинга * удаляет файл из каталога батчей после полной загрузки батча */ @Override public void endBatch(long batchId) { List<BatchStatus> batchStatusList = batchStatusDao.getList(batchId); boolean hasError = false; for (BatchStatus batchStatus : batchStatusList) { if (BatchStatusType.ERROR.equals(batchStatus.getStatus())) { hasError = true; break; } } Batch batch = getBatch(batchId); if ((!hasError && !batch.isMaintenance() )|| (batch.isMaintenance() && batch.isMaintenanceApproved())) { addBatchStatus(new BatchStatus(batchId, BatchStatusType.COMPLETED)); } if (!hasError && batch.isMaintenance() && !batch.isMaintenanceApproved()) { addBatchStatus(new BatchStatus(batchId, BatchStatusType.MAINTENANCE_REQUEST)); batch.setBatchType(BatchType.MAINTENANCE); save(batch); } else { try { if (batch.getFilePath() != null) { File file = new File(batch.getFilePath()); if (file.exists()) if (!file.delete()) logger.error("Не удалось удалить файл после завершения " + batch.getFilePath()); } } catch (Exception e) { throw new UsciException("Не удалось удалить файл после завершения " + batch.getFilePath(), e); } } } @Override public List<Batch> getPendingBatchList() { return batchDao.getPendingBatchList(); } @Override public void approveMaintenanceBatchList(List<Long> batchIds) { batchDao.approveMaintenanceBatchList(batchIds); } @Override public void declineMaintenanceBatchList(List<Long> batchIds) { batchDao.declineMaintenanceBatchList(batchIds); } @Override public List<BatchStatus> getBatchStatusList(List<Long> batchIds) { return batchStatusDao.getList(batchIds); } @Override public void cancelBatch(long batchId) { addBatchStatus(new BatchStatus(batchId, BatchStatusType.CANCELLED)); } @Override public void signBatch(long batchId, String sign, String signInfo, LocalDateTime signTime) { Batch batch = batchDao.load(batchId); batch.setSignature(sign); batch.setSignInfo(signInfo); batch.setSignTime(signTime); batchDao.save(batch); } @Override public boolean clearActualCount(long batchId) { try { batchDao.clearActualCount(batchId); return true; } catch (Exception e) { return false; } } @Override @Transactional public boolean incrementActualCounts(Map<Long, Long> batchesToUpdate) { try { for (Long batchId : batchesToUpdate.keySet()) { batchDao.incrementActualCount(batchId, batchesToUpdate.get(batchId)); } } catch (Exception e) { logger.error(e.getMessage()); return false; } return true; } @Override public void setBatchTotalCount(long batchId, long totalCount) { batchDao.setBatchTotalCount(batchId, totalCount); } @Override public int getErrorEntitiesCount(Long batchId) { return baseEntityStatusDao.getErrorEntityCount(batchId); } @Override public int getSuccessEntitiesCount(Long batchId) { return baseEntityStatusDao.getSuccessEntityCount(batchId); } } <file_sep>var label_ERROR = 'Ошибка'; var label_RETURN = 'Вернуться к списку отчетов'; var label_FILTER = 'Добавить фильтр'; var label_CHOSEN = 'Выбран отчет "'; var label_PARAMETRS = '". Заполните входные параметры.'; var label_REPORT = 'Выгрузить отчет в XLS'; var label_TABLE = 'Загрузить таблицу отчета'; var label_REPORTING = 'Идет формирования отчета...'; var label_REP_NAME = 'Название отчета'; var LABEL_USER = 'Пользовтель'; var label_BEG_TIME = 'Время начало'; var label_END_TIME = 'Время завершения'; var label_COMMENT = 'Комментарий'; var label_REFRESH = 'Обновить'; var label_OUTPUT = 'Выходные формы'; var label_SPISOK = 'Список отчетов'; var label_FINISHED = 'Сформированнные отчеты'; var label_FILES = 'Файлы'; var label_FILE_NAME = 'Название файла'; var label_DOWNLOAD = 'Загрузить'; var label_WAIT = 'Подождите...'; <file_sep>package kz.bsbnb.usci.core.dao; import kz.bsbnb.usci.model.adm.Position; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.util.*; /** * @author <NAME> */ @Repository public class PositionDaoImpl implements PositionDao { private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; private final SimpleJdbcInsert positionUserInsert; public PositionDaoImpl(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) { this.jdbcTemplate = jdbcTemplate; this.npJdbcTemplate = npJdbcTemplate; this.positionUserInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_ADM") .withTableName("USER_PROD_POS") .usingColumns("USER_ID", "PRODUCT_ID", "POS_ID") .usingGeneratedKeyColumns("ID"); } @Override public List<Position> getUserPosList() { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from USCI_ADM.REF_POS"); List<Position> userPos = new ArrayList<>(); for (Map<String, Object> row : rows) userPos.add(getPosFromJdbcMap(row)); return userPos; } @Override public List<Position> getUserPosListByProductId(Long userId, Long productId) { String query = "select t.* from USCI_ADM.REF_POS t, USCI_ADM.USER_PROD_POS ps \n" + " where ps.user_id = :userId \n" + " and ps.product_id = :productId \n" + " and ps.pos_id = t.id"; MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("userId", userId); params.addValue("productId", productId); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); if (rows.size() < 1) return Collections.emptyList(); List<Position> userPos = new ArrayList<>(); for (Map<String, Object> row : rows) userPos.add(getPosFromJdbcMap(row)); return userPos; } @Override public Position getUserPosById(Long id) { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from USCI_ADM.REF_POS where ID = ?", new Object[]{id}); if (rows.size() != 1) throw new UsciException("Ошибка нахождения записи в таблице USCI_ADM.REF_POS"); return getPosFromJdbcMap(rows.get(0)); } @Override public void addUserPosition(Long userId, Long productId, List<Long> positionIds) { List<MapSqlParameterSource> params = new ArrayList<>(); for (Long positionId : positionIds) { params.add(new MapSqlParameterSource("USER_ID", userId) .addValue("PRODUCT_ID", productId) .addValue("POS_ID", positionId)); } if (positionIds.size() > 1) { int counts[] = positionUserInsert.executeBatch(params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException("Ошибка insert записей в таблицу USCI_ADM.USER_PROD_POS"); } else { int count = positionUserInsert.execute(params.get(0)); if (count != 1) throw new UsciException("Ошибка insert записей в таблицу USCI_ADM.USER_PROD_POS"); } } @Override public void delUserPosition(Long userId, Long productId, List<Long> positionIds) { List<MapSqlParameterSource> params = new ArrayList<>(); for (Long positionId : positionIds) { params.add(new MapSqlParameterSource("userId", userId) .addValue("productId", productId) .addValue("positionId", positionId)); } String delete = "delete from USCI_ADM.USER_PROD_POS \n" + " where USER_ID = :userId \n" + " and PRODUCT_ID = :productId \n" + " and POS_ID = :positionId"; if (positionIds.size() > 1) { int counts[] = npJdbcTemplate.batchUpdate(delete, params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException("Ошибка delete записей из таблицы USCI_ADM.USER_PROD_POS"); } else { int count = npJdbcTemplate.update(delete, params.get(0)); if (count != 1) throw new UsciException("Ошибка delete записей из таблицы USCI_ADM.USER_PROD_POS"); } } private static Position getPosFromJdbcMap(Map<String, Object> row) { Position position = new Position(); position.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); position.setNameRu(SqlJdbcConverter.convertObjectToString(row.get("NAME_RU"))); position.setNameKz(SqlJdbcConverter.convertObjectToString(row.get("NAME_KZ"))); position.setLevel(SqlJdbcConverter.convertToLong(row.get("LEVEL_"))); return position; } } <file_sep>package kz.bsbnb.usci.model.respondent; import kz.bsbnb.usci.model.persistence.Persistable; /** * @author <NAME> */ public class ConfirmMessageFile extends Persistable { private Long messageId; private String fileName; private byte[] content; public Long getMessageId() { return messageId; } public void setMessageId(Long messageId) { this.messageId = messageId; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } } <file_sep>/** * @author <NAME> * @author <NAME> * @author <NAME> */ function es_escape(xmlStr) { return xmlStr.replace(new RegExp('&','g'), '&amp;'); }<file_sep>package kz.bsbnb.usci.receiver.reader; import kz.bsbnb.usci.eav.client.EntityClient; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseEntityJson; import kz.bsbnb.usci.eav.model.base.OperType; import kz.bsbnb.usci.eav.model.core.BaseEntityStatus; import kz.bsbnb.usci.eav.model.core.EntityStatusType; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.eav.model.meta.json.EntityExtJsTreeJson; import kz.bsbnb.usci.eav.repository.MetaClassRepository; import kz.bsbnb.usci.eav.service.BaseEntityLoadXmlService; import kz.bsbnb.usci.receiver.batch.service.BatchService; import kz.bsbnb.usci.receiver.model.exception.ReceiverException; import kz.bsbnb.usci.receiver.validator.XsdValidator; import kz.bsbnb.usci.sync.client.SyncClient; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.configuration.annotation.StepScope; import org.springframework.batch.item.NonTransientResourceException; import org.springframework.batch.item.ParseException; import org.springframework.batch.item.UnexpectedInputException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.ByteArrayOutputStream; import java.util.*; @Component @StepScope public class MaintenanceEntityReader<T> extends AbstractReader<T>{ private static final Logger logger = LoggerFactory.getLogger(MaintenanceEntityReader.class); private List<BaseEntityJson> baseEntityJsonList = new ArrayList<>(); private Iterator<BaseEntityJson> iterator; @Autowired public MaintenanceEntityReader(BatchService batchService, SyncClient syncClient, MetaClassRepository metaClassRepository, XsdValidator xsdValidator, EntityClient entityClient, BaseEntityLoadXmlService baseEntityLoadXmlService) { this.batchService = batchService; this.syncClient = syncClient; this.metaClassRepository = metaClassRepository; this.xsdValidator = xsdValidator; this.entityClient = entityClient; this.baseEntityLoadXmlService = baseEntityLoadXmlService; } @PostConstruct @Override protected void init() { baseEntityJsonList = baseEntityLoadXmlService.loadEntityForApproval(batchId); if (baseEntityJsonList.size() == 0L) { logger.error(String.format("Нет сущности в таблице EAV_ENTITY_MAINTENANCE с batch_id = %d", batchId)); batchService.endBatch(batchId); iterator = null; } else iterator = baseEntityJsonList.iterator(); } @Override public ByteArrayOutputStream extractBatch() { return null; } @Override public T read() throws UnexpectedInputException, ParseException, NonTransientResourceException { try { if (iterator != null) { return readInner(); } else return null; } catch (Exception e) { logger.error(e.getMessage(), e); entityClient.addEntityStatus(new BaseEntityStatus(batchId, EntityStatusType.ERROR) .setErrorMessage(e.getLocalizedMessage())); return null; } } private T readInner() { waitSync(); while (iterator.hasNext()) { BaseEntityJson baseEntityJson = iterator.next(); MetaClass metaClass = metaClassRepository.getMetaClass(baseEntityJson.getMetaClassId()); EntityExtJsTreeJson entityJson = baseEntityLoadXmlService.loadBaseEntity(baseEntityJson.getId()); BaseEntity baseEntity = baseEntityLoadXmlService.getBaseEntityFromJsonTree(respondentId, baseEntityJson.getReportDate(), entityJson, metaClass, batchId); baseEntity.setOperation(baseEntityJson.getOperType()); totalCount++; return (T) baseEntity; } //saveTotalCounts(); return null; } } <file_sep>var label_ERROR = 'Ошибка'; var label_QUEUE = 'Очередь'; var label_ORGS = 'Организации'; var label_SELECT_ALL = 'Выделить все'; var label_DOWN_Q = 'Загрузить очередь'; var label_AUTO = 'Автообновление'; var label_FILES = 'Файлы'; var label_FILE_INFO = 'Информация о файлах'; var label_ORG_NAME = 'Наименование организации'; var label_FILE_NAME = 'Имя файла'; var label_PRODUCT = 'Продукт'; var label_STATUS = 'Статус'; var label_REC_TIME = 'Время получения'; var label_AMOUNT = 'Количество обработанных записей'; var label_REP_DATE = 'Дата отчета'; var label_EXCEL = 'Выгрузить в Excel'; var label_RESUME = 'Резюме'; var label_FILES_IN_Q = 'Файлов в очереди'; var label_Q_CONTROL = 'Управление очередью'; var label_SETTINGS = 'Порядок обработки'; var label_CHOOSE_P = 'Выбрать приоритетные организации'; var label_SAVE = 'Сохранить'; var label_CONFIRMED = 'Одобрено'; var label_CONFIG = 'Конфигурация Receiver обновлена'; var label_VIEW = 'Предварительный просмотр порядка обработки'; <file_sep>package kz.bsbnb.usci.model.util; import kz.bsbnb.usci.model.persistence.Persistable; /** * @author <NAME> */ public class Error extends Persistable { private static final long serialVersionUID = 1L; private String code; private String nameRu; private String descriptionRu; private String nameKz; private String descriptionKz; public Error() { super(); } public String getCode() {return code; } public void setCode(String code) {this.code = code;} public String getNameRu() {return nameRu;} public void setNameRu(String nameRu) {this.nameRu = nameRu;} public String getDescriptionRu() {return descriptionRu;} public void setDescriptionRu(String descriptionRu) {this.descriptionRu = descriptionRu;} public String getNameKz() {return nameKz;} public void setNameKz(String nameKz) {this.nameKz = nameKz;} public String getDescriptionKz() {return descriptionKz;} public void setDescriptionKz(String descriptionKz) {this.descriptionKz = descriptionKz;} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Error error = (Error) o; if (!getCode().equals(error.getCode())) return false; if (!getNameRu().equals(error.getNameRu())) return false; return getDescriptionRu().equals(error.getDescriptionRu()); } @Override public int hashCode() { int result = getCode().hashCode(); result = 31 * result + getNameRu().hashCode(); result = 31 * result + getDescriptionRu().hashCode(); return result; } @Override public String toString() { return "Error{" + "code='" + code + '\'' + ", nameRu='" + nameRu + '\'' + ", descriptionRu='" + descriptionRu + '\'' + ", nameKz='" + nameKz + '\'' + ", descriptionKz='" + descriptionKz + '\'' + '}'; } } <file_sep>package kz.bsbnb.usci.receiver.parser.impl; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseSet; import kz.bsbnb.usci.eav.model.base.BaseValue; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.receiver.parser.BatchParser; import kz.bsbnb.usci.receiver.parser.exceptions.UnknownTagException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.xml.sax.SAXException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** * @author <NAME> * @author <NAME> */ @Component @Scope("prototype") public class SubjectOrganizationHeadParser extends BatchParser { @Autowired private SubjectOrganizationHeadNamesParser subjectOrganizationHeadNamesParser; @Autowired private SubjectOrganizationHeadDocsParser subjectOrganizationHeadDocsParser; public SubjectOrganizationHeadParser() { super(); } private MetaClass personNameMeta, documentMeta; @Override public void init() { currentBaseEntity = new BaseEntity(metaClassRepository.getMetaClass("head"), respondentId, batch.getReportDate(), batch.getId()); personNameMeta = metaClassRepository.getMetaClass("person_name"); documentMeta = metaClassRepository.getMetaClass("document"); } @Override public boolean startElement(XMLEvent event, StartElement startElement, String localName) throws SAXException { switch (localName) { case "head": break; case "names": BaseSet headNames = new BaseSet(personNameMeta); while (true) { subjectOrganizationHeadNamesParser.parse(xmlReader, batch, index, respondentId); if (subjectOrganizationHeadNamesParser.hasMore()) { headNames.put(new BaseValue(subjectOrganizationHeadNamesParser.getCurrentBaseEntity())); } else break; } currentBaseEntity.put("names", new BaseValue(headNames)); break; case "docs": BaseSet docs = new BaseSet(documentMeta); while (true) { subjectOrganizationHeadDocsParser.parse(xmlReader, batch, index, respondentId); if (subjectOrganizationHeadDocsParser.hasMore()) { docs.put(new BaseValue(subjectOrganizationHeadDocsParser.getCurrentBaseEntity())); } else break; } currentBaseEntity.put("docs", new BaseValue(docs)); break; default: throw new UnknownTagException(localName); } return false; } @Override public boolean endElement(String localName) throws SAXException { switch (localName) { case "head": return true; case "names": break; case "docs": break; default: throw new UnknownTagException(localName); } return false; } } <file_sep>var label_TITLE = 'Басқару'; var label_ERROR = 'Қате'; var label_CHOOSE_PRODUCT = 'Өнімді таңдаңыз!'; var label_SETUP_USERS = 'Пайдаланушыны баптау'; var label_USERS = 'Пайдаланушылар'; var label_SYNC_USERS = 'Пайдаланушыларды синхрондау'; var label_SYNC = 'Синхрондалған'; var label_SETUP_RESP = 'Респонденттерді баптау'; var label_APPOINTED_RESP = 'Тағайындалған респонденттер'; var label_ADD = 'Қосу'; var label_IMPOSSIBLE_ADDING = 'Таңдалған пайдаланушыға бірнеше респондентерді қосу мүмкін емес!'; var label_DELETE = 'Жою'; var label_AVAILABLE_RESP = 'Қолжетімді респонденттер'; var label_SETUP_POST = 'Лауазымдарды баптау'; var label_SELECTED_PROD = 'Өнімді таңдаңыз:'; var label_CHOOSE_USER = 'Пайдаланушыны таңдаңыз!'; var label_CHOOSE_POST = 'Осы өнімге арналған лауазымдарды таңдаңыз'; var label_AVAILABLE_POST = 'Қолжетімді лауазымдар'; var label_APPOINTED_POST = 'Тағайындалған лауазым'; var label_SETUP_PRODUCTS = 'Өнімдерді баптау'; var label_AVAILABLE_PRODUCTS = 'Қолжетімді өнімдер'; var label_APPOINTED_PRODUCTS = 'Тағайындалған өнімдер'; var label_SETUP_PERIODICITY = 'Субъекттердің есепті күнінің мерзімділігін белгілеу'; var label_SUBJECTS = 'Субъекттер'; var label_PERIODICITY = 'Мерзімділік' var label_CHOOSE_SUBJECT = 'Субъекті таңдаңыз!'; var label_PERIOD = 'Мерзімділік:'; var label_SAVE = 'Сақтау'; var label_SUCCESS_UPDATE = 'Сәтті жаңартылды!'; var label_SETUP_EDS = 'ЭЦҚ баптаулар'; var label_REQUIRED_EDS = 'ЭСҚ арқылы міндетті түрде жіберуді ұйымдастырларды таңдаңыз'; var label_UPDATED = 'Жаңартылған'; <file_sep>package kz.bsbnb.usci.receiver.queue.impl; import kz.bsbnb.usci.receiver.model.Batch; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author <NAME> */ public class RespondentCycleOrder extends AbstractQueueOrder { private Map<Long, Long> respondentsTime = new HashMap<>(); private Long time = 0L; @Override public int compare(Batch batch1, Batch batch2) { return (int) (batch1.getId() - batch2.getId()); } @Override public Batch getNextBatch(List<Batch> batches) { Batch nextBatch = null; Long minTime = null; for (Batch file : batches) { if (nextBatch == null) { nextBatch = file; minTime = respondentsTime.getOrDefault(file.getRespondentId(), -1L); } else { Long respondentLastTime = respondentsTime.getOrDefault(file.getRespondentId(), -1L); if (minTime > respondentLastTime) { minTime = respondentLastTime; nextBatch = file; } } } if (nextBatch != null) respondentsTime.put(nextBatch.getRespondentId(), time++); return nextBatch; } } <file_sep>plugins { id 'java' id 'war' } group 'kz.bsbnb.usci.portlet' version '0.1.0' sourceCompatibility = 1.7 targetCompatibility = 1.7 repositories { mavenCentral() } war { baseName = 'product' version = '2.1.2' enabled = true } bootWar { enabled = false } dependencies { compile group: 'com.liferay.portal', name: 'portal-service', version:'6.1.1' compile group: 'com.liferay.portal', name: 'util-bridges', version:'6.1.1' compile group: 'com.liferay.portal', name: 'util-taglib', version:'6.1.1' compile group: 'com.liferay.portal', name: 'util-java', version:'6.1.1' compile group: 'javax.portlet', name: 'portlet-api', version:'2.0' compile group: 'javax.servlet', name: 'servlet-api', version:'2.4' compile group: 'javax.servlet.jsp', name: 'jsp-api', version:'2.0' } <file_sep>package kz.bsbnb.usci.util; import com.google.gson.Gson; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author <NAME> */ public class JsonMaker { private static Gson gson = new Gson(); public static class ExtJsJsonList { int totalCount; List<Object> data; boolean success; public ExtJsJsonList(List data) { this.data = data; totalCount = data.size(); success = true; } } public static String getJson(List data){ return gson.toJson(new ExtJsJsonList(data)); } public static String getJson(Object data){ Map m = new HashMap(); m.put("data",data); m.put("success",true); return gson.toJson(m); } public static String getJson(Map m){ m.put("success", true); return gson.toJson(m); } } <file_sep>package kz.bsbnb.usci.eav.meta.controller; import kz.bsbnb.usci.eav.model.meta.json.MetaClassJson; import kz.bsbnb.usci.eav.model.meta.json.ProductJson; import kz.bsbnb.usci.eav.service.ProductService; import kz.bsbnb.usci.model.adm.Position; import kz.bsbnb.usci.model.batch.Product; import kz.bsbnb.usci.model.json.ApproveIterationJson; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; /** * @author <NAME> */ @RestController @RequestMapping(value = "/product") public class ProductController { private final ProductService productService; public ProductController(ProductService productService) { this.productService = productService; } @GetMapping(value = "getProductList") public List<ProductJson> getProductList() { return productService.getProducts().stream() // показываем все продукты кроме справочников // .filter(product -> !product.getCode().equals("DICT")) .map(ProductController::convertProductToJson) .collect(Collectors.toList()); } @GetMapping(value = "getProducts") public List<Product> getProducts() { return productService.getProducts(); } @GetMapping(value = "getProductById") public Product getProductById(@RequestParam(name = "id") Long id) { return productService.getProductById(id); } @GetMapping(value = "getProductJsonById") public ProductJson getProductJsonById(@RequestParam(name = "id") Long id) { return convertProductToJson(productService.getProductById(id)); } @GetMapping(value = "findProductByCode") public Product findProductByCode(@RequestParam(name = "code") String code) { return productService.findProductByCode(code).orElse(null); } @PostMapping(value = "saveProduct") public void saveProduct(@RequestBody ProductJson json) { if (json.getId() == null) productService.createProduct(json); else productService.updateProduct(json); } @GetMapping(value = "getMetaClasses") public List<MetaClassJson> getMetaClasses(@RequestParam(name = "productId") Long productId, @RequestParam(name = "available") boolean available) { return productService.getMetaClasses(productId, available); } @GetMapping(value = "getPositions") public List<Position> getPositions(@RequestParam(name = "productId") Long productId, @RequestParam(name = "available") boolean available) { return productService.getPositions(productId, available); } @PutMapping(value = "addProductMetaClass") public void addProductMetaClass(@RequestParam(name = "productId") Long productId, @RequestParam(name = "metaIds") List<Long> metaIds) { productService.addProductMetaClass(productId, metaIds); } @PostMapping(value = "deleteProductMetaClass") public void deleteProductMetaClass(@RequestParam(name = "productId") Long productId, @RequestParam(name = "metaIds") List<Long> metaIds) { productService.deleteProductMetaClass(productId, metaIds); } @PostMapping(value = "generateXsd") public void generateXsd() { productService.generateXsd(); } @GetMapping(value = "getProductXsd") public byte[] getProductXsd(@RequestParam(name = "productId") long productId) { return productService.getProductById(productId).getXsd(); } @GetMapping(value = "getProductIdsByMetaClassId") public List<Long> getProductIdsByMetaClassId(@RequestParam(name = "metaClassId") Long metaClassId) { return productService.getProductIdsByMetaClassId(metaClassId); } @PostMapping(value = "addProductPosition") public void addProductPosition(@RequestParam(name = "productId") Long productId, @RequestParam(name = "posIds") List<Long> posIds) { productService.addProductPosition(productId, posIds); } @PostMapping(value = "deleteProductPosition") public void deleteProductPosition(@RequestParam(name = "productId") Long productId, @RequestParam(name = "posIds") List<Long> posIds) { productService.deleteProductPosition(productId, posIds); } @GetMapping(value = "getApproveIterations") public List<ApproveIterationJson> getApproveIterations(@RequestParam(name = "productId") Long productId) { return productService.getApproveIterations(productId); } @PostMapping(value = "setApproveIterations") public void setApproveIterations(@RequestParam(name = "productId") Long productId, @RequestBody List<ApproveIterationJson> approveIterationJsonList) { productService.setApproveIterations(productId, approveIterationJsonList); } @GetMapping(value = "checkForApprove") public boolean checkForApprove(@RequestParam(name = "productId") Long productId, @RequestParam(name = "receiptDateMillis") Long receiptDateMillis, @RequestParam(name = "reportDateMillis") Long reportDateMillis) { return productService.checkForApprove(productId, receiptDateMillis, reportDateMillis); } public static ProductJson convertProductToJson(Product product) { ProductJson json = new ProductJson(); json.setId(product.getId()); json.setCode(product.getCode()); json.setName(product.getName()); json.setCrosscheckPackageName(product.getCrosscheckPackageName()); json.setConfirmWithApproval(product.isConfirmWithApproval()); json.setConfirmWithSignature(product.isConfirmWithSignature()); json.setConfirmPositionIds(product.getConfirmPositionIds()); return json; } } <file_sep>package kz.bsbnb.usci.receiver.dao.impl; import kz.bsbnb.usci.model.batch.Product; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.receiver.dao.BatchDao; import kz.bsbnb.usci.receiver.model.Batch; import kz.bsbnb.usci.receiver.model.BatchStatusType; import kz.bsbnb.usci.receiver.model.BatchType; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ @Repository public class BatchDaoImpl implements BatchDao { private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; private SimpleJdbcInsert batchInsert; @Autowired public BatchDaoImpl(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) { this.jdbcTemplate = jdbcTemplate; this.npJdbcTemplate = npJdbcTemplate; this.batchInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_BATCH") .withTableName("BATCH") .usingGeneratedKeyColumns("ID"); } @Override public Batch load(long id) { List<Map<String, Object>> list = npJdbcTemplate.queryForList("select * from USCI_BATCH.BATCH t where ID = :ID", new MapSqlParameterSource("ID", id)); if (list.size() != 1) throw new UsciException("Ошибка нахождения записи в таблице USCI_BATCH.BATCH"); return getBatchFromJdbcMap(list).get(0); } @Override public long save(Batch batch) { long batchId; if (batch.getId() == null) { batchId = insertBatch(batch); batch.setId(batchId); } else { updateBatch(batch); batchId = batch.getId(); } return batchId; } private long insertBatch(Batch batch) { MapSqlParameterSource params = new MapSqlParameterSource() .addValue("USER_ID", batch.getUserId()) .addValue("CREDITOR_ID", batch.getRespondentId()) .addValue("FILE_NAME",batch.getFilePath()) .addValue("HASH", batch.getHash()) .addValue("SIGN", batch.getSignature()) .addValue("SIGN_INFO", batch.getSignInfo()) .addValue("SIGN_TIME", SqlJdbcConverter.convertToSqlTimestamp(batch.getSignTime())) .addValue("REP_DATE", SqlJdbcConverter.convertToSqlDate(batch.getReportDate())) .addValue("RECEIPT_DATE", SqlJdbcConverter.convertToSqlTimestamp(batch.getReceiptDate())) .addValue("BATCH_ENTRY_ID", batch.getBatchEntryId()) .addValue("TOTAL_COUNT", batch.getTotalEntityCount()) .addValue("ACTUAL_COUNT", batch.getActualEntityCount()) .addValue("REPORT_ID", batch.getConfirmId()) .addValue("PRODUCT_ID", batch.getProduct() != null? batch.getProduct().getId(): null) .addValue("IS_DISABLED", 0) .addValue("IS_MAINTENANCE", batch.isMaintenance()? 1: 0) .addValue("IS_MAINTENANCE_APPROVED", batch.isMaintenanceApproved()? 1: 0) .addValue("IS_MAINTENANCE_DECLINED", batch.isMaintenanceDeclined()? 1: 0); if (batch.getBatchType() != null) params.addValue("BATCH_TYPE", batch.getBatchType()); Number batchId = batchInsert.executeAndReturnKey(params); batch.setId(batchId.longValue()); return batch.getId(); } private void updateBatch(Batch batch) { int count = npJdbcTemplate.update("update USCI_BATCH.BATCH\n" + " set USER_ID = :USER_ID,\n" + " CREDITOR_ID = :CREDITOR_ID,\n" + " PRODUCT_ID = :PRODUCT_ID,\n" + " FILE_NAME = :FILE_NAME,\n" + " HASH = :HASH,\n" + " SIGN = :SIGN,\n" + " SIGN_INFO = :SIGN_INFO,\n" + " SIGN_TIME = :SIGN_TIME,\n" + " REP_DATE = :REP_DATE,\n" + " RECEIPT_DATE = :RECEIPT_DATE,\n" + " BATCH_TYPE = :BATCH_TYPE,\n" + " TOTAL_COUNT = :TOTAL_COUNT,\n" + " ACTUAL_COUNT = :ACTUAL_COUNT,\n" + " REPORT_ID = :REPORT_ID,\n" + " IS_MAINTENANCE = :IS_MAINTENANCE\n" + " where ID = :ID", new MapSqlParameterSource("USER_ID", batch.getUserId()) .addValue("CREDITOR_ID", batch.getRespondentId()) .addValue("FILE_NAME", batch.getFilePath()) .addValue("HASH", batch.getHash()) .addValue("SIGN", batch.getSignature()) .addValue("SIGN_INFO", batch.getSignInfo()) .addValue("SIGN_TIME", SqlJdbcConverter.convertToSqlTimestamp(batch.getSignTime())) .addValue("REP_DATE", SqlJdbcConverter.convertToSqlDate(batch.getReportDate())) .addValue("RECEIPT_DATE", SqlJdbcConverter.convertToSqlTimestamp(batch.getReceiptDate())) .addValue("BATCH_TYPE", batch.getBatchType() != null? batch.getBatchType().getCode(): null) .addValue("TOTAL_COUNT", batch.getTotalEntityCount()) .addValue("ACTUAL_COUNT", batch.getActualEntityCount()) .addValue("REPORT_ID", batch.getConfirmId()) .addValue("IS_MAINTENANCE", batch.isMaintenance()) .addValue("PRODUCT_ID", batch.getProduct() != null? batch.getProduct().getId(): null) .addValue("ID", batch.getId())); if (count != 1) throw new UsciException("Ошибка update записи в таблице USCI_BATCH.BATCH"); } @Override public void updateBatchStatus(long batchId, BatchStatusType status) { int count = jdbcTemplate.update("update USCI_BATCH.BATCH set STATUS_ID = ? where ID = ?", status.getId(), batchId); if (count != 1) throw new UsciException("Ошибка update записи в таблице USCI_BATCH.BATCH"); } @Override //TODO: рефакторинг public List<Batch> getPendingBatchList() { MapSqlParameterSource params = new MapSqlParameterSource() .addValue("statusCompleted", BatchStatusType.COMPLETED.getId()) .addValue("statusError", BatchStatusType.ERROR.getId()) .addValue("statusCancelled", BatchStatusType.CANCELLED.getId()) .addValue("statusDeclined", BatchStatusType.MAINTENANCE_DECLINED.getId()); String query = "select *" + " from USCI_BATCH.BATCH b\n" + " where b.IS_DISABLED = 0\n" + " and b.CREDITOR_ID not in (46) \n"+ // " and b.PRODUCT_ID <> 10 \n"+ //" and b.id in (142132)\n"+ " and b.STATUS_ID not in (:statusError, :statusCancelled, :statusCompleted, :statusDeclined)\n" + " and b.BATCH_TYPE <> 4 order by id\n"; //"and (b.BATCH_TYPE <> 4 or (b.BATCH_TYPE = 4 and b.is_maintenance = 1 and b.is_maintenance_approved = 1 and b.receipt_date > to_date('10.01.2020','dd.mm.yyyy')))order by id\n "; return getBatchFromJdbcMap(npJdbcTemplate.queryForList(query, params)); } @Override public void approveMaintenanceBatchList(List<Long> batchIds) { int count = npJdbcTemplate.update("update USCI_BATCH.BATCH set IS_MAINTENANCE_APPROVED = 1 where ID in (:batchIds)", new MapSqlParameterSource("batchIds", batchIds)); if (count != batchIds.size()) throw new UsciException("Ошибка update записей из таблицы USCI_BATCH.BATCH"); } @Override public void declineMaintenanceBatchList(List<Long> batchIds) { int count = npJdbcTemplate.update("update USCI_BATCH.BATCH set IS_MAINTENANCE_DECLINED = 1 where ID in (:batchIds)", new MapSqlParameterSource("batchIds", batchIds)); if (count != batchIds.size()) throw new UsciException("Ошибка update записей из таблицы USCI_BATCH.BATCH"); } @Override public void clearActualCount(long batchId) { int count = jdbcTemplate.update("update USCI_BATCH.BATCH set ACTUAL_COUNT = 0 where ID = ?", batchId); if (count != 1) throw new UsciException("Ошибка update записи в таблице USCI_BATCH.BATCH"); } @Override public void setBatchTotalCount(long batchId, long totalCount) { int count = jdbcTemplate.update("update USCI_BATCH.BATCH set TOTAL_COUNT = ? where ID = ?", totalCount, batchId); if (count != 1) throw new UsciException("Ошибка update записи в таблице USCI_BATCH.BATCH"); } @Override public void incrementActualCount(long batchId, long count) { int updates = jdbcTemplate.update("update USCI_BATCH.BATCH set ACTUAL_COUNT = ACTUAL_COUNT + :counter where ID = ?", count, batchId); if (updates != 1) throw new UsciException("Ошибка update записи в таблице USCI_BATCH.BATCH"); } @Override public List<Batch> getBatchFromJdbcMap(List<Map<String, Object>> rows) { List<Batch> list = new ArrayList<>(); for (Map<String, Object> row : rows) { Batch batch = new Batch(); batch.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); batch.setUserId(SqlJdbcConverter.convertToLong(row.get("USER_ID"))); batch.setStatus(row.get("STATUS_ID") != null? BatchStatusType.getBatchStatus(SqlJdbcConverter.convertToInt(row.get("STATUS_ID"))): null); batch.setBatchEntryId(SqlJdbcConverter.convertToLong(row.get("BATCH_ENTRY_ID"))); batch.setRespondentId(SqlJdbcConverter.convertToLong(row.get("CREDITOR_ID"))); batch.setFilePath(SqlJdbcConverter.convertObjectToString((row.get("FILE_NAME")))); batch.setProduct(row.get("PRODUCT_ID") != null? new Product(SqlJdbcConverter.convertToLong(row.get("PRODUCT_ID"))): null); batch.setHash(SqlJdbcConverter.convertObjectToString(row.get("HASH"))); batch.setSignature(SqlJdbcConverter.convertObjectToString((row.get("SIGN")))); batch.setStatusId(SqlJdbcConverter.convertToLong(row.get("STATUS_ID"))); batch.setReportDate(SqlJdbcConverter.convertToLocalDate(row.get("REP_DATE"))); batch.setReceiptDate(SqlJdbcConverter.convertToLocalDateTime(row.get("RECEIPT_DATE"))); batch.setBatchType(row.get("BATCH_TYPE") != null? BatchType.getBatchTypeByCode(SqlJdbcConverter.convertObjectToString(row.get("BATCH_TYPE"))): null); batch.setTotalEntityCount(SqlJdbcConverter.convertToLong(row.get("TOTAL_COUNT"))); batch.setActualEntityCount(SqlJdbcConverter.convertToLong(row.get("ACTUAL_COUNT"))); batch.setConfirmId(SqlJdbcConverter.convertToLong(row.get("REPORT_ID"))); batch.setMaintenance(SqlJdbcConverter.convertToBoolean(row.get("IS_MAINTENANCE"))); batch.setMaintenanceApproved(SqlJdbcConverter.convertToBoolean(row.get("IS_MAINTENANCE_APPROVED"))); batch.setMaintenanceDeclined(SqlJdbcConverter.convertToBoolean(row.get("IS_MAINTENANCE_DECLINED"))); list.add(batch); } return list; } } <file_sep>package kz.bsbnb.usci.receiver.parser.impl; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseValue; import kz.bsbnb.usci.eav.model.base.OperType; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.receiver.model.Batch; import kz.bsbnb.usci.receiver.parser.BatchParser; import kz.bsbnb.usci.receiver.parser.exceptions.UnknownTagException; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.io.IOException; import java.io.InputStream; /** * @author <NAME> * @author <NAME> */ @Component @Scope("prototype") public class MainParser extends BatchParser { private final InfoParser infoParser; private final PackageParser packageParser; private final PortfolioDataParser portfolioDataParser; private MetaClass creditMeta; public MainParser(InfoParser infoParser, PackageParser packageParser, PortfolioDataParser portfolioDataParser) { this.infoParser = infoParser; this.packageParser = packageParser; this.portfolioDataParser = portfolioDataParser; } @Override public void init() { creditMeta = metaClassRepository.getMetaClass("credit"); } public void parse(InputStream in, Batch batch) throws SAXException, IOException, XMLStreamException { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); parse(inputFactory.createXMLEventReader(in), batch, 1L, respondentId); } public void parseNextPackage() throws SAXException { long currentIndex = index++; packageParser.parse(xmlReader, batch, currentIndex, respondentId); if (packageParser.hasMore()) { currentBaseEntity = packageParser.getCurrentBaseEntity(); BaseEntity creditor = infoParser.getCurrentBaseEntity(); currentBaseEntity.put("creditor", new BaseValue(creditor)); for (String s : creditor.getValidationErrors()) { currentBaseEntity.addValidationError(s); } } else { parse(xmlReader, batch, index = 1L, respondentId); } } public void skipNextPackage() throws SAXException { while (xmlReader.hasNext()) { XMLEvent event = (XMLEvent) xmlReader.next(); currentBaseEntity = null; if (event.isEndElement()) { EndElement endElement = event.asEndElement(); String localName = endElement.getName().getLocalPart(); if (localName.equals("packages")) { hasMore = false; return; } else if (localName.equals("package")) { hasMore = true; return; } } } } public boolean startElement(XMLEvent event, StartElement startElement, String localName) throws SAXException { switch (localName) { case "batch": break; case "info": infoParser.parse(xmlReader, batch, index, respondentId); break; case "packages": break; case "package": BaseEntity pkg = new BaseEntity(creditMeta, respondentId, batch.getReportDate(), batch.getId()); String strOperationType = event.asStartElement().getAttributeByName( new QName("operation_type")).getValue(); switch (strOperationType) { case "insert": pkg.setOperation(OperType.INSERT); break; case "update": pkg.setOperation(OperType.UPDATE); break; case "delete": pkg.setOperation(OperType.DELETE); break; default: throw new UsciException(String.format("Операция не поддерживается %s", strOperationType)); } packageParser.setCurrentBaseEntity(pkg); hasMore = true; parseNextPackage(); return true; case "portfolio_data": hasMore = true; portfolioDataParser.parse(xmlReader, batch, index, respondentId); currentBaseEntity = portfolioDataParser.getCurrentBaseEntity(); currentBaseEntity.put("creditor", new BaseValue(infoParser.getCurrentBaseEntity())); return true; default: throw new UnknownTagException(localName); } return false; } public boolean endElement(String localName) throws SAXException { switch (localName) { case "batch": hasMore = false; return true; case "info": break; case "packages": break; default: throw new UnknownTagException(localName); } return false; } public int getPackageCount() { return packageParser.getTotalCount(); } } <file_sep>package kz.bsbnb.usci.eav.dao; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseEntityRegistry; import kz.bsbnb.usci.model.exception.UsciException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; /** * @author <NAME> */ @Repository public class BaseEntityRegistryDaoImpl implements BaseEntityRegistryDao { private static final BaseEntityRegistryMapper BASE_ENTITY_REGISTRY_MAPPER = new BaseEntityRegistryMapper(); private final JdbcTemplate jdbcTemplate; private SimpleJdbcInsert baseEntityRegistryInsert; public BaseEntityRegistryDaoImpl(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; this.baseEntityRegistryInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("EAV_DATA") .withTableName("EAV_ENTITY") .usingColumns("ENTITY_ID", "PARENT_ENTITY_ID", "PARENT_CLASS_ID", "CREDITOR_ID", "CLASS_ID"); } @Override public void insert(List<BaseEntityRegistry> baseEntityRegistries) { List<MapSqlParameterSource> params = new ArrayList<>(); for (BaseEntityRegistry info : baseEntityRegistries) params.add(new MapSqlParameterSource() .addValue("ENTITY_ID", info.getEntityId()) .addValue("PARENT_ENTITY_ID", info.getParentEntityId()) .addValue("PARENT_CLASS_ID", info.getParentClassId()) .addValue("CREDITOR_ID", info.getRespondentId()) .addValue("CLASS_ID", info.getMetaClassId())); if (baseEntityRegistries.size() > 1) { int counts[] = baseEntityRegistryInsert.executeBatch(params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException(String.format("Ошибка insert(batch) записей %s в таблицу EAV_DATA.EAV_ENTITY", baseEntityRegistries)); } else { int count = baseEntityRegistryInsert.execute(params.get(0)); if (count != 1) throw new UsciException(String.format("Ошибка insert записи %s в таблицу EAV_DATA.EAV_ENTITY", baseEntityRegistries.get(0))); } } @Override public Optional<BaseEntityRegistry> find(BaseEntity baseEntity) { try { return Optional.ofNullable(jdbcTemplate.queryForObject("select *\n" + " from EAV_DATA.EAV_ENTITY\n" + " where CREDITOR_ID = ?\n" + " and CLASS_ID = ?\n" + " and ENTITY_ID = ?\n", BASE_ENTITY_REGISTRY_MAPPER, baseEntity.getRespondentId(), baseEntity.getMetaClass().getId(), baseEntity.getId())); } catch (EmptyResultDataAccessException e) { return Optional.empty(); } catch (IncorrectResultSizeDataAccessException e) { throw new UsciException(String.format("Найдено более одной записи в таблице EAV_DATA.EAV_ENTITY по сущности %s", baseEntity)); } } @Override public List<BaseEntityRegistry> getBaseEntitiesByMetaClass(Long metaClassId) { return jdbcTemplate.query("select * from EAV_DATA.EAV_ENTITY where CLASS_ID = ?", new Object[]{metaClassId}, BASE_ENTITY_REGISTRY_MAPPER); } private static class BaseEntityRegistryMapper implements RowMapper<BaseEntityRegistry> { @Override public BaseEntityRegistry mapRow(ResultSet rs, int rowNum) throws SQLException { return new BaseEntityRegistry() .setRespondentId(rs.getLong("CREDITOR_ID")) .setMetaClassId(rs.getLong("CLASS_ID")) .setEntityId(rs.getLong("ENTITY_ID")) .setParentEntityId(rs.getLong("PARENT_ENTITY_ID")) .setParentClassId(rs.getLong("PARENT_CLASS_ID")); } } } <file_sep>package kz.bsbnb.usci.util.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import java.util.Set; /** * @author <NAME> */ @FeignClient(name = "utils") public interface ConfigClient { @GetMapping(value = "/config/getDigitalSigningOrgIds") Set<Long> getDigitalSigningOrgIds(); @GetMapping(value = "/config/getQueueAlgorithm") String getQueueAlgorithm(); @GetMapping(value = "/config/getPriorityRespondentIds") Set<Long> getPriorityRespondentIds(); @GetMapping(value = "/config/getManifestXsd") byte[] getManifestXsd(); @GetMapping(value = "/config/getConfirmText") String getConfirmText(); } <file_sep>/** * @author <NAME> * @author <NAME> * @author <NAME> */ Ext.require([ 'Ext.tab.*', 'Ext.tree.*', 'Ext.data.*', 'Ext.tip.*' ]); Ext.onReady(function() { function showEntityData(entityId, metaClassId, respondentId) { // показываю в поле entityId идентификатор сущности var edEntityId = Ext.getCmp("edEntityId"); edEntityId.setValue(entityId); var date = Ext.getCmp('edDate').value; // при выборке записи сущности в гриде подгружаю сущность из бд // чтобы отобразить сущность в дереве сущности // подгружаем из бэкенда сущность в виде дерева entityStore.load({ url: dataUrl + '/core/eav/getEntityData', method: 'GET', params: { entityId: entityId, respondentId: respondentId, metaClassId: metaClassId, date: moment(date).local().format('YYYY-MM-DD'), asRoot: true } }); } Ext.override(Ext.data.proxy.Ajax, {timeout: timeout}); // доп работы по ExtJS createExtJsComps(); // создаем модели мета данных createMetaModels(); var entityStore = Ext.create('Ext.data.TreeStore', { model: 'entityModel', storeId: 'entityStore', folderSort: true, proxy: { type: 'ajax', url: dataUrl + '/core/eav/getEntityData' } }); var buttonReload = Ext.create('Ext.button.Button', { id: "buttonReload", text: label_REFRESH, handler: function() { var dictGrid = Ext.getCmp('dictGrid'); if (!dictGrid) return; var metaClassId = Ext.getCmp('edMetaClass').value; var repDate = Ext.getCmp('edDate').value; var dictStore = dictGrid.getStore(); dictStore.proxy.extraParams = { metaId : metaClassId, userId: userId, isNb: isNb, reportDate: moment(repDate).local().format('YYYY-MM-DD') }; dictStore.load(); dictGrid.getView().refresh(); } }); var buttonNewEntity = Ext.create('Ext.button.Button', { id: "buttonNewEntity", hidden: !isDataManager, text: label_ADD, handler: function() { var edMetaClass = Ext.getCmp('edMetaClass'); var classId = edMetaClass.value; var metaClass = edMetaClass.findRecordByValue(classId).data; showNewEntityWindow(metaClass); } }); var buttonExport = Ext.create('Ext.button.Button', { id: "buttonExport", text: label_EXPORT, handler: function() { var metaClassId = Ext.getCmp('edMetaClass').value; var date = moment(Ext.getCmp('edDate').value).local().format('YYYY-MM-DD'); var xhr = new XMLHttpRequest(); xhr.open("GET", dataUrl + "/core/dict/exportDictionaryToMsExcel?metaClassId="+ metaClassId + '&userId=' + userId + '&isNb=' + isNb + '&date=' + date, true); xhr.responseType = "arraybuffer"; xhr.onload = function (oEvent) { var responseArray = new Uint8Array(this.response); // извлекаю наименование файла из заголовков var fileName = ""; var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition && disposition.indexOf('attachment') !== -1) { var fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = fileNameRegex.exec(disposition); if (matches != null && matches[1]) { fileName = matches[1].replace(/['"]/g, ''); } } var blob = new Blob([responseArray], {type: "application/vnd.ms-excel"}); saveAs(blob, fileName); }; xhr.send(); } }); var buttonOpenEntity = Ext.create('Ext.button.Button', { id: "buttonOpenEntity", text: label_OPEN, hidden: !isDataManager, handler: function() { sendXml('OPEN', Ext.getCmp('edDate').value, Ext.getCmp('edMetaClass').value); } }); var buttonCloseEntity = Ext.create('Ext.button.Button', { id: "buttonCloseEntity", text: label_CLOSE, hidden: !isDataManager, handler: function() { sendXml('CLOSE', Ext.getCmp('edDate').value, Ext.getCmp('edMetaClass').value); } }); var buttonDeleteEntity = Ext.create('Ext.button.Button', { id: "buttonDeleteEntity", text: label_DEL, hidden: !isDataManager, handler: function() { sendXml('DELETE', Ext.getCmp('edDate').value, Ext.getCmp('edMetaClass').value); } }); var buttonShowXml = Ext.create('Ext.button.Button', { id: "buttonShowXml", text: 'XML', handler: function() { showXml(); } }); var buttonSendXml = Ext.create('Ext.button.Button', { id: "buttonSendXml", text: label_SAVE, hidden: !isDataManager, handler: function() { // по справочникам признак подтверждения всегда false isMaintenance = false; sendXml(null, Ext.getCmp('edDate').value, Ext.getCmp('edMetaClass').value); } }); var entityTreeView = Ext.create('Ext.tree.Panel', { id: 'entityTreeView', preventHeader: true, useArrows: true, rootVisible: false, store: entityStore, multiSelect: true, singleExpand: true, columns: [{ xtype: 'treecolumn', text: label_TITLE, flex: 4, sortable: true, dataIndex: 'title' }, { text: label_CODE, flex: 2, dataIndex: 'name', sortable: true }, { text: label_VALUE, flex: 2, dataIndex: 'value', sortable: true }, { text: label_OPEN_DATE, xtype: 'datecolumn', flex: 5, dataIndex: 'openDate', format: 'd.m.Y', sortable: true }, { text: label_CLOSE_DATE, xtype: 'datecolumn', flex: 6, dataIndex: 'closeDate', format: 'd.m.Y', sortable: true }], listeners: { itemcontextmenu: function (me, node, item, index, e, eOpts) { if (!isDataManager) return; if (e.button <= 0) return; // пункты меню при нажатий правой кнопкой мыши var items = []; // меню активно только если нажали узел комплексного атрибута // добавляем значения по комплексному атрибуту if (!node.data.simple) { items.push({ text: label_ADD, handler: function() { showAddEntityAttrWindow(node); } }); } // редактирование сущности и всех ее атрибутов if (!node.data.array && !node.data.simple && (!node.data.dictionary || node.data.depth == 1)) { items.push({ text: label_CHANGE, handler: function() { var metaClassId = null; var windowTitle = null; if (node.data.depth == 1) { metaClassId = Ext.getCmp('edMetaClass').value; windowTitle = Ext.getCmp('edMetaClass').getRawValue(); } else { metaClassId = node.data.refClassId; windowTitle = node.data.title; } showEditEntityWindow(node, metaClassId, windowTitle, false, function() { Ext.getCmp('entityTreeView').getView().refresh(); }); } }); } if (node.data.depth > 1) { // редактирование отдельного атрибута if (node.data.dictionary || (node.data.simple && !(node.parentNode.data.dictionary && node.parentNode.data.depth > 1))) items.push({ text: label_EDIT_ATTR, handler: function() { // если справочник то показываем пикер выбора справочника с гридом // если обычный атрибут то диалговое окошко с атрибутом и его значением if (node.data.dictionary) { showDictPicker(node.data.refClassId, node.data.title, function(selData) { dictChange(node, selData.entity_id, selData.creditor_id, node.data.refClassId, function() { Ext.getCmp('entityTreeView').getView().refresh(); }); }); } else { showEditAttrWindow(node, false, function() { Ext.getCmp('entityTreeView').getView().refresh(); editorAction.commitEdit(); }); } } }); // запрещаем удалять элементы кумулятивного сета, // ключевые атрибуты и также значения справочников if (!(node.parentNode.data.array && node.parentNode.data.cumulative) && !node.data.key && !(node.parentNode.data.dictionary && node.parentNode.data.depth > 1)) { items.push({ text: label_DEL, handler: function () { showDeleteWindow(node); } }); } } // внимание!!! костыль для справочника ref_portfolio // если нажали на атрибуты respondent, code то обнуляю меню // так как данные атрибуты нельзя редактировать if (node.data.classId == 36 && node.data.name == 'respondent' || node.data.name == 'code') items = []; if (items.length == 0) items.push({ text: label_NO_AVA, handler: function() { } }); var menu = new Ext.menu.Menu({ items: items }); menu.showAt(e.xy); e.stopEvent(); } } }); var mainPanel = Ext.create('Ext.panel.Panel', { height: '700px', width: '100%', renderTo: 'entity-editor-content', title: '&nbsp', id: 'mainPanel', layout: 'border', defaults : { padding: '3' }, dockedItems: [ { fieldLabel: label_REF, id: 'edMetaClass', xtype: 'combobox', displayField: 'title', width: '60%', labelWidth: '40%', valueField: 'id', editable: false, listeners: { change: function(a, key, prev) { var metaClass = a.findRecordByValue(key).data; // банки могут только работать со справочником ref_portfolio // то есть для остальных справочников операций не доступны if(!isNb) { if (metaClass.name == 'ref_portfolio') { buttonNewEntity.show(); buttonSendXml.show(); buttonShowXml.show(); } else { buttonNewEntity.hide(); buttonSendXml.hide(); buttonShowXml.hide(); buttonDeleteEntity.hide(); buttonCloseEntity.hide(); buttonOpenEntity.hide(); } } var repDate = Ext.getCmp('edDate').value; // создаю грид справочника createDictGrid(metaClass.id, repDate, function(dictGrid) { dictGrid.on('itemclick', function(dv, record, item, index, e) { var entityId = record.get('entity_id'); var respondentId = record.get('creditor_id'); showEntityData(entityId, metaClass.id, respondentId); }); dictGrid.store.on('load', function(me, records, options) { if (records.length > 0) { dictGrid.getSelectionModel().select(0); var entityId = records[0].data.entity_id; var respondentId = records[0].data.creditor_id; showEntityData(entityId, metaClass.id, respondentId); } }); var dictGridContainer = Ext.getCmp('gridPanel'); dictGridContainer.removeAll(); dictGridContainer.add(dictGrid); }); } }, store: Ext.create('Ext.data.Store', { model: 'metaClassModel', id: 'metaClassStore', pageSize: 100, proxy: { type: 'ajax', url: dataUrl + '/core/meta/getDictionaries', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } }, listeners: { load: function(me, records, options) { var metaClass = records[0]; Ext.getCmp('edMetaClass').setValue(metaClass.get('id')); } }, autoLoad: true, remoteSort: true }) }, { xtype: 'textfield', id: 'edEntityId', fieldLabel: label_ID_ENTITY, width: '60%', labelWidth: '40%', enabled: true, disabled : true, value: (queryEntityId == "null" ? "" : queryEntityId) }, { xtype: 'datefield', id: 'edDate', fieldLabel: label_DATE, format: 'd.m.Y', value: new Date(), width: '60%', labelWidth: '40%' }, { xtype: 'tbseparator', height: 10 } ], items: [ { id: 'gridPanel', region: 'north', width: '100%', split: true, items: [], autoScroll: true, tbar: [buttonReload, buttonNewEntity, buttonSendXml, buttonShowXml, buttonDeleteEntity, buttonOpenEntity, buttonCloseEntity, buttonExport] }, { xtype : 'panel', region: 'center', preventHeader: true, width: '100%', autoScroll: true, items: [entityTreeView] } ] }); }); <file_sep>package kz.bsbnb.usci.brms.model; import java.io.Serializable; import java.time.LocalDate; /** * @author <NAME> */ public class PackageVersion implements Serializable { private static final long serialVersionUID = 1L; private LocalDate reportDate; private RulePackage rulePackage; public PackageVersion() { super(); } public PackageVersion(RulePackage rulePackage, LocalDate date) { this.reportDate = date; this.rulePackage = rulePackage; } public LocalDate getReportDate() { return reportDate; } public void setReportDate(LocalDate reportDate) { this.reportDate = reportDate; } public RulePackage getRulePackage() { return rulePackage; } public void setRulePackage(RulePackage rulePackage) { this.rulePackage = rulePackage; } } <file_sep>package kz.bsbnb.usci.report.model; import kz.bsbnb.usci.model.persistence.Persistable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Report extends Persistable { private static final long serialVersionUID = 1L; private String nameRu; private String nameKz; private String name; private String procedureName; private String type; private Long orderNumber; private Set<ReportInputParameter> inputParameters; private List<ExportType> exportTypesList; public String getNameRu() { return nameRu; } public void setNameRu(String nameRu) { this.nameRu = nameRu; } public String getNameKz() { return nameKz; } public void setNameKz(String nameKz) { this.nameKz = nameKz; } public String getName() { return name; } public void setName(String fileName) { this.name = fileName; } public String getProcedureName() { return procedureName; } public void setProcedureName(String procedureName) { this.procedureName = procedureName; } public List<ReportInputParameter> getInputParameters() { return new ArrayList<ReportInputParameter>(inputParameters); } public void setInputParameters(List<ReportInputParameter> inputParameters) { this.inputParameters = new HashSet<ReportInputParameter>(inputParameters); } public List<String> getParameterNames() { List<java.lang.String> result = new ArrayList<java.lang.String>(); for(ReportInputParameter parameter : inputParameters) { result.add(parameter.getParameterName()); } return result; } public List<String> getParameterCaptions() { List<java.lang.String> result = new ArrayList<java.lang.String>(); for(ReportInputParameter parameter : inputParameters) { result.add(parameter.getNameRu()); } return result; } @Override public boolean equals(Object other) { if (other instanceof Report) { Report otherReport = (Report) other; return id == otherReport.getId(); } return false; } @Override public int hashCode() { int hash = 7; hash = 47 * hash + (int) (this.id ^ (this.id >>> 32)); return hash; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<ExportType> getExportTypesList() { return exportTypesList; } public void setExportTypeList(List<ExportType> exportTypeList) { this.exportTypesList = exportTypeList; } public Long getOrderNumber() { return orderNumber; } public void setOrderNumber(Long orderNumber) { this.orderNumber = orderNumber; } }<file_sep>package kz.bsbnb.usci.receiver.model.json; import com.fasterxml.jackson.annotation.JsonFormat; import org.springframework.format.annotation.DateTimeFormat; import java.time.LocalDate; import java.time.LocalDateTime; /** * @author <NAME> */ public class BatchEntryJson { private Long id; private String value; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @JsonFormat(pattern = "yyyy-MM-dd") private LocalDate repDate; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") private LocalDateTime updateDate; private Long userId; private Long entityId; private Boolean isMaintenance; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public LocalDate getRepDate() { return repDate; } public void setRepDate(LocalDate repDate) { this.repDate = repDate; } public LocalDateTime getUpdateDate() { return updateDate; } public void setUpdateDate(LocalDateTime updateDate) { this.updateDate = updateDate; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getEntityId() { return entityId; } public void setEntityId(Long entityId) { this.entityId = entityId; } public Boolean getMaintenance() { return isMaintenance; } public void setMaintenance(Boolean maintenance) { isMaintenance = maintenance; } } <file_sep>package kz.bsbnb.usci.receiver.parser.impl; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseValue; import kz.bsbnb.usci.receiver.parser.BatchParser; import kz.bsbnb.usci.receiver.parser.exceptions.UnknownTagException; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.xml.sax.SAXException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.time.LocalDate; /** * @author <NAME> * @author <NAME> */ @Component @Scope("prototype") public class CreditContractParser extends BatchParser { public CreditContractParser() { super(); } @Override public void init() { currentBaseEntity = new BaseEntity(metaClassRepository.getMetaClass("contract"), respondentId, batch.getReportDate(), batch.getId()); } @Override public boolean startElement(XMLEvent event, StartElement startElement, String localName) throws SAXException { switch (localName) { case "contract": break; case "no": event = (XMLEvent) xmlReader.next(); currentBaseEntity.put("no", new BaseValue(trim(event.asCharacters().getData()))); break; case "date": event = (XMLEvent) xmlReader.next(); currentBaseEntity.put("date", new BaseValue(LocalDate.parse(trim(event.asCharacters().getData())))); break; default: throw new UnknownTagException(localName); } return false; } @Override public boolean endElement(String localName) throws SAXException { switch (localName) { case "contract": return true; case "no": break; case "date": break; default: throw new UnknownTagException(localName); } return false; } } <file_sep>package kz.bsbnb.usci.eav.dao; import kz.bsbnb.usci.eav.model.meta.MetaClass; import java.util.List; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ public interface MetaClassDao { long save(MetaClass meta); MetaClass load(String className); MetaClass load(Long id); List<MetaClass> loadAll(); void remove(MetaClass metaClass); List<Long> loadClassesWithReference(Long id); } <file_sep>package kz.bsbnb.usci.brms.service; import kz.bsbnb.usci.brms.model.RulePackage; import java.util.List; public interface PackageService { long savePackage(String rulePackageName); RulePackage load(long id); List<RulePackage> getAllPackages(); } <file_sep>var LABEL_SEND = 'Отправить'; var LABEL_EDIT = 'Редактировать'; var LABEL_DATE = 'Дата'; var LABEL_CODE = 'Код'; var LABEL_TITLE = 'Наименование'; var LABEL_REFERENCE = 'Справочник'; var LABEL_ITEMS = 'Элементы'; var LABEL_ERROR = 'Ошибка'; var LABEL_ERROR_NO_DATA = 'Не возможно получить данные'; var LABEL_VIEW = 'Просмотр'; var LABEL_ERROR_NO_DATA_FOR = 'Не возможно получить данные: {0}'; var LABEL_SAVE = 'Сохранить'; var LABEL_CANCEL = 'Отмена'; var LABEL_VALUE = 'Значение'; var LABEL_ARRAY = 'Массив'; var LABEL_TYPE = 'Тип'; var LABEL_INPUT_FORM = "Форма ввода"; var LABEL_REF = 'Справочник'; var LABEL_ITEMS = 'Элементы'; var LABEL_ENTITY_ID = 'Идентификатор сущности'; var LABEL_DEL = 'Удалить'; var LABEL_ADD = 'Добавить'; var LABEL_ADDING = 'Идет удаление...'; var LABEL_ERROR_ACC = "Произошла ошибка: {0}"; var LABEL_ERROR_ACC = "Произошла ошибка: {0}_"; var LABEL_CHOOSE = 'Выберите класс для просмотра'; var LABEL_CLASSES = "Классы"; var LABEL_DATA_PANEL = 'Панель метаданных'; var LABEL_CLASS_ST = 'Структура класса'; var LABEL_UNFOLD = 'Раскрыть всё'; var LABEL_FOLD = 'Свернуть всё'; var LABEL_DOWNLOAD_XSD = 'Скачать схему'; var LABEL_ACTIVE = 'Активный'; var LABEL_NOT_ACTIVE = 'Не активный'; var LABEL_SENDING = 'Идет отправка...'; var LABEL_ATTENTION = 'Внимание'; var LABEL_ERROR_EXIST = "Произошла ошибка"; var LABEL_YES = 'Да'; var LABEL_NO = 'Нет'; var LABEL_SIMPLE = 'Простой'; var LABEL_COMPLEX = 'Составной'; var LABEL_SIMPLE_SET = 'Массив простых'; var LABEL_COMPLEX_SET = 'Массив составных'; var LABEL_NUMBER = 'Число'; var LABEL_STRING = 'Строка'; var LABEL_BOOLEAN = 'Булево'; var LABEL_FLOAT = 'Число с плавающей точкой'; var LABEL_CLASS_CODE = 'Код класса'; var LABEL_PARENT_CODE = 'Код родителя'; var LABEL_ATTRIBUTE_PUTH = 'Путь аттрибута'; var LABEL_ATTRIBUTE_CODE = 'Код аттрибута'; var LABEL_ARRTIBUTE_NAME = 'Наименование аттрибута'; var LABEL_ATTRIBUTE_TYPE = 'Тип аттрибута'; var LABEL_ATTRIBUTE_CLASS = 'Класс аттрибута'; var LABEL_KEY_ATTRIBUTE = 'Ключевой аттрибут'; var LABEL_MUST_ATTRIBUTE = 'Обязательный аттрибут'; var LABEL_NULL_GET = 'Обнуляемый'; var LABEL_FINAL_RECORD = 'Финальная запись'; var LABEL_NOT_CHANGED_RECORD = 'Не изменная запись'; var LABEL_ACTIVITY = 'Признак активности'; var LABEL_LOADING = 'Идет загрузка...'; var LABEL_ERROR = 'Ошибка'; var LABEL_ATTRIBUTE = 'Аттрибут'; var LABEL_NOT_REF = 'Не справочник'; var LABEL_ALL_FIELDS = 'Заполните ВСЕ поля'; var LABEL_CLASS_TYPE = 'Тип класса'; var LABEL_META = 'Метакласс'; var LABEL_REQUIRED_FIELD = "Обязательное поле"; var LABEL_UI_CONFIG = "UI CONFIG"; var label_OPER = 'Оперативные'; var label_SYNCING = 'Идет синхронизация обьектов БД с мета данными...'; var label_INFO = 'Информация'; var label_SUC_SYNC = 'Синхранизация завершена успешно'; var label_ALL = 'Все'; var label_OFF = 'Отдельно'; var label_DATE_AND_TIME = 'Дата и время'; var label_SAVING = 'Идет сохранение...'; var label_MUST = 'Обязательный'; var label_NOT_ACTIVE = 'Не активный'; var label_LINK = 'Ссылка'; var label_NULLABLE = 'Обнуляемый'; var label_DOCH = 'Дочерний'; var label_MASS = 'Массивы'; var label_SOBIR = 'Собирательный'; var label_TYPE_KEY = 'Тип ключа'; var label_KEYS = 'Ключи'; var label_KEYABLE = 'Ключевой'; var label_EMPTY = 'Пустой'; var label_GROUP_KEYS = 'Группа ключей'; var label_2min = 'До 2 минут'; var label_10min = 'До 10 минут'; var label_50min = 'До 50 минут'; var label_50minmore = 'Свыше 50 минут'; var label_PERIODICY = 'Период*'; var label_SIZE_TABLE = 'Размер таблиц *'; <file_sep>package kz.bsbnb.usci.core; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.util.json.ext.ExtJsJson; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; /** * @author <NAME> * Перехватчик ошибок для ExtJs */ @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); private static final String JSON_V1 = "application/vnd.captech-v1.0+json"; private static final String JSON_V2 = "application/vnd.captech-v2.0+json"; @RequestMapping(produces = {JSON_V1, JSON_V2}) @ExceptionHandler(UsciException.class) @ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE) @ResponseBody public ExtJsJson handleUncaughtException(UsciException ex) { logger.error("Ошибка", ex); return buildError(ex); } private ExtJsJson buildError(Throwable ex) { ExtJsJson error = new ExtJsJson(); error.setSuccess(false); error.setErrorMessage(ex.getMessage()); return error; } } <file_sep>group = 'kz.bsbnb.usci' version '0.1.0' dependencies { compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul') compile("org.springframework.boot:spring-boot-starter-actuator") } bootJar { baseName = 'usci-zuul' version = '0.1.0' } springBoot { mainClassName = 'kz.bsbnb.usci.zuul.ZuulApplication' } <file_sep>group = 'kz.bsbnb.usci.core' version = '0.1.0' dependencies { compile project(':eav:eav-core') compile project(':eav:eav-meta') compile project(':brms:brms-core') compile project(':util:util-api') compile project(':core:core-api') compile project(':mail:mail-api') compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-jdbc") // библиотеки эцп compile('kz.gamma:crypto-common10') compile('kz.gamma:gammaprov11') compile('com.itextpdf:itextpdf5513') } jar { baseName = 'usci-core-core' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>package kz.bsbnb.usci.model.respondent; import kz.bsbnb.usci.model.persistence.Persistable; import java.time.LocalDateTime; /** * @author <NAME> */ public class ConfirmStage extends Persistable { private Long confirmId; private ConfirmStatus status; private LocalDateTime stageDate; private Long userId; private String signature; private byte[] document; private Long userPosId; private String docHash; private String signInfo; public ConfirmStage() { super(); } @Override public ConfirmStage setId(Long id) { super.setId(id); return this; } public Long getConfirmId() { return confirmId; } public ConfirmStage setConfirmId(Long confirmId) { this.confirmId = confirmId; return this; } public Long getUserId() { return userId; } public ConfirmStage setUserId(Long userId) { this.userId = userId; return this; } public ConfirmStatus getStatus() { return status; } public ConfirmStage setStatus(ConfirmStatus status) { this.status = status; return this; } public LocalDateTime getStageDate() { return stageDate; } public ConfirmStage setStageDate(LocalDateTime stageDate) { this.stageDate = stageDate; return this; } public String getSignature() { return signature; } public ConfirmStage setSignature(String signature) { this.signature = signature; return this; } public byte[] getDocument() { return document; } public ConfirmStage setDocument(byte[] document) { this.document = document; return this; } public Long getUserPosId() { return userPosId; } public ConfirmStage setUserPosId(Long userPosId) { this.userPosId = userPosId; return this; } public String getDocHash() { return docHash; } public ConfirmStage setDocHash(String docHash) { this.docHash = docHash; return this; } public String getSignInfo() { return signInfo; } public ConfirmStage setSignInfo(String signInfo) { this.signInfo = signInfo; return this; } } <file_sep>package kz.bsbnb.usci.eav.service; import kz.bsbnb.usci.eav.dao.BaseEntityStatusDao; import kz.bsbnb.usci.eav.model.core.BaseEntityStatus; import org.springframework.stereotype.Service; @Service public class BaseEntityStatusServiceImpl implements BaseEntityStatusService { private final BaseEntityStatusDao baseEntityStatusDao; BaseEntityStatusServiceImpl(BaseEntityStatusDao baseEntityStatusDao) { this.baseEntityStatusDao = baseEntityStatusDao; } @Override public BaseEntityStatus insert(BaseEntityStatus baseEntityStatus) { return baseEntityStatusDao.insertBatchMethod(baseEntityStatus); } @Override public void update(BaseEntityStatus baseEntityStatus) { baseEntityStatusDao.update(baseEntityStatus); } } <file_sep>package kz.bsbnb.usci.core.controller; import kz.bsbnb.usci.core.service.ConfirmService; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.model.respondent.*; import kz.bsbnb.usci.util.json.ext.ExtJsList; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; import java.util.Map; /** * @author <NAME> * @author <NAME> */ @RestController @RequestMapping(value = "/confirm") public class ConfirmRestController { private final ConfirmService confirmService; public ConfirmRestController(ConfirmService confirmService) { this.confirmService = confirmService; } @GetMapping(value = "/updateConfirm") public Map<String, Object> updateConfirm(@RequestParam(name = "respondentId") Long respondentId, @RequestParam(name = "reportDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate reportDate, @RequestParam(name = "productId") Long productId, @RequestParam(name = "userId") Long userId) { return confirmService.updateConfirm(respondentId, reportDate, productId, userId); } @GetMapping(value = "/getConfirmList") public ExtJsList getConfirmJson(@RequestParam(required = false, name = "userId") Long userId, @RequestParam(required = false, name = "isNb") Boolean isNb, @RequestParam(required = false, name = "respondentIds") List<Long> respondentIds, @RequestParam(required = false, name = "reportDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate reportDate, @RequestParam(name = "page") Integer pageIndex, @RequestParam(name = "limit") Integer pageSize) { return confirmService.getConfirmJsonList(userId, isNb, respondentIds, reportDate, pageIndex, pageSize); } @GetMapping(value = "createConfirmDocument") public byte[] createConfirmDocument(@RequestParam(name = "confirmId") long confirmId, @RequestParam(name = "userId") long userId, @RequestParam(name = "userName") String userName) { return confirmService.createConfirmDocument(confirmId, userId, userName); } @GetMapping(value = "getConfirmDocument") public byte[] getConfirmDocument(@RequestParam(name = "id") long id) { return confirmService.getConfirmDocument(id); } @GetMapping(value = "/getConfirmJson") public ConfirmJson getConfirmJson(@RequestParam Long confirmId) { return confirmService.getConfirmJson(confirmId); } @GetMapping(value = "getConfirmStageJsonList") public List<ConfirmStageJson> getConfirmStageJsonList(@RequestParam(name = "confirmId") Long confirmId) { return confirmService.getConfirmStageJsonList(confirmId); } @GetMapping(value = "getConfirmDocumentHash") public String getConfirmDocumentHash(@RequestParam(name = "confirmId") Long confirmId, @RequestParam(name = "userId") Long userId, @RequestParam(name = "userName") String userName) { return confirmService.getConfirmDocumentHash(confirmId, userId, userName); } @PostMapping(value = "approve") public void approve(@RequestParam(name = "userId") Long userId, @RequestParam(name = "confirmId") Long confirmId, @RequestParam(name = "documentHash") String documentHash, @RequestParam(name = "signature") String signature, @RequestParam(name = "userName") String userName) { confirmService.approve(userId, confirmId, documentHash, signature, userName); } @PostMapping(value = "addConfirmMessage") public void addConfirmMessage(@RequestParam(name = "confirmId") Long confirmId, @RequestParam(name = "userId") Long userId, @RequestParam(name = "text") String text, @RequestParam("file") MultipartFile[] files) { ConfirmMessage confirmMessage = new ConfirmMessage(); confirmMessage.setConfirmId(confirmId); confirmMessage.setUserId(userId); confirmMessage.setSendDate(LocalDateTime.now()); confirmMessage.setText(text); for (MultipartFile uploadedFile : files) { ConfirmMessageFile messageFile = new ConfirmMessageFile(); try { messageFile.setContent(uploadedFile.getBytes()); messageFile.setFileName(uploadedFile.getOriginalFilename()); } catch (IOException e) { throw new UsciException("Ошибка загрузки прикрепленного документа сообщения", e); } confirmMessage.getFiles().add(messageFile); } confirmService.addConfirmMessage(confirmMessage); } @GetMapping(value = "/getMessagesByConfirmId") public List<ConfirmMessageJson> getMessagesByConfirmId(@RequestParam(name = "confirmId") Long confirmId) { return confirmService.getMessagesByConfirmId(confirmId); } @GetMapping(value = "getMessageFileContent") public byte[] getMessageFileContent(@RequestParam(name = "fileId") Long fileId) { return confirmService.getMessageFileContent(fileId); } @GetMapping(value = "getFilesByMessageId") public List<ConfirmMsgFileJson> getFilesByMessageId(@RequestParam(name = "messageId") Long messageId) { return confirmService.getFilesByMessageId(messageId); } } <file_sep>package kz.bsbnb.usci.eav.service; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseEntityRegistry; import kz.bsbnb.usci.eav.model.core.BaseEntityStatus; import java.time.LocalDate; import java.util.List; public interface EntityService { boolean existsBaseEntity(BaseEntity baseEntity, LocalDate reportDate); long countBaseEntityEntries(BaseEntity baseEntity); boolean hasReference(BaseEntity baseEntity); void insert(List<BaseEntityRegistry> infos); Long addEntityStatus(BaseEntityStatus entityStatus); } <file_sep>/** * @author <NAME> * @author <NAME> * @author <NAME> */ Ext.require([ 'Ext.tab.*', 'Ext.tree.*', 'Ext.data.*', 'Ext.tip.*' ]); Ext.onReady(function() { Ext.override(Ext.data.proxy.Ajax, {timeout: timeout}); // доп работы по ExtJS createExtJsComps(); // создаем модели мета данных createMetaModels(); var respondentId; var respondentStore = Ext.create('Ext.data.Store', { fields: ['id', 'name'], proxy: { type: 'ajax', extraParams: { userId: userId }, url: dataUrl + '/core/respondent/getUserRespondentList', reader: { type: 'json', root: 'data', totalProperty: 'total' } }, autoLoad: true, listeners: { load: function(me, records, options) { if (queryRespondentId && queryRespondentId != 'null') { respondentId = records[0].get('id'); return; } respondentId = records[0].get('id'); // по умолчанию укажем на первого кредитора Ext.getCmp('edRespondent').setValue(respondentId); } } }); var entityStore = Ext.create('Ext.data.TreeStore', { model: 'entityModel', storeId: 'entityStore', folderSort: true, proxy: { type: 'memory' } }); // при нажатий кнопки идет обращение в бэк для поиска var buttonSearch = Ext.create('Ext.button.Button', { id: "buttonSearch", text: label_SEARCH, handler: function() { // сбрасываю значение перед каждым поиском isMaintenance = false; Ext.getCmp('buttonSearch').disable(); var loadMask = new Ext.LoadMask(Ext.getBody(), { msg: label_SEARCHING }); loadMask.show(); var entityData = getSearchDataFromTree(searchTree.getRootNode()); Ext.Ajax.request({ url: dataUrl + '/core/eav/searchEntity', method: 'POST', params: { respondentId: Ext.getCmp('edRespondent').value, metaClassId: Ext.getCmp('edMetaClass').value, date: moment(Ext.getCmp('edDate').value).local().format('YYYY-MM-DD') }, jsonData: entityData, success: function(response) { loadMask.hide(); Ext.getCmp('buttonSearch').enable(); var jsonData = JSON.parse(response.responseText); entityStore.setRootNode(jsonData); Ext.getCmp('entityTreeView').getView().refresh(); }, failure: function(response) { loadMask.hide(); Ext.getCmp('buttonSearch').enable(); var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); }, maxWidth: 70, shadow: true }); var buttonNewEntity = Ext.create('Ext.button.Button', { id: "buttonNewEntity", text: label_ADD, handler: function() { var edMetaClass = Ext.getCmp('edMetaClass'); var classId = edMetaClass.value; var metaClass = edMetaClass.findRecordByValue(classId).data; showNewEntityWindow(metaClass); } }); var searchStore = Ext.create('Ext.data.TreeStore', { model: 'entityModel', storeId: 'searchStore', folderSort: true, proxy: { type: 'memory' } }); var searchTree = Ext.create('Ext.tree.Panel', { id: 'searchTreeView', preventHeader: true, useArrows: true, rootVisible: true, store: searchStore, multiSelect: true, singleExpand: true, columns: [{ xtype: 'treecolumn', text: label_TITLE, flex: 4, sortable: true, dataIndex: 'title' }, { text: label_CODE, flex: 2, dataIndex: 'name', sortable: true }, { text: label_VALUE, flex: 2, dataIndex: 'value', sortable: true }], listeners: { itemcontextmenu: function (me, node, item, index, e, eOpts) { if (e.button <= 0) return; // пункты меню при нажатий правой кнопкой мыши var items = []; // меню активно только если нажали узел комплексного атрибута // добавляем значения по комплексному атрибуту // создал отдельное окошко чтобы не было путаницы if (!node.data.simple && !node.data.dictionary && ((node.parentNode && !node.parentNode.data.dictionary) || !node.parentNode)) { items.push({ text: label_ADD, handler: function() { showAddSearchParamWindow(node); } }); } // редактирование отдельного атрибута if (node.data.dictionary || (node.data.simple && !node.parentNode.data.dictionary)) items.push({ text: label_EDITING_ATTR, handler: function() { // если справочник то показываем пикер выбора справочника с гридом // если обычный атрибут то диалговое окошко с атрибутом и его значением if (node.data.dictionary) { showDictPicker(node.data.refClassId, node.data.title, function(selData) { dictChange(node, selData.entity_id, selData.creditor_id, node.data.refClassId, function() { Ext.getCmp('searchTreeView').getView().refresh(); }); }); } else { showEditAttrWindow(node, true, function() { Ext.getCmp('searchTreeView').getView().refresh(); }); } } }); // изменение параметров поиска // меню позволяет редактировать только комлексные атрибуты // то есть запрещает редактировать простые атрибуты или справочники if (!node.data.array && !node.data.simple && !node.data.dictionary) { items.push({ text: label_CHANGE, handler: function() { var metaClassId = null; var windowTitle = null; if (node.data.depth == 0) { metaClassId = Ext.getCmp('edMetaClass').value; windowTitle = Ext.getCmp('edMetaClass').getRawValue(); } else { metaClassId = node.data.refClassId; windowTitle = node.data.title; } showEditEntityWindow(node, metaClassId, windowTitle, true, function() { Ext.getCmp('searchTreeView').getView().refresh(); }); } }); } // удаление параметра поиска; никаких ограничений, удаляют что хотят if (node.data.depth > 0 && !node.parentNode.data.dictionary) { items.push({ text: label_DEL, handler: function() { node.parentNode.removeChild(node); } }); } if (items.length == 0) items.push({ text: label_NO_AVA_OPER, handler: function() { } }); var menu = new Ext.menu.Menu({ items: items }); menu.showAt(e.xy); e.stopEvent(); } } }); var entityGrid = Ext.create('Ext.tree.Panel', { id: 'entityTreeView', preventHeader: true, useArrows: true, rootVisible: false, store: entityStore, multiSelect: true, singleExpand: true, columns: [{ xtype: 'treecolumn', text: label_TITLE, flex: 4, sortable: true, dataIndex: 'title' }, { text: label_CODE, flex: 4, sortable: true, dataIndex: 'name' }, { text: label_VALUE, flex: 2, dataIndex: 'value', sortable: true }, { text: label_OPEN_DATE, flex: 5, xtype: 'datecolumn', format: 'd.m.Y', dataIndex: 'openDate', sortable: true }, { text: label_CLOSE_DATE, flex: 6, xtype: 'datecolumn', format: 'd.m.Y', dataIndex: 'closeDate', sortable: true }], listeners: { itemcontextmenu: function (me, node, item, index, e, eOpts) { if (e.button <= 0) return; // пункты меню при нажатий правой кнопкой мыши var items = []; // пункты меню: "отправка изменений", "просмотр XML" отображаем только если нажали // корневой узел; например: кредит if (node.data.depth == 1) { items.push({ text: label_SEND_CHANGES, handler: function() { sendXml(null, Ext.getCmp('edDate').value, Ext.getCmp('edMetaClass').value); } }); items.push({ text: 'XML', handler: function() { showXml(); } }); } // меню активно только если нажали узел комплексного атрибута // добавляем значения по комплексному атрибуту // создал отдельное окошко чтобы не было путаницы if (!node.data.simple && !node.data.dictionary && ((node.parentNode && !node.parentNode.data.dictionary) || !node.parentNode) || node.data.array) { items.push({ text: label_ADD, handler: function() { showAddEntityAttrWindow(node); } }); } if ((node.data.dictionary && !node.data.array) || (node.data.simple && !node.data.array && !node.parentNode.data.dictionary)) items.push({ text: label_EDITING_ATTR, handler: function() { // если справочник то показываем пикер выбора справочника с гридом // если обычный атрибут то диалговое окошко с атрибутом и его значением if (node.data.dictionary) { if (node.parentNode.data.array && node.parentNode.data.dictionary) { showDictPicker(node.parentNode.data.refClassId, node.data.title, function(selData) { dictChange(node, selData.entity_id, selData.creditor_id, node.data.refClassId, function() { Ext.getCmp('entityTreeView').getView().refresh(); editorAction.commitEdit(); }); }); } else { showDictPicker(node.data.refClassId, node.data.title, function(selData) { dictChange(node, selData.entity_id, selData.creditor_id, node.data.refClassId, function() { Ext.getCmp('entityTreeView').getView().refresh(); editorAction.commitEdit(); }); }); } } else { showEditAttrWindow(node, false, function() { Ext.getCmp('entityTreeView').getView().refresh(); editorAction.commitEdit(); }); } } }); if (!(node.parentNode.data.array && node.parentNode.data.cumulative)) { items.push({ text: label_DEL, handler: function() { showDeleteWindow(node); }, disabled: node.data.key || node.parentNode.data.dictionary }); } if (items.length == 0) items.push({ text: label_NO_AVA_OPER, handler: function() { } }); var menu = new Ext.menu.Menu({ items: items }); menu.showAt(e.xy); e.stopEvent(); } } }); var metaClassStore = Ext.create('Ext.data.Store', { model: 'metaClassModel', id: 'metaClassStore', pageSize: 100, proxy: { type: 'ajax', url: dataUrl + '/core/meta/getMetaClassJsonListByUserId', actionMethods: { read: 'GET' }, extraParams: { userId: userId }, listeners : { exception: function(proxy, response, operation, eOpts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }, reader: { type: 'json', root: '' } }, listeners: { load: function(me, records, options) { var edMetaClass = Ext.getCmp("edMetaClass"); var defaultMetaClassId = records[0].get('id'); if (queryMetaClassId && queryMetaClassId != 'null') defaultMetaClassId = Number(queryMetaClassId); Ext.getCmp('edMetaClass').setValue(defaultMetaClassId); } }, autoLoad: true, remoteSort: true }); var mainPanel = Ext.create('Ext.panel.Panel', { height: 500, renderTo: 'entity-editor-content', title: '&nbsp', id: 'mainPanel', layout: 'border', items: [{ region: 'west', width: '35%', split: true, layout: 'border', items: [{ region: 'north', height: '30%', split: true, layout: { type: 'vbox', padding: 5, align: 'stretch' }, items: [ { fieldLabel: 'Метакласс', id: 'edMetaClass', xtype: 'combobox', displayField: 'title', width: '60%', labelWidth: '40%', valueField: 'id', editable: false, listeners: { change: function(a, key, prev) { if (a.store.getRange().length == 0) return; // добавляем в дерево поиска сущности корень ноду var metaClass = a.findRecordByValue(Number(key)).data; var entityData = { "title": metaClass.title, "expanded": true }; searchStore.setRootNode(entityData); fillSearchTree(metaClass.id); var rootData = Ext.create('entityModel', { title: '.', children: [] }); entityStore.setRootNode(rootData); } }, store: metaClassStore }, { id: 'edRespondent', xtype: 'combobox', displayField: 'name', store: respondentStore, labelWidth: 70, valueField: 'id', fieldLabel: label_RESPONDENT, editable: false, width: '60%', labelWidth: '40%' }, { xtype: 'datefield', id: 'edDate', fieldLabel: label_DATE, format: 'd.m.Y', value: new Date(), width: '60%', labelWidth: '40%' } ] }, { region: 'center', id: 'form-area', title: label_SEARCH_PARA, height: '80%', split: true, items: [searchTree], tbar: [buttonSearch] }] }, { id: 'gridPanel', region: 'center', width: "40%", split: true, items: [entityGrid], autoScroll: true, tbar: [buttonNewEntity], bbar: [ {xtype: 'label', text: label_CHANGING}, {xtype: 'label', text: label_NO, id: 'lblOperation'} ] }] }); if (queryEntityId && queryEntityId != 'null') { var edDate = Ext.getCmp("edDate"); edDate.setValue(queryRepDate); var edRespondent = Ext.getCmp("edRespondent"); edRespondent.setValue(Number(queryRespondentId)); Ext.Ajax.request({ url: dataUrl + '/core/respondent/getUserRespondentList', method: 'GET', params: { userId: userId }, success: function(response) { var jsonData = JSON.parse(response.responseText); respondentId = jsonData.data[0].id; if (respondentId == Number(queryRespondentId) || respondentId == 0) { var loadMask = new Ext.LoadMask(Ext.getCmp('mainPanel'), {msg: label_LOADING}); loadMask.show(); Ext.Ajax.request({ url: dataUrl + '/core/eav/getEntityData', method: 'GET', params: { entityId: Number(queryEntityId), respondentId: queryRespondentId, metaClassId: queryMetaClassId, date: moment(queryRepDate).local().format('YYYY-MM-DD'), asRoot: true }, success: function(response) { loadMask.hide(); var jsonData = JSON.parse(response.responseText); entityStore.setRootNode(jsonData); Ext.getCmp('entityTreeView').getView().refresh(); }, failure: function(response) { loadMask.hide(); var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } else { Ext.Msg.show({ title: label_ERROR, msg: "У вас нет доступа к данной сущности!", width : 300, buttons: Ext.MessageBox.YES }); queryRespondentId = null; queryMetaClassId = null; queryRepDate = null; } }, failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } else { queryRespondentId = null; queryMetaClassId = null; queryRepDate = null; } }); <file_sep>package kz.bsbnb.usci.model.util; /** * @author <NAME> */ public class TextJson { private Long id; private String code; private String nameRu; private String nameKz; public TextJson() { super(); } public TextJson(Text text) { this.id = text.getId(); this.code = text.getCode(); this.nameKz = text.getNameKz(); this.nameRu = text.getNameRu(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getNameRu() { return nameRu; } public void setNameRu(String nameRu) { this.nameRu = nameRu; } public String getNameKz() { return nameKz; } public void setNameKz(String nameKz) { this.nameKz = nameKz; } } <file_sep>// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.09.02 at 11:19:52 AM ALMT // package kz.bsbnb.usci.wsclient.jaxb.test; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="header"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="guid"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="\{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}\}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="creationDateTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="data"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="contractRegistrationInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="accountingNumber"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="30"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="dateOfRegistration" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="contractPartiesInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="residentInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice> * &lt;element name="bin"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{12}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="iin"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{12}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element name="regionCode"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="nonResidentInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="100"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="countryCode"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[A-Z]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="contractDetailsInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="number"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="100"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="dateOfExecution" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="sum"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;fractionDigits value="2"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="currency"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[A-Z]{3}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="commodityServiceOrMixedSign" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Commodity"/> * &lt;enumeration value="Service"/> * &lt;enumeration value="Mixed"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="termOfRepatriation"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{3}\.[0-9]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="terminationNoticeInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="noticeSentDate" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="contractClosureInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="closureDate" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="closureBasis"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;enumeration value="1"/> * &lt;enumeration value="2"/> * &lt;enumeration value="3"/> * &lt;enumeration value="4"/> * &lt;enumeration value="5"/> * &lt;enumeration value="6"/> * &lt;enumeration value="7"/> * &lt;enumeration value="8"/> * &lt;enumeration value="9"/> * &lt;enumeration value="10"/> * &lt;enumeration value="11"/> * &lt;enumeration value="12"/> * &lt;enumeration value="13"/> * &lt;enumeration value="14"/> * &lt;enumeration value="15"/> * &lt;enumeration value="16"/> * &lt;enumeration value="17"/> * &lt;enumeration value="18"/> * &lt;enumeration value="19"/> * &lt;enumeration value="20"/> * &lt;enumeration value="21"/> * &lt;enumeration value="22"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="note" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="300"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "header", "data" }) @XmlRootElement(name = "ancInfo") public class AncInfo { @XmlElement(required = true) protected AncInfo.Header header; @XmlElement(required = true) protected AncInfo.Data data; /** * Gets the value of the header property. * * @return * possible object is * {@link AncInfo.Header } * */ public AncInfo.Header getHeader() { return header; } /** * Sets the value of the header property. * * @param value * allowed object is * {@link AncInfo.Header } * */ public void setHeader(AncInfo.Header value) { this.header = value; } /** * Gets the value of the data property. * * @return * possible object is * {@link AncInfo.Data } * */ public AncInfo.Data getData() { return data; } /** * Sets the value of the data property. * * @param value * allowed object is * {@link AncInfo.Data } * */ public void setData(AncInfo.Data value) { this.data = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="contractRegistrationInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="accountingNumber"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="30"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="dateOfRegistration" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="contractPartiesInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="residentInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice> * &lt;element name="bin"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{12}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="iin"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{12}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element name="regionCode"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="nonResidentInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="100"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="countryCode"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[A-Z]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="contractDetailsInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="number"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="100"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="dateOfExecution" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="sum"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;fractionDigits value="2"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="currency"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[A-Z]{3}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="commodityServiceOrMixedSign" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Commodity"/> * &lt;enumeration value="Service"/> * &lt;enumeration value="Mixed"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="termOfRepatriation"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{3}\.[0-9]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="terminationNoticeInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="noticeSentDate" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="contractClosureInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="closureDate" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="closureBasis"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;enumeration value="1"/> * &lt;enumeration value="2"/> * &lt;enumeration value="3"/> * &lt;enumeration value="4"/> * &lt;enumeration value="5"/> * &lt;enumeration value="6"/> * &lt;enumeration value="7"/> * &lt;enumeration value="8"/> * &lt;enumeration value="9"/> * &lt;enumeration value="10"/> * &lt;enumeration value="11"/> * &lt;enumeration value="12"/> * &lt;enumeration value="13"/> * &lt;enumeration value="14"/> * &lt;enumeration value="15"/> * &lt;enumeration value="16"/> * &lt;enumeration value="17"/> * &lt;enumeration value="18"/> * &lt;enumeration value="19"/> * &lt;enumeration value="20"/> * &lt;enumeration value="21"/> * &lt;enumeration value="22"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="note" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="300"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "contractRegistrationInfo", "contractPartiesInfo", "contractDetailsInfo", "terminationNoticeInfo", "contractClosureInfo", "note" }) public static class Data { @XmlElement(required = true) protected AncInfo.Data.ContractRegistrationInfo contractRegistrationInfo; @XmlElement(required = true) protected AncInfo.Data.ContractPartiesInfo contractPartiesInfo; @XmlElement(required = true) protected AncInfo.Data.ContractDetailsInfo contractDetailsInfo; protected AncInfo.Data.TerminationNoticeInfo terminationNoticeInfo; protected AncInfo.Data.ContractClosureInfo contractClosureInfo; protected String note; /** * Gets the value of the contractRegistrationInfo property. * * @return * possible object is * {@link AncInfo.Data.ContractRegistrationInfo } * */ public AncInfo.Data.ContractRegistrationInfo getContractRegistrationInfo() { return contractRegistrationInfo; } /** * Sets the value of the contractRegistrationInfo property. * * @param value * allowed object is * {@link AncInfo.Data.ContractRegistrationInfo } * */ public void setContractRegistrationInfo(AncInfo.Data.ContractRegistrationInfo value) { this.contractRegistrationInfo = value; } /** * Gets the value of the contractPartiesInfo property. * * @return * possible object is * {@link AncInfo.Data.ContractPartiesInfo } * */ public AncInfo.Data.ContractPartiesInfo getContractPartiesInfo() { return contractPartiesInfo; } /** * Sets the value of the contractPartiesInfo property. * * @param value * allowed object is * {@link AncInfo.Data.ContractPartiesInfo } * */ public void setContractPartiesInfo(AncInfo.Data.ContractPartiesInfo value) { this.contractPartiesInfo = value; } /** * Gets the value of the contractDetailsInfo property. * * @return * possible object is * {@link AncInfo.Data.ContractDetailsInfo } * */ public AncInfo.Data.ContractDetailsInfo getContractDetailsInfo() { return contractDetailsInfo; } /** * Sets the value of the contractDetailsInfo property. * * @param value * allowed object is * {@link AncInfo.Data.ContractDetailsInfo } * */ public void setContractDetailsInfo(AncInfo.Data.ContractDetailsInfo value) { this.contractDetailsInfo = value; } /** * Gets the value of the terminationNoticeInfo property. * * @return * possible object is * {@link AncInfo.Data.TerminationNoticeInfo } * */ public AncInfo.Data.TerminationNoticeInfo getTerminationNoticeInfo() { return terminationNoticeInfo; } /** * Sets the value of the terminationNoticeInfo property. * * @param value * allowed object is * {@link AncInfo.Data.TerminationNoticeInfo } * */ public void setTerminationNoticeInfo(AncInfo.Data.TerminationNoticeInfo value) { this.terminationNoticeInfo = value; } /** * Gets the value of the contractClosureInfo property. * * @return * possible object is * {@link AncInfo.Data.ContractClosureInfo } * */ public AncInfo.Data.ContractClosureInfo getContractClosureInfo() { return contractClosureInfo; } /** * Sets the value of the contractClosureInfo property. * * @param value * allowed object is * {@link AncInfo.Data.ContractClosureInfo } * */ public void setContractClosureInfo(AncInfo.Data.ContractClosureInfo value) { this.contractClosureInfo = value; } /** * Gets the value of the note property. * * @return * possible object is * {@link String } * */ public String getNote() { return note; } /** * Sets the value of the note property. * * @param value * allowed object is * {@link String } * */ public void setNote(String value) { this.note = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="closureDate" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="closureBasis"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;enumeration value="1"/> * &lt;enumeration value="2"/> * &lt;enumeration value="3"/> * &lt;enumeration value="4"/> * &lt;enumeration value="5"/> * &lt;enumeration value="6"/> * &lt;enumeration value="7"/> * &lt;enumeration value="8"/> * &lt;enumeration value="9"/> * &lt;enumeration value="10"/> * &lt;enumeration value="11"/> * &lt;enumeration value="12"/> * &lt;enumeration value="13"/> * &lt;enumeration value="14"/> * &lt;enumeration value="15"/> * &lt;enumeration value="16"/> * &lt;enumeration value="17"/> * &lt;enumeration value="18"/> * &lt;enumeration value="19"/> * &lt;enumeration value="20"/> * &lt;enumeration value="21"/> * &lt;enumeration value="22"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "closureDate", "closureBasis" }) public static class ContractClosureInfo { @XmlElement(required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar closureDate; @XmlElement(required = true) protected BigDecimal closureBasis; /** * Gets the value of the closureDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getClosureDate() { return closureDate; } /** * Sets the value of the closureDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setClosureDate(XMLGregorianCalendar value) { this.closureDate = value; } /** * Gets the value of the closureBasis property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getClosureBasis() { return closureBasis; } /** * Sets the value of the closureBasis property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setClosureBasis(BigDecimal value) { this.closureBasis = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="number"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="100"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="dateOfExecution" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="sum"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;fractionDigits value="2"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="currency"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[A-Z]{3}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="commodityServiceOrMixedSign" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Commodity"/> * &lt;enumeration value="Service"/> * &lt;enumeration value="Mixed"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="termOfRepatriation"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{3}\.[0-9]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "number", "dateOfExecution", "sum", "currency", "commodityServiceOrMixedSign", "termOfRepatriation" }) public static class ContractDetailsInfo { @XmlElement(required = true) protected String number; @XmlElement(required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar dateOfExecution; @XmlElement(required = true) protected BigDecimal sum; @XmlElement(required = true) protected String currency; protected String commodityServiceOrMixedSign; @XmlElement(required = true) protected String termOfRepatriation; /** * Gets the value of the number property. * * @return * possible object is * {@link String } * */ public String getNumber() { return number; } /** * Sets the value of the number property. * * @param value * allowed object is * {@link String } * */ public void setNumber(String value) { this.number = value; } /** * Gets the value of the dateOfExecution property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDateOfExecution() { return dateOfExecution; } /** * Sets the value of the dateOfExecution property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDateOfExecution(XMLGregorianCalendar value) { this.dateOfExecution = value; } /** * Gets the value of the sum property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getSum() { return sum; } /** * Sets the value of the sum property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setSum(BigDecimal value) { this.sum = value; } /** * Gets the value of the currency property. * * @return * possible object is * {@link String } * */ public String getCurrency() { return currency; } /** * Sets the value of the currency property. * * @param value * allowed object is * {@link String } * */ public void setCurrency(String value) { this.currency = value; } /** * Gets the value of the commodityServiceOrMixedSign property. * * @return * possible object is * {@link String } * */ public String getCommodityServiceOrMixedSign() { return commodityServiceOrMixedSign; } /** * Sets the value of the commodityServiceOrMixedSign property. * * @param value * allowed object is * {@link String } * */ public void setCommodityServiceOrMixedSign(String value) { this.commodityServiceOrMixedSign = value; } /** * Gets the value of the termOfRepatriation property. * * @return * possible object is * {@link String } * */ public String getTermOfRepatriation() { return termOfRepatriation; } /** * Sets the value of the termOfRepatriation property. * * @param value * allowed object is * {@link String } * */ public void setTermOfRepatriation(String value) { this.termOfRepatriation = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="residentInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice> * &lt;element name="bin"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{12}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="iin"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{12}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element name="regionCode"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="nonResidentInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="100"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="countryCode"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[A-Z]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "residentInfo", "nonResidentInfo" }) public static class ContractPartiesInfo { @XmlElement(required = true) protected AncInfo.Data.ContractPartiesInfo.ResidentInfo residentInfo; @XmlElement(required = true) protected AncInfo.Data.ContractPartiesInfo.NonResidentInfo nonResidentInfo; /** * Gets the value of the residentInfo property. * * @return * possible object is * {@link AncInfo.Data.ContractPartiesInfo.ResidentInfo } * */ public AncInfo.Data.ContractPartiesInfo.ResidentInfo getResidentInfo() { return residentInfo; } /** * Sets the value of the residentInfo property. * * @param value * allowed object is * {@link AncInfo.Data.ContractPartiesInfo.ResidentInfo } * */ public void setResidentInfo(AncInfo.Data.ContractPartiesInfo.ResidentInfo value) { this.residentInfo = value; } /** * Gets the value of the nonResidentInfo property. * * @return * possible object is * {@link AncInfo.Data.ContractPartiesInfo.NonResidentInfo } * */ public AncInfo.Data.ContractPartiesInfo.NonResidentInfo getNonResidentInfo() { return nonResidentInfo; } /** * Sets the value of the nonResidentInfo property. * * @param value * allowed object is * {@link AncInfo.Data.ContractPartiesInfo.NonResidentInfo } * */ public void setNonResidentInfo(AncInfo.Data.ContractPartiesInfo.NonResidentInfo value) { this.nonResidentInfo = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="100"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="countryCode"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[A-Z]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "name", "countryCode" }) public static class NonResidentInfo { @XmlElement(required = true) protected String name; @XmlElement(required = true) protected String countryCode; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the countryCode property. * * @return * possible object is * {@link String } * */ public String getCountryCode() { return countryCode; } /** * Sets the value of the countryCode property. * * @param value * allowed object is * {@link String } * */ public void setCountryCode(String value) { this.countryCode = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice> * &lt;element name="bin"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{12}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="iin"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{12}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element name="regionCode"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[0-9]{2}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "bin", "iin", "regionCode" }) public static class ResidentInfo { protected String bin; protected String iin; @XmlElement(required = true) protected String regionCode; /** * Gets the value of the bin property. * * @return * possible object is * {@link String } * */ public String getBin() { return bin; } /** * Sets the value of the bin property. * * @param value * allowed object is * {@link String } * */ public void setBin(String value) { this.bin = value; } /** * Gets the value of the iin property. * * @return * possible object is * {@link String } * */ public String getIin() { return iin; } /** * Sets the value of the iin property. * * @param value * allowed object is * {@link String } * */ public void setIin(String value) { this.iin = value; } /** * Gets the value of the regionCode property. * * @return * possible object is * {@link String } * */ public String getRegionCode() { return regionCode; } /** * Sets the value of the regionCode property. * * @param value * allowed object is * {@link String } * */ public void setRegionCode(String value) { this.regionCode = value; } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="accountingNumber"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="30"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="dateOfRegistration" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "accountingNumber", "dateOfRegistration" }) public static class ContractRegistrationInfo { @XmlElement(required = true) protected String accountingNumber; @XmlElement(required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar dateOfRegistration; /** * Gets the value of the accountingNumber property. * * @return * possible object is * {@link String } * */ public String getAccountingNumber() { return accountingNumber; } /** * Sets the value of the accountingNumber property. * * @param value * allowed object is * {@link String } * */ public void setAccountingNumber(String value) { this.accountingNumber = value; } /** * Gets the value of the dateOfRegistration property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDateOfRegistration() { return dateOfRegistration; } /** * Sets the value of the dateOfRegistration property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDateOfRegistration(XMLGregorianCalendar value) { this.dateOfRegistration = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="noticeSentDate" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "noticeSentDate" }) public static class TerminationNoticeInfo { @XmlElement(required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar noticeSentDate; /** * Gets the value of the noticeSentDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getNoticeSentDate() { return noticeSentDate; } /** * Sets the value of the noticeSentDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setNoticeSentDate(XMLGregorianCalendar value) { this.noticeSentDate = value; } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="guid"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="\{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}\}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="creationDateTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "guid", "creationDateTime" }) public static class Header { @XmlElement(required = true) protected String guid; @XmlElement(required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationDateTime; /** * Gets the value of the guid property. * * @return * possible object is * {@link String } * */ public String getGuid() { return guid; } /** * Sets the value of the guid property. * * @param value * allowed object is * {@link String } * */ public void setGuid(String value) { this.guid = value; } /** * Gets the value of the creationDateTime property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCreationDateTime() { return creationDateTime; } /** * Sets the value of the creationDateTime property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreationDateTime(XMLGregorianCalendar value) { this.creationDateTime = value; } } } <file_sep>package kz.bsbnb.usci.brms.model; import kz.bsbnb.usci.model.persistence.Persistable; import java.io.Serializable; import java.time.LocalDate; /** * @author <NAME> */ public class Rule extends Persistable implements Serializable { private static final long serialVersionUID = 1L; private String rule; private String title; private boolean isActive; private LocalDate openDate; private LocalDate closeDate; public Rule() { super(); } public Rule(long ruleId, LocalDate date) { this.id = ruleId; this.openDate = date; } public Rule(String title, String rule) { this.title = title; this.rule = rule; } public Rule(String title, String rule, LocalDate openDate) { this.title = title; this.rule = rule; this.openDate = openDate; } public Rule(String rule) { this.rule = rule; } public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isActive() { return isActive; } public void setIsActive(boolean isActive) { this.isActive = isActive; } public LocalDate getOpenDate() { return openDate; } public void setOpenDate(LocalDate openDate) { this.openDate = openDate; } public LocalDate getCloseDate() { return closeDate; } public void setCloseDate(LocalDate closeDate) { this.closeDate = closeDate; } } <file_sep>var label_ERROR = 'Ошибка'; var label_CRED = 'Респонденты'; var label_PROCCESING = 'Идет формирование межформенного контроля…'; var label_EXCEL = 'Выгрузить в Excel'; var label_CROSSCHECK = 'Межформенный контроль'; var label_ORG_NAME = 'Наименование организации'; var label_BEG_DATE = 'Дата начало контроля'; var label_END_DATE = 'Дата завершения контроля'; var label_STATUS = 'Статус'; var label_USER = 'Пользователь'; var label_PARAMETR = 'Показатель'; var label_VALUE_KR = 'Значение в АИС ЕССП'; var label_OUT_VALUE = 'Значение во внешнем источнике'; var label_DIFF = 'Расхождение'; var label_ORGS = 'Организаций'; var label_R = 'Банк развития'; var label_VU = 'Банк второго уровня'; var label_PU = 'Банк первого уровня'; var label_IO = 'Ипотечная организация'; var label_OTHER = 'Прочие организации, осуществляющие отдельные виды банковских операций'; var label_SELECT_ALL = 'Выбрать все'; var label_OFF_SELECTED = 'Снять выделение'; var label_ALL = 'Выделить все'; var label_SHOW = 'Показать'; var label_START = 'Запуск межформенного контроля'; var label_DATA = 'Данные по контролю'; <file_sep>package kz.bsbnb.usci.util.controller; import kz.bsbnb.usci.model.util.Text; import kz.bsbnb.usci.util.service.TextService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author <NAME> */ @RestController @RequestMapping(value = "/text") public class TextController { private final TextService textService; public TextController(TextService textService) { this.textService = textService; } @GetMapping(value = "/getTextListByType") public List<Text> getTextListByType(@RequestParam List<String> types) { return textService.getTextListByType(types); } @GetMapping(value = "/getTextById") public Text getTextById(@RequestParam(name = "id") Long id) { return textService.getText(id); } } <file_sep>var label_ERROR = 'Ошибка'; var label_ORGANIZATIONS = 'Организации'; var label_DEV = 'Банк Развития'; var label_VU = 'Банк второго уровня'; var label_PU = 'Банк первого уровня'; var label_IO = 'Ипотечная организация'; var label_OTHERS = 'Прочие организации, осуществляющие отдельные виды банковских операций'; var label_SELECT = 'Выбрать все'; var label_OFF_SELECTED = 'Снять выделение'; var label_NO_DATA = 'Нет данных для отображения'; var label_CHOOSE = 'Выделить все'; var label_REP_DATE = 'Отчетная дата'; var label_SHOW = 'Показать'; var label_FILE_INFO = 'Информация о файлах'; var label_ORG_NAME = 'Наименование организации'; var label_FILE_NAME = 'Имя файла'; var label_PRODUCT = 'Продукт'; var label_STATUS = 'Статус'; var label_EDITED = 'Обработанные'; var label_SUC_EDITED = 'Успешно обработанные'; var label_ERR_EDITED = 'Обработанные с ошибками'; var label_DATE_REP = 'Дата отчета'; var label_RECIEPED = 'Дата получения'; var label_DATE_BEGINING = 'Дата начала обработки'; var label_DATE_END = 'Дата завершения'; var label_PAGE = 'Страница'; var label_FILES = 'Файлы {0} - {1} из {2}'; var label_NO_DATA_SIG = 'Нет данных'; var label_FIRST = 'Первая страница'; var label_LAST = 'Последняя страница'; var label_NEXT = 'Следующая страница'; var label_PREVIOUS = 'Предыдущая страница'; var label_REFRESH = 'Обновить'; var label_EXCEL = 'Выгрузить таблицу в Excel'; var label_WAIT = 'Подождите...'; var label_NO_D = 'нет данных'; var label_SIGN_FILE = 'Файл подписан: '; var label_ERRORS = 'Ошибки пакетных файлов'; var label_NOTE_TYPE = 'Тип записи'; var label_ID_ENTITY = 'ID cущности'; var label_ENTITY = 'Сущность'; var label_TYPE_OPER = 'Тип операции'; var label_MESSAGE = 'Сообщение'; var label_COMMENT = 'Комментарий'; var label_PROTOCOLS = 'Протоколы {0} - {1} из {2}'; var label_XML_FORMAT = 'Загрузить данные в формате XML'; var label_DOWN_ERRORS = 'Загрузить сущности с ошибками'; var label_CRITIC = 'Степень критичности'; <file_sep>package kz.bsbnb.usci.wsclient.dao; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.util.SqlJdbcConverter; import kz.bsbnb.usci.util.json.ext.ExtJsList; import kz.bsbnb.usci.wsclient.model.ctrkgd.Request; import kz.bsbnb.usci.wsclient.model.ctrkgd.RequestStatus; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; @Repository public class KGDDaoImpl implements KGDDao { private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; private final SimpleJdbcInsert requestInsert; public KGDDaoImpl(NamedParameterJdbcTemplate npJdbcTemplate, JdbcTemplate jdbcTemplate) { this.npJdbcTemplate = npJdbcTemplate; this.jdbcTemplate = jdbcTemplate; this.requestInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_WS") .withTableName("CTR_KGD") .usingColumns("REPORT_DATE", "STATUS_ID", "REQUEST_BODY", "RESPONSE_BODY", "ENTITIES_COUNT", "REQUEST_ID") .usingGeneratedKeyColumns("ID"); } @Override public List<Map<String, Object>> entityRows(LocalDate reportDate) { return npJdbcTemplate.queryForList("select t.curr_trans_date, t.reference, t.cont_sum, t.cont_num, t.cont_date, t.cont_reg_num ,\n" + " (select r.code_alpha_2 from eav_data.ref_country r, eav_data.ctr_subject c \n" + " where r.entity_id = c.ref_country_id\n" + " and c.entity_id = t.beneficiary_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as beneficiary_country_code ,\n" + " (select r.code from eav_data.ref_residency r, eav_data.ctr_subject c \n" + " where r.entity_id = c.ref_residency_id\n" + " and c.entity_id = t.beneficiary_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as beneficiary_residency_code ,\n" + " (select c.name from eav_data.ctr_subject c \n" + " where c.entity_id = t.beneficiary_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as beneficiary_name , \n" + //" (select c.bin_iin_id from eav_data.ctr_subject c \n" + " (select c.bin_iin from eav_data.ctr_subject c \n" + " where c.entity_id = t.beneficiary_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as beneficiary_biniin , --надо поменять bin_iin_id на bin_iin\n" + " (select r.code from eav_data.ref_econ_sector r, eav_data.ctr_subject c \n" + " where r.entity_id = c.ref_econ_sector_id\n" + " and c.entity_id = t.beneficiary_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as beneficiary_econ_sector_code , \n" + " (select r.code_alpha_2 from eav_data.ref_country r, eav_data.ctr_subject c \n" + " where r.entity_id = c.ref_country_id\n" + " and c.entity_id = t.sender_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as sender_country_code ,\n" + " (select r.code from eav_data.ref_residency r, eav_data.ctr_subject c \n" + " where r.entity_id = c.ref_residency_id\n" + " and c.entity_id = t.sender_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as sender_residency_code ,\n" + " (select c.name from eav_data.ctr_subject c \n" + " where c.entity_id = t.sender_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as sender_name , \n" + //" (select c.bin_iin_id from eav_data.ctr_subject c \n" + " (select c.bin_iin from eav_data.ctr_subject c \n" + " where c.entity_id = t.sender_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as sender_biniin , --надо поменять bin_iin_id на bin_iin\n" + " (select r.code from eav_data.ref_econ_sector r, eav_data.ctr_subject c \n" + " where r.entity_id = c.ref_econ_sector_id\n" + " and c.entity_id = t.sender_id\n" + " and c.report_date = (Select max(report_date)\n" + " from eav_data.ctr_subject cs2\n" + " where cs2.entity_id = c.entity_id\n" + " and cs2.report_date <= t.report_date)) as sender_econ_sector_code ,\n" + " (select r.code from eav_data.ref_curr_trans_ppc r\n" + " where r.entity_id = t.ref_curr_trans_ppc_id\n" + " and r.report_date = (Select max(report_date)\n" + " from eav_data.ref_curr_trans_ppc cs2\n" + " where cs2.entity_id = r.entity_id\n" + " and cs2.report_date <= t.report_date)) as curr_trans_ppc_code ,\n" + " (select r.code from eav_data.ref_currency r\n" + " where r.entity_id = t.ref_currency_id\n" + " and r.report_date = (Select max(report_date)\n" + " from eav_data.ref_currency cs2\n" + " where cs2.entity_id = r.entity_id\n" + " and cs2.report_date <= t.report_date)) as currency_code ,\n" + " (select r.short_name from eav_data.ref_currency r\n" + " where r.entity_id = t.ref_currency_id\n" + " and r.report_date = (Select max(report_date)\n" + " from eav_data.ref_currency cs2\n" + " where cs2.entity_id = r.entity_id\n" + " and cs2.report_date <= t.report_date)) as currency_name ----надо поменять name_ru на short_name\n" + " from eav_data.ctr_transaction t , reporter.v_currency_usd_tg cur\n" + " where t.cont_date is not null \n" + " and t.ref_corp_money_trans_id = 1 \n" + " and t.ref_curr_trans_code_id in (1,2,3,15,8,14,11,6,5,4,17,22,18,13,12,10,25,9,20,7,19,16,24,27,30,21,28,31,23,26,29,34,33,32,42,43,45,46,48,49,50,51,52,57,58)\n" + " and t.entity_id = cur.entity_id\n" + " and (t.cont_sum * cur.course_curr /cur.corellation/ cur.course_usd) > 50\n" + " and t.report_date = (Select max(report_date)\n" + " from eav_data.ctr_transaction t2\n" + " where t2.entity_id = t.entity_id\n" + " and t2.report_date <= t.report_date)\n" + " and not exists (select *\n" + " from eav_data.ctr_transaction ctr3\n" + " where ctr3.entity_id = t.entity_id\n" + " and ctr3.creditor_id = t.creditor_id\n" + " and ctr3.operation_id = 3)\n" + " and t.report_date = :REPORT_DATE" + " and t.system_date < to_date('14.10.2019','dd.mm.yyyy')", new MapSqlParameterSource("REPORT_DATE", SqlJdbcConverter.convertToSqlDate(reportDate))); } @Override public void insertRequest(Request request) { MapSqlParameterSource params = new MapSqlParameterSource() .addValue("REPORT_DATE", SqlJdbcConverter.convertToSqlDate(request.getReportDate())) .addValue("STATUS_ID", request.getRequestStatus().getId()) .addValue("REQUEST_BODY", request.getRequestBody()) .addValue("RESPONSE_BODY", request.getResponseBody()) .addValue("ENTITIES_COUNT", request.getEntitiesCount()) .addValue("REQUEST_ID", request.getRequestId()); int count = requestInsert.execute(params); if (count != 1) throw new UsciException("Ошибка insert записи в таблицу USCI_WS.CTR_KGD"); } @Override public void updateRequest(Request request) { int count = npJdbcTemplate.update("update USCI_WS.CTR_KGD\n" + " set STATUS_ID = :STATUS_ID, ENTITIES_COUNT = :ENTITIES_COUNT, REQUEST_BODY = :REQUEST_BODY, " + " RESPONSE_BODY = :RESPONSE_BODY, REQUEST_ID = :REQUEST_ID\n" + " where ID = :ID", new MapSqlParameterSource("ID", request.getId()) .addValue("STATUS_ID", request.getRequestStatus().getId()) .addValue("REQUEST_BODY", request.getRequestBody()) .addValue("RESPONSE_BODY", request.getResponseBody()) .addValue("ENTITIES_COUNT", request.getEntitiesCount()) .addValue("REQUEST_ID", request.getRequestId())); if (count != 1) throw new UsciException("Ошибка update записи в таблице USCI_WS.CTR_KGD"); } @Override public List<Request> getCtrRequestList(LocalDate reportDate) { List<Request> requestList = new ArrayList<>(); String query = "select * from USCI_WS.CTR_KGD\n"; if (reportDate != null) query += " where REPORT_DATE = :REPORT_DATE\n"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("REPORT_DATE", SqlJdbcConverter.convertToSqlDate(reportDate)); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); if (rows.isEmpty()) return Collections.emptyList(); for (Map<String, Object> row : rows) { Request request = getRequestFromJdbcMap(row); requestList.add(request); } return requestList; } private Request getRequestFromJdbcMap(Map<String, Object> row) { Request request = new Request(); request.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); request.setReportDate(SqlJdbcConverter.convertToLocalDate(row.get("REPORT_DATE"))); request.setRequestStatus(RequestStatus.getRequestStatus(SqlJdbcConverter.convertToLong(row.get("STATUS_ID")))); request.setRequestBody(String.valueOf(row.get("REQUEST_BODY"))); request.setResponseBody(String.valueOf(row.get("RESPONSE_BODY"))); request.setEntitiesCount(SqlJdbcConverter.convertToLong(row.get("ENTITIES_COUNT"))); return request; } } <file_sep>package kz.bsbnb.usci.eav; import kz.bsbnb.usci.eav.model.meta.MetaAttribute; import kz.bsbnb.usci.eav.model.meta.MetaType; import kz.bsbnb.usci.eav.model.meta.MetaValue; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.util.SqlJdbcConverter; /** * @author <NAME> */ public class EavSqlConverter { /** * метод конвертирует значение sql jdbc формата в формат java eav (удобный нам формат) * пояснения: BOOLEAN в таблицах БД хранится в формате varchar2(1) * дата конвертируется из java.sql.Timestamp в LocalDate * числа хранятся в БД как NUMBER, конвертируются из BigDecimal в Long, Double и тд * String получаем как есть (varchar2) * */ public static Object convertSqlValueToJavaType(MetaAttribute attribute, Object sqlValue) { MetaType metaType = attribute.getMetaType(); if (metaType.isComplex() || metaType.isSet()) throw new UsciException("Метод предназначен только для конвертаций примитивных типов данных"); if (sqlValue == null) throw new UsciException("Ошибка значения NULL"); Object javaValue; MetaValue metaValue = (MetaValue) metaType; switch (metaValue.getMetaDataType()) { case DATE: javaValue = SqlJdbcConverter.convertToLocalDate((java.sql.Timestamp)sqlValue); break; case DATE_TIME: javaValue = SqlJdbcConverter.convertToLocalDateTime((java.sql.Timestamp)sqlValue); break; case BOOLEAN: javaValue = sqlValue.equals("1")? Boolean.TRUE: Boolean.FALSE; break; case DOUBLE: javaValue = SqlJdbcConverter.convertToDouble(sqlValue); break; case INTEGER: javaValue = SqlJdbcConverter.convertToInt(sqlValue); break; case STRING: javaValue = sqlValue; break; default: throw new UsciException("Не верный тип мета данных"); } return javaValue; } } <file_sep>package kz.bsbnb.usci.core.service; import kz.bsbnb.usci.core.dao.SubjectDao; import kz.bsbnb.usci.model.respondent.SubjectType; import kz.bsbnb.usci.model.util.Text; import kz.bsbnb.usci.util.client.TextClient; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author <NAME> */ @Service public class SubjectServiceImpl implements SubjectService { private final TextClient textClient; private final SubjectDao subjectDao; public SubjectServiceImpl(TextClient textClient, SubjectDao subjectDao) { this.textClient = textClient; this.subjectDao = subjectDao; } @Override public String getSubjectTypeProductPeriod(Long subjectTypeId, Long productId) { Long periodId = subjectDao.getSubjectTypeProductPeriod(subjectTypeId, productId); List<Text> periodTypes = textClient.getTextListByType(Collections.singletonList("PERIOD_TYPE")); Map<Long, Text> periodTypesMap = periodTypes.stream() .collect(Collectors.toMap(Text::getId, o -> o)); return periodTypesMap.get(periodId).getNameRu(); } @Override public List<SubjectType> getSubjectTypeList() { return subjectDao.getSubjectTypeList(); } @Override public void updateSubjectTypeProductPeriod(Long subjectTypeId, Long productId, Long periodId) { subjectDao.updateSubjectTypeProductPeriod(subjectTypeId, productId, periodId); } } <file_sep>package kz.bsbnb.usci.eav.model.base; import java.io.Serializable; /** * Реестр сущностей * Все сущности когда либо созданные хранятся в таблице EAV_ENTITY * @author <NAME> */ public class BaseEntityRegistry implements Cloneable, Serializable { private static final long serialVersionUID = 1L; private Long respondentId; private Long metaClassId; private Long entityId; private Long parentEntityId; private Long parentClassId; public BaseEntityRegistry() { /*Пустой конструктор*/ } public BaseEntityRegistry(BaseEntity baseEntity) { this.entityId = baseEntity.getId(); this.respondentId = baseEntity.getRespondentId(); this.metaClassId = baseEntity.getMetaClass().getId(); this.parentEntityId = baseEntity.parentIsKey()? baseEntity.getParentEntity().getId(): 0L; this.parentClassId = baseEntity.parentIsKey()? baseEntity.getParentEntity().getMetaClass().getId(): 0L; } public Long getRespondentId() { return respondentId; } public BaseEntityRegistry setRespondentId(Long respondentId) { this.respondentId = respondentId; return this; } public Long getMetaClassId() { return metaClassId; } public BaseEntityRegistry setMetaClassId(Long metaClassId) { this.metaClassId = metaClassId; return this; } public Long getEntityId() { return entityId; } public BaseEntityRegistry setEntityId(Long entityId) { this.entityId = entityId; return this; } public Long getParentEntityId() { return parentEntityId; } public BaseEntityRegistry setParentEntityId(Long parentEntityId) { this.parentEntityId = parentEntityId; return this; } public Long getParentClassId() { return parentClassId; } public BaseEntityRegistry setParentClassId(Long parentClassId) { this.parentClassId = parentClassId; return this; } @Override public String toString() { return "BaseEntityRegistry{" + "respondentId=" + respondentId + ", metaClassId=" + metaClassId + ", entityId=" + entityId + ", parentEntityId=" + parentEntityId + ", parentClassId=" + parentClassId + '}'; } } <file_sep>var label_TITLE = 'Загрузка файлов'; var label_INFO = 'Перетащите файлы в эту область или выберите нажав кнопку "Выбрать файлы..."'; var label_UPLOADED = 'Загружено'; var label_ERROR = 'Ошибка: '; var label_INFO_NO = 'Нет доступа к загрузке'; var label_FILE_NAME = 'Название файла'; var label_FILE_SIZE = 'Размер файла'; var label_STATUS = 'Статус'; var label_READY = 'Готов к загрузке'; var label_UPLOADING = 'Загружается'; var label_UPLOADED = 'Загружено'; var label_MAIN_ERROR = 'Ошибка'; var label_CHOOSE = 'Выбрать файлы…'; var label_TO_UPLOAD = 'Загрузить'; var label_DELETE_ALL = 'Удалить все файлы'; var label_DELETE_UPLOAD = 'Удалить загруженные файлы'; var label_DELETE_CHOSEN = 'Удалить выбранные файлы'; var label_EDS = 'Цифровая подпись'; var label_SENDING = 'Отправлять с использованием цифровой подписи'; var label_DATE_SETTING = 'Настройка первой отчетной даты'; var label_ORGANIZATION = 'Организация'; <file_sep>/** * @author <NAME> */ Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.selection.CellModel', 'Ext.grid.*', 'Ext.data.*' ]); function showProductWindow(productId) { if (productId) { Ext.Ajax.request({ url: dataUrl + '/core/product/getProductJsonById', method: 'GET', params: { id: productId }, success: function(response) { var productData = JSON.parse(response.responseText); createProductWindow(productData); } }); } else { createProductWindow({}); } } function createProductWindow(productData) { var buttonSave = Ext.create('Ext.button.Button', { hidden: !isDataManager, text: label_SAVE, handler: function() { var form = Ext.getCmp('formProduct').getForm(); if (!form.isValid()) { Ext.Msg.alert({ title: label_ERROR, msg: label_FIELDS }); return; } var formValues = form.getValues(); var tempProductData = { id: productData.id, code: formValues.code, name: formValues.name, crosscheckPackageName: formValues.crosscheckPackageName }; var loadMask = new Ext.LoadMask(Ext.getBody(), { msg: label_SAVING }); loadMask.show(); Ext.Ajax.request({ url: dataUrl + '/core/product/saveProduct', method: 'POST', waitMsg: label_SAVING, jsonData: tempProductData, reader: { type: 'json', root: 'data' }, success: function(response, opts) { loadMask.hide(); Ext.getCmp('windowProduct').destroy(); var productGrid = Ext.getCmp('productGrid'); // перегружаем весь грид чтобы отобразить изменения productGrid.getStore().load(); productGrid.getView().refresh(); }, failure: function(response, opts) { loadMask.hide(); var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } }); var buttonClose = Ext.create('Ext.button.Button', { text: label_CANCEL, handler : function() { Ext.getCmp('windowProduct').destroy(); } }); var formProduct = Ext.create('Ext.form.Panel', { id: 'formProduct', width: 520, height: 160, fieldDefaults: { msgTarget: 'side' }, defaults: { anchor: '100%' }, defaultType: 'textfield', bodyPadding: '5 5 0', items: [ { fieldLabel: 'Код', name: 'code', allowBlank: false, readOnly: productData.id != null }, { fieldLabel: label_NAME, name: 'name', allowBlank: false }, { fieldLabel: 'Название пакета межформенного контроля', name: 'crosscheckPackageName', allowBlank: false }], buttons: [buttonSave, buttonClose] }); var form = formProduct.getForm(); form.setValues(productData); var windowProduct = new Ext.Window({ id: 'windowProduct', layout: 'fit', title: label_PRODUCT, modal: true, maximizable: true, items: [formProduct] }); windowProduct.show(); } function loadMetaClasses() { // if (!isNb) // return; var productGrid = Ext.getCmp('productGrid'); var productId = productGrid.getSelectionModel().getLastSelected().data.id; var metaClassSelGrid = Ext.getCmp('metaClassSelGrid'); var metaClassAvlGrid = Ext.getCmp('metaClassAvlGrid'); metaClassSelGrid.store.load({ params: { productId: productId, available: false } }); metaClassAvlGrid.store.load({ params: { productId: productId, available: true } }); metaClassSelGrid.getView().refresh(); metaClassAvlGrid.getView().refresh(); } function loadPositions() { // if (!isNb) // return; var productGrid = Ext.getCmp('productGrid'); var productId = productGrid.getSelectionModel().getLastSelected().data.id; var positionSelGrid = Ext.getCmp('positionSelGrid'); var positionAvlGrid = Ext.getCmp('positionAvlGrid'); positionSelGrid.store.load({ params: { productId: productId, available: false } }); positionAvlGrid.store.load({ params: { productId: productId, available: true } }); positionSelGrid.getView().refresh(); positionAvlGrid.getView().refresh(); } Ext.onReady(function() { Ext.override(Ext.data.proxy.Ajax, {timeout: 1200000}); Ext.define('productModel', { extend: 'Ext.data.Model', fields: ['id', 'code', 'name'] }); Ext.define('metaClassModel', { extend: 'Ext.data.Model', fields: ['id', 'name', 'title'] }); Ext.define('positionModel', { extend: 'Ext.data.Model', fields: ['id', 'nameRu'] }); Ext.define('iterationModel', { extend: 'Ext.data.Model', fields: ['iterationNumber', 'month', 'day', 'hour', 'min', 'dayTransfer'] }); var productStore = Ext.create('Ext.data.Store', { id: 'productStore', model: 'productModel', autoLoad: true, listeners: { load: function (me, records, options) { productGrid.getSelectionModel().select(0); loadMetaClasses(); loadPositions(); if (records.length > 0) Ext.getCmp('comboProducts').setValue(records[0].get('id')); }, scope: this }, proxy: { type: 'ajax', url: dataUrl + '/core/product/getProductList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } }, }); var metaClassSelStore = Ext.create('Ext.data.Store', { id: 'metaClassSelStore', model: 'metaClassModel', pageSize: 100, proxy: { type: 'ajax', url: dataUrl + '/core/product/getMetaClasses', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } } }); var metaClassAvlStore = Ext.create('Ext.data.Store', { id: 'metaClassAvlStore', model: 'metaClassModel', pageSize: 100, proxy: { type: 'ajax', url: dataUrl + '/core/product/getMetaClasses', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } } }); var positionSelStore = Ext.create('Ext.data.Store', { id: 'positionSelStore', model: 'positionModel', pageSize: 100, proxy: { type: 'ajax', url: dataUrl + '/core/product/getPositions', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } } }); var positionAvlStore = Ext.create('Ext.data.Store', { id: 'positionAvlStore', model: 'positionModel', pageSize: 100, proxy: { type: 'ajax', url: dataUrl + '/core/product/getPositions', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } } }); var buttonDownloadXsd = Ext.create('Ext.button.Button', { text: label_DOWN, handler: function() { var productGrid = Ext.getCmp('productGrid'); var productData = productGrid.getSelectionModel().getLastSelected().data; var xhr = new XMLHttpRequest(); xhr.open('GET', dataUrl + '/core/product/getProductXsd?productId=' + productData.id); xhr.responseType = 'arraybuffer'; xhr.onload = function (oEvent) { var responseArray = new Uint8Array(this.response); var blob = new Blob([responseArray], {type: 'application/xsd'}); var fileName = productData.code + '.xsd'; saveAs(blob, fileName); }; xhr.send(); } }); var buttonGenerateXsd = Ext.create('Ext.button.Button', { hidden: !isDataManager, text: label_XSD, //hidden: !isNb, handler: function() { var loadMask = new Ext.LoadMask(Ext.getBody(), { msg: label_XSDING }); loadMask.show(); Ext.Ajax.request({ url: dataUrl + '/core/product/generateXsd', waitMsg: label_XSDING, method: 'POST', success: function(response, opts) { loadMask.hide(); Ext.Msg.alert(label_INFO, label_XSD_END); }, failure: function(response, opts) { loadMask.hide(); var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } }); var productGrid = Ext.create('Ext.grid.Panel', { id: 'productGrid', store: productStore, region: 'west', // width: isNb? '40%': '100%', width: '40%', minSize: 50, split: true, columns: [ { text: label_CODE, dataIndex: 'code', flex: 1 }, { text: label_NAME, dataIndex: 'name', flex: 2 } ], listeners: { cellclick: function(grid, td, cellIndex, newValue, tr, rowIndex, e, eOpts) { loadMetaClasses(); loadPositions(); }, itemdblclick: function(dv, record, item, index, e) { // if (!isNb) // return; showProductWindow(Number(record.get('id'))); } }, tbar: [ { text: label_ADD, hidden: !isDataManager, //hidden: !isNb, handler: function(e1, e2) { showProductWindow(); } }, { xtype: 'tbseparator' }, buttonDownloadXsd, { xtype: 'tbseparator', // hidden: isNb }, buttonGenerateXsd ] }); var metaClassSelGrid = Ext.create('Ext.grid.Panel', { id: 'metaClassSelGrid', store: metaClassSelStore, viewConfig: { emptyText: label_NO_DATA }, columns: [ { text: label_CODE, dataIndex: 'name', flex: 1 }, { text: label_NAME, dataIndex: 'title', flex: 2 } ], }); var metaClassAvlGrid = Ext.create('Ext.grid.Panel', { id: 'metaClassAvlGrid', store: metaClassAvlStore, viewConfig: { emptyText: label_NO_DATA }, columns: [ { text: label_CODE, dataIndex: 'name', flex: 1 }, { text: label_NAME, dataIndex: 'title', flex: 2 } ] }); var positionSelGrid = Ext.create('Ext.grid.Panel', { id: 'positionSelGrid', store: positionSelStore, viewConfig: { emptyText: label_NO_DATA }, columns: [ { text: label_CODE, dataIndex: 'nameRu', flex: 1 } ], }); var positionAvlGrid = Ext.create('Ext.grid.Panel', { id: 'positionAvlGrid', store: positionAvlStore, viewConfig: { emptyText: label_NO_DATA }, columns: [ { text: label_CODE, dataIndex: 'nameRu', flex: 1 } ] }); var buttonAddMetaClass = Ext.create('Ext.button.Button', { id: 'buttonAddMetaClass', hidden: !isDataManager, text: label_ADD, //icon: contextPathUrl + '/icons/down_1.png', flex: 1, handler: function() { if (!metaClassAvlGrid.getSelectionModel().hasSelection() || !productGrid.getSelectionModel().hasSelection()) return; var metaIds = []; for (var i = 0; i < metaClassAvlGrid.store.getCount(); i++) { if (metaClassAvlGrid.getSelectionModel().isSelected(i)) { metaIds.push(metaClassAvlGrid.store.getAt(i).data.id); } } var productData = productGrid.getSelectionModel().getLastSelected().data; Ext.Ajax.request({ url: dataUrl + '/core/product/addProductMetaClass', method: 'PUT', params: { productId: productData.id, metaIds: metaIds }, reader: { type: 'json', root: '' }, success: function() { loadMetaClasses(); }, failure: function(response, opts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } }); var buttonDeleteMetaClass = Ext.create('Ext.button.Button', { id: 'buttonDeleteMetaClass', flex: 1, hidden: !isDataManager, //icon: contextPathUrl + '/icons/up_1.png', text: label_DELETE, handler: function() { if (!metaClassSelGrid.getSelectionModel().hasSelection() || !productGrid.getSelectionModel().hasSelection()) return; var metaIds = []; for (var i = 0; i < metaClassSelGrid.store.getCount(); i++) { if (metaClassSelGrid.getSelectionModel().isSelected(i)) { metaIds.push(metaClassSelGrid.store.getAt(i).data.id); } } var productData = productGrid.getSelectionModel().getLastSelected().data; Ext.Ajax.request({ url: dataUrl + '/core/product/deleteProductMetaClass', method: 'POST', params: { productId: productData.id, metaIds: metaIds }, reader: { type: 'json', root: '' }, success: function() { loadMetaClasses(); }, failure: function(response, opts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } }); var buttonAddPosition = Ext.create('Ext.button.Button', { id: 'buttonAddPosition', hidden: !isDataManager, text: label_ADD, flex: 1, handler: function() { if (!positionAvlGrid.getSelectionModel().hasSelection() || !productGrid.getSelectionModel().hasSelection()) return; var posIds = []; for (var i = 0; i < positionAvlGrid.store.getCount(); i++) { if (positionAvlGrid.getSelectionModel().isSelected(i)) { posIds.push(positionAvlGrid.store.getAt(i).data.id); } } var productData = productGrid.getSelectionModel().getLastSelected().data; Ext.Ajax.request({ url: dataUrl + '/core/product/addProductPosition', method: 'POST', params: { productId: productData.id, posIds: posIds }, reader: { type: 'json', root: '' }, success: function() { loadPositions(); }, failure: function(response, opts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } }); var buttonDeletePosition = Ext.create('Ext.button.Button', { id: 'buttonDeletePosition', flex: 1, hidden: !isDataManager, text: label_DELETE, handler: function() { if (!positionSelGrid.getSelectionModel().hasSelection() || !productGrid.getSelectionModel().hasSelection()) return; var posIds = []; for (var i = 0; i < positionSelGrid.store.getCount(); i++) { if (positionSelGrid.getSelectionModel().isSelected(i)) { posIds.push(positionSelGrid.store.getAt(i).data.id); } } var productData = productGrid.getSelectionModel().getLastSelected().data; Ext.Ajax.request({ url: dataUrl + '/core/product/deleteProductPosition', method: 'POST', params: { productId: productData.id, posIds: posIds }, reader: { type: 'json', root: '' }, success: function() { loadPositions(); }, failure: function(response, opts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } }); var iterationStore = Ext.create('Ext.data.Store', { id: 'iterationStore', model: 'iterationModel', autoLoad: false, proxy: { type: 'ajax', url: dataUrl + '/core/product/getApproveIterations', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } }, listeners: { load: function (me, records, options) { iterationsPanel = Ext.getCmp('iterationsPanel'); iterationsPanel.removeAll(); if (records.length > 0) { Ext.getCmp('numIterationCount').setValue(records.length); for (var i = 0; i < records.length; i++) { Ext.create('Ext.form.Panel', { id: 'iterationPanel' + (i + 1), title: 'Итерация №' + (i + 1), height: 50, layout: { type: 'hbox', align: 'middle' }, items: [{ xtype: 'numberfield', id: 'numMonth' + (i + 1), fieldLabel: 'Месяцы', labelWidth: 55, width: 100, value: records[i].data.month, minValue: 0, keyNavEnabled: false, mouseWheelEnabled: false, margin: '0 20 0 0' }, { xtype: 'numberfield', id: 'numDay' + (i + 1), fieldLabel: 'Дни', labelWidth: 45, width: 90, value: records[i].data.day, minValue: 0, keyNavEnabled: false, mouseWheelEnabled: false, margin: '0 20 0 0' }, { xtype: 'numberfield', id: 'numHour' + (i + 1), fieldLabel: 'Часы', labelWidth: 50, width: 95, value: records[i].data.hour, minValue: 0, keyNavEnabled: false, mouseWheelEnabled: false, margin: '0 20 0 0' }, { xtype: 'numberfield', id: 'numMin' + (i + 1), fieldLabel: 'Минуты', labelWidth: 60, width: 105, value: records[i].data.min, minValue: 0, keyNavEnabled: false, mouseWheelEnabled: false, margin: '0 20 0 0' }, { xtype: 'checkbox', cls: 'checkBox', id: 'chkDayTransfer' + (i + 1), boxLabel: 'С переносом на рабочий день', width: 300, checked: records[i].data.dayTransfer, margin: '0 20 0 0' }] }); iterationsPanel.add(Ext.getCmp('iterationPanel' + (i + 1))); iterationsPanel.doLayout(); } } else { Ext.getCmp('numIterationCount').setValue(0); } }, scope: this } }); Ext.create('Ext.panel.Panel', { width: 1200, height: 600, padding: 10, renderTo: 'product-content', title: label_PRODUCTS, autoScroll: true, layout: { type: 'border', align: 'stretch' }, items: [ productGrid, { xtype: 'tabpanel', width: '100%', region: 'center', items: [{ xtype: 'panel', title: 'Настройка мета классов', //width: 500, width: '100%', //hidden: !isNb, layout: { type: 'vbox', align: 'stretch' }, items: [{ xtype: 'panel', title: label_META, autoScroll: true, height: 300, items: [metaClassSelGrid] }, { xtype: 'panel', height: 24, layout: { align: 'middle', pack: 'center', type: 'hbox' }, items: [buttonAddMetaClass, buttonDeleteMetaClass] }, { xtype: 'panel', title: label_AVA_META, autoScroll: true, height: 280, items: [metaClassAvlGrid] }] }, { xtype: 'panel', title: 'Настройка должностей', //width: 500, width: '100%', //hidden: !isNb, layout: { type: 'vbox', align: 'stretch' }, items: [{ xtype: 'panel', title: 'Выбранные должности', autoScroll: true, height: 300, items: [positionSelGrid] }, { xtype: 'panel', height: 24, layout: { align: 'middle', pack: 'center', type: 'hbox' }, items: [buttonAddPosition, buttonDeletePosition] }, { xtype: 'panel', title: 'Доступные должности', autoScroll: true, height: 280, items: [positionAvlGrid] }] }, { xtype: 'panel', title: 'Настройка одобрения', hidden: !isDataManager, width: '100%', autoScroll: true, layout: { type: 'vbox', align: 'stretch' }, items: [{ xtype: 'panel', autoScroll: true, height: 50, layout: { type: 'hbox', align: 'middle' }, items: [{ xtype: 'combobox', id: 'comboProducts', name: 'comboProdsId', fieldLabel: 'Продукт', labelWidth: 60, width:350, allowBlank: false, editable: false, store: productStore, valueField: 'id', displayField: 'name', margin: '0 20 0 0', listeners: { change: function (record, newValue, oldValue, eOpts) { productId = record.value; iterationStore.load({ params: { productId: productId } }); } } }, { xtype: 'numberfield', id: 'numIterationCount', fieldLabel: 'Количество итераций', labelWidth: 130, width: 175, name: 'iterationCount', value: 0, minValue: 0, editable: false, keyNavEnabled: false, mouseWheelEnabled: false, listeners: { spindown: function (record, eOpts) { valueToRemove = record.value; iterationsPanel = Ext.getCmp('iterationsPanel'); iterationsPanel.remove(Ext.getCmp('iterationPanel' + valueToRemove)); iterationsPanel.doLayout(); }, spinup: function (record, eOpts) { valueToAdd = record.value; iterationsPanel = Ext.getCmp('iterationsPanel'); Ext.create('Ext.form.Panel', { id: 'iterationPanel' + (valueToAdd + 1), title: 'Итерация №' + (valueToAdd + 1), height: 50, layout: { type: 'hbox', align: 'middle' }, items: [{ xtype: 'numberfield', id: 'numMonth' + (valueToAdd + 1), fieldLabel: 'Месяцы', labelWidth: 55, width: 100, value: 0, minValue: 0, keyNavEnabled: false, mouseWheelEnabled: false, margin: '0 20 0 0' }, { xtype: 'numberfield', id: 'numDay' + (valueToAdd + 1), fieldLabel: 'Дни', labelWidth: 45, width: 90, value: 0, minValue: 0, keyNavEnabled: false, mouseWheelEnabled: false, margin: '0 20 0 0' }, { xtype: 'numberfield', id: 'numHour' + (valueToAdd + 1), fieldLabel: 'Часы', labelWidth: 50, width: 95, value: 0, minValue: 0, keyNavEnabled: false, mouseWheelEnabled: false, margin: '0 20 0 0' }, { xtype: 'numberfield', id: 'numMin' + (valueToAdd + 1), fieldLabel: 'Минуты', labelWidth: 60, width: 105, value: 0, minValue: 0, keyNavEnabled: false, mouseWheelEnabled: false, margin: '0 20 0 0' }, { xtype: 'checkbox', cls: 'checkBox', id: 'chkDayTransfer' + (valueToAdd + 1), boxLabel: 'С переносом на рабочий день', width: 300, checked: true, margin: '0 20 0 0' }] }); iterationsPanel.add(Ext.getCmp('iterationPanel' + (valueToAdd + 1))); iterationsPanel.doLayout(); }, } }] }, { xtype: 'form', title: 'Итераций', id: 'iterationsPanel', autoScroll: true, height: 280, items: [] }, { xtype: 'panel', height: 40, border: false, layout: { align: 'middle', type: 'hbox' }, items: [{ xtype: 'button', margin: '0 0 0 5', text: 'Сохранить', //bind: true, listeners: { click: function () { var jsonList = []; var items = Ext.getCmp('iterationsPanel').items; for (i=0; i<items.getCount(); ++i) { var json = { iterationNumber: i+1, month: Ext.getCmp('numMonth'+(i+1)).value, day: Ext.getCmp('numDay'+(i+1)).value, hour: Ext.getCmp('numHour'+(i+1)).value, min: Ext.getCmp('numMin'+(i+1)).value, dayTransfer: Ext.getCmp('chkDayTransfer'+(i+1)).value }; jsonList.push(json); } Ext.Ajax.request({ url: dataUrl + '/core/product/setApproveIterations', method: 'POST', jsonData: jsonList, params: { productId: Ext.getCmp('comboProducts').value }, reader: { type: 'json', root: 'data' }, success: function(response, opts) { Ext.Msg.show({ title: '', msg: 'Изменения сохранены успешно', width : 300, buttons: Ext.MessageBox.YES }); }, failure: function(response, opts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } } }] }] }] }] }); }); <file_sep>function isEmpty(value) { return value === undefined || value === null || value.length === 0; } function getProfiles() { if (isSenchaMode) return ['profile://FSystem', 'profile://eToken']; var profilesString = document.app.getProfileNames('|'); return profilesString.split('|'); } function getCertificates(profile, password) { if (isSenchaMode) return ['C=KZ,O=Веб портал НБ РК,CN=Попова Светлана,UID=IIN851127400204', 'CN=ИБРАИМОВ БАУЫРЖАН,SURNAME=ИБРАИМОВ,SERIALNUMBER=IIN880318301425,C=KZ,L=АЛМАТЫ,ST=АЛМАТЫ,GIVENNAME=КАДЫРБЕКОВИЧ,E=<EMAIL>']; var certificatesInfo = document.app.getCertificatesInfo(profile, password, 0, '', true, false, '|'); return certificatesInfo.split('|'); } function getUserNameByCertificate(certificate) { if (!certificate) throw new Error('Сертификато не может быть = NULL'); var index = certificate.indexOf('CN='); if (index < 0) throw new Error('Ошибка получение имени пользователя из сертификата'); index += 3; var userName = ''; for (var i = index; i < certificate.length; i++) { var ch = certificate.charAt(i); if (ch === ',') break; userName += ch; } return userName; } function signHash(value, certificate, profile, password) { if (isSenchaMode) return 'TEST SIGNATURE'; return document.app.createPKCS7(value, 0, null, certificate, true, profile, password, '1.3.6.1.4.1.6801.1.5.8', true); }<file_sep>package kz.bsbnb.usci.receiver.batch.converter; import kz.bsbnb.usci.model.util.DtoConverter; import kz.bsbnb.usci.receiver.model.BatchEntry; import kz.bsbnb.usci.receiver.model.json.BatchEntryJson; import org.springframework.stereotype.Component; /** * @author <NAME> */ @Component public class BatchEntryConverter implements DtoConverter<BatchEntry, BatchEntryJson> { @Override public BatchEntryJson convertToDto(BatchEntry batchEntry) { BatchEntryJson batchEntryJson = new BatchEntryJson(); batchEntryJson.setId(batchEntry.getId()); batchEntryJson.setEntityId(batchEntry.getEntityId()); batchEntryJson.setRepDate(batchEntry.getRepDate()); batchEntryJson.setValue(batchEntry.getValue()); batchEntryJson.setUpdateDate(batchEntry.getUpdateDate()); batchEntryJson.setMaintenance(batchEntry.isMaintenance()); batchEntryJson.setUserId(batchEntry.getUserId()); return batchEntryJson; } @Override public void updateFromDto(BatchEntry batchEntry, BatchEntryJson dto) { throw new UnsupportedOperationException(); } } <file_sep>package kz.bsbnb.usci.model.json; import kz.bsbnb.usci.model.adm.User; import java.time.LocalDateTime; public class AuditJson { private static final long serialVersionUID = 1L; private long record_id; private String schema_name; private long userId; private LocalDateTime auditTime; private long id; private String tableName; private String content; private String eventName; private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public void setRecord_id(long record_id) { this.record_id = record_id; } public void setSchema_name(String schema_name) { this.schema_name = schema_name; } public void setUserId(long userId) { this.userId = userId; } public void setAuditTime(LocalDateTime auditTime) { this.auditTime = auditTime; } public void setId(long id) { this.id = id; } public void setTableName(String tableName) { this.tableName = tableName; } public void setContent(String content) { this.content = content; } public void setEventName(String eventName) { this.eventName = eventName; } public long getRecord_id() { return record_id; } public String getSchema_name() { return schema_name; } public long getUserId() { return userId; } public LocalDateTime getAuditTime() { return auditTime; } public long getId() { return id; } public String getTableName() { return tableName; } public String getContent() { return content; } public String getEventName() { return eventName; } } <file_sep>package kz.bsbnb.usci.portlet.confirm; import com.liferay.util.bridges.mvc.MVCPortlet; /** * @author <NAME> */ public class ConfirmPortlet extends MVCPortlet { } <file_sep>package kz.bsbnb.usci.eav.dao; import kz.bsbnb.usci.eav.model.base.BaseEntityJson; import kz.bsbnb.usci.eav.model.meta.json.EntityExtJsTreeJson; import java.util.List; public interface BaseEntityLoadXmlDao { List<BaseEntityJson> loadEntityForApproval(long batchId); EntityExtJsTreeJson loadBaseEntity(Long id); void updateBaseEntityState(BaseEntityJson baseEntityJson); void updateBaseEntity(BaseEntityJson baseEntityJson, boolean approve); void deleteBaseEntity(Long id); } <file_sep>package kz.bsbnb.usci.mail.service.impl; import kz.bsbnb.usci.mail.config.MailConfig; import kz.bsbnb.usci.mail.dao.MailMessageDao; import kz.bsbnb.usci.mail.dao.MailTemplateDao; import kz.bsbnb.usci.mail.model.*; import kz.bsbnb.usci.mail.model.dto.MailMessageDto; import kz.bsbnb.usci.mail.service.MailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author <NAME> * @author <NAME> * @author <NAME> */ @Service public class MailServiceImpl implements MailService { private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class); private final MailTemplateDao mailTemplateDao; private final MailConfig mailConfig; private final MailMessageDao mailMessageDao; private final JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); public MailServiceImpl(MailTemplateDao mailTemplateDao, MailConfig mailConfig, MailMessageDao mailMessageDao) { this.mailTemplateDao = mailTemplateDao; this.mailConfig = mailConfig; this.mailMessageDao = mailMessageDao; } @PostConstruct private void init() { Properties properties = new Properties(); properties.put("mail.smtp.host", mailConfig.getHost()); properties.put("mail.smtp.user", mailConfig.getEmail()); javaMailSender.setJavaMailProperties(properties); javaMailSender.setHost(properties.getProperty("mail.smtp.host")); javaMailSender.setUsername(properties.getProperty("mail.smtp.user")); } private boolean isTemplateEnabledForUser(MailTemplate mailTemplate, Long receiverUserId) { // данный шаблон не настраивается пользователем, а высылается в обязательном порядке if (mailTemplate.getTypeId() == MailConfigurationTypes.OBLIGATORY) { return true; } // если шаблон настраивается пользователем, проверяются настройки return mailTemplateDao.isTemplateEnabledForUser(mailTemplate.getId(), receiverUserId); } @Async @Override public void sendMail(MailMessageDto mailMessageDto) { MailMessage mailMessage = new MailMessage(); mailMessage.setParams(mailMessageDto.getParams()); mailMessage.setReceiver(mailMessageDto.getReceiver()); mailMessage.setCreationDate(LocalDateTime.now()); mailMessage.setMailTemplate(mailTemplateDao.getTemplate(mailMessageDto.getMailTemplate())); mailMessage.setStatus(MailMessageStatus.PROCESSING); logger.info("Обработка сообщения к email {}", mailMessage); mailMessageDao.insertMailMessage(mailMessage); boolean isSending = isTemplateEnabledForUser(mailMessage.getMailTemplate(), mailMessage.getReceiver().getUserId()); if (!mailMessage.getReceiver().isActive()) { isSending = false; } if (isSending) { sendMail(prepareMail(mailMessage)); mailMessage.setStatus(MailMessageStatus.SENT); } else { mailMessage.setStatus(MailMessageStatus.REJECTED_BY_USER_SETTINGS); } mailMessage.setSendingDate(LocalDateTime.now()); mailMessageDao.updateMailMessage(mailMessage); } @Override public List<UserMailTemplate> getUserMailTemplateList(Long userId) { return mailTemplateDao.getUserMailTemplateList(userId); } @Override public void saveUserMailTemplateList(List<UserMailTemplate> userMailTemplateList) { mailTemplateDao.saveUserMailTemplateList(userMailTemplateList); } private Mail prepareMail(MailMessage mailMessage) { MailTemplate mailTemplate = mailMessage.getMailTemplate(); return new Mail() .setSenderEmail(mailConfig.getEmail()) .setReceiverEmail(mailMessage.getReceiver().getEmailAddress()) .setSubject(replaceParamsWithValues(mailTemplate.getSubject(), mailMessage.getParams())) .setText(replaceParamsWithValues(mailTemplate.getText(), mailMessage.getParams())); } private String replaceParamsWithValues(String templateText, Map<String, String> params) { for (String paramKey : params.keySet()) templateText = templateText.replace("${" + paramKey + "}", params.get(paramKey)); return templateText; } private void sendMail(Mail mail) { if (mail.getReceiverEmail().toLowerCase().endsWith("liferay.com") || mail.getReceiverEmail().toLowerCase().endsWith("oldbank.kz")) { return; } logger.info("Отправка сообщения по email {}", mail); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { mimeMessage.setFrom(new InternetAddress(mail.getSenderEmail())); mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mail.getReceiverEmail())); mimeMessage.setSubject(mail.getSubject()); mimeMessage.setText(mail.getText(), "utf-8", "html"); javaMailSender.send(mimeMessage); } catch (MessagingException e) { logger.error("Ошибка отправки письма по email", e); } } } <file_sep>var label_ERROR = 'Қате'; var label_CRED = 'Респонденттер'; var label_PROCCESING = 'Аралық бақылауды қалыптастыру '; var label_EXCEL = 'Excel -ге түсіру'; var label_CROSSCHECK = 'Аралық бақылау'; var label_ORG_NAME = 'Ұйымның атауы '; var label_BEG_DATE = 'Бақылаудың басталу күні '; var label_END_DATE = 'Бақылаудың аяқталу күні'; var label_STATUS = 'Статус'; var label_USER = 'Пайдаланушы'; var label_PARAMETR = 'Көрсеткіш'; var label_VALUE_KR = 'ААЖ ЕССП мағына '; var label_OUT_VALUE = 'Сыртқы негіз көзіндегі мағына '; var label_DIFF = 'Айырмашылық'; var label_ORGS = 'Ұйым'; var label_R = 'Даму банкі'; var label_VU = 'Бірінші деңгейдегі банк'; var label_PU = 'Екінші деңгейдегі банк'; var label_IO = 'Ипотекалық ұйым'; var label_OTHER = 'Банктік операциялардың жеке түрлерін жүзеге асырушы басқада ұйымдар '; var label_SELECT_ALL = 'Барлығын таңдау'; var label_OFF_SELECTED = 'Бөліп көрсетілгендерді алып тастау'; var label_ALL = 'Барлығын бөліп көрсету'; var label_SHOW = 'Көрсету'; var label_START = 'Аралық бақылауды іске қосу'; var label_DATA = 'Бақылау бойынша деректер'; <file_sep>package kz.bsbnb.usci.receiver.parser.impl; import kz.bsbnb.usci.receiver.parser.BatchParser; import kz.bsbnb.usci.receiver.parser.exceptions.UnknownTagException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.xml.sax.SAXException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** * @author <NAME> * @author <NAME> */ @Component @Scope("prototype") public class SubjectsParser extends BatchParser { @Autowired private SubjectPersonParser subjectPersonParser; @Autowired private SubjectOrganizationParser subjectOrganizationParser; @Autowired private SubjectCreditorParser subjectCreditorParser; public SubjectsParser() { super(); } @Override public boolean startElement(XMLEvent event, StartElement startElement, String localName) throws SAXException { switch (localName) { case "subjects": break; case "subject": break; case "person": subjectPersonParser.parse(xmlReader, batch, index, respondentId); currentBaseEntity = subjectPersonParser.getCurrentBaseEntity(); break; case "organization": subjectOrganizationParser.parse(xmlReader, batch, index, respondentId); currentBaseEntity = subjectOrganizationParser.getCurrentBaseEntity(); break; case "creditor": subjectCreditorParser.parse(xmlReader, batch, index, respondentId); currentBaseEntity = subjectCreditorParser.getCurrentBaseEntity(); break; default: throw new UnknownTagException(localName); } return false; } @Override public boolean endElement(String localName) throws SAXException { switch (localName) { case "subjects": hasMore = false; break; case "subject": hasMore = true; break; default: throw new UnknownTagException(localName); } return true; } } <file_sep>package kz.bsbnb.usci.model.respondent; /** * @author <NAME> */ public class RespondentJson { private Long id; private String name; private String shortName; private String code; public RespondentJson() { super(); } public RespondentJson(Long id) { this.id = id; } public RespondentJson(Long id, String name) { this.id = id; this.name = name; } public RespondentJson(Respondent respondent) { this.id = respondent.getId(); this.name = respondent.getName(); } public Long getId() { return id; } public RespondentJson setId(Long id) { this.id = id; return this; } public String getName() { return name; } public RespondentJson setName(String name) { this.name = name; return this; } public String getShortName() { return shortName; } public RespondentJson setShortName(String shortName) { this.shortName = shortName; return this; } public String getCode() { return code; } public RespondentJson setCode(String code) { this.code = code; return this; } } <file_sep>var label_TITLE = 'Administration'; var label_ERROR = 'Error'; var label_CHOOSE_PRODUCT = 'Select a product!'; var label_SETUP_USERS = 'User settings'; var label_USERS = 'Users'; var label_SYNC_USERS = 'Sync users'; var label_SYNC = 'Synchronized'; var label_SETUP_RESP = 'Configuring respondents'; var label_APPOINTED_RESP = 'Assigned respondents'; var label_ADD = 'Add'; var label_IMPOSSIBLE_ADDING = 'Cannot add more than one respondent to the selected user!'; var label_DELETE = 'Delete'; var label_AVAILABLE_RESP = 'Available respondents'; var label_SETUP_POST = 'Post settings'; var label_SELECTED_PROD = 'Select a product:'; var label_CHOOSE_USER = 'Select a user!'; var label_CHOOSE_POST = 'Select posts for this product'; var label_AVAILABLE_POST = 'Available posts'; var label_APPOINTED_POST = 'Appointed posts'; var label_SETUP_PRODUCTS = 'Products settings'; var label_AVAILABLE_PRODUCTS = 'Available products'; var label_APPOINTED_PRODUCTS = 'Assigned products'; var label_SETUP_PERIODICITY = 'Setting the periodicity of the reporting date of the subjects'; var label_SUBJECTS = 'Subjects'; var label_PERIODICITY = 'Periodicity' var label_CHOOSE_SUBJECT = 'Choose a subject!'; var label_PERIOD = 'Periodicity:'; var label_SAVE = 'Save'; var label_SUCCESS_UPDATE = 'Successfully updated!'; var label_SETUP_EDS = 'EDS settings'; var label_REQUIRED_EDS = 'Select organizations with mandatory sending via EDS'; var label_UPDATED = 'Updated'; <file_sep>package kz.bsbnb.usci.eav.meta.repository; import kz.bsbnb.usci.eav.dao.MetaClassDao; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.eav.repository.MetaClassRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Repository; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @author <NAME> * @author <NAME> * @author <NAME> */ @Repository public class MetaClassRepositoryImpl implements MetaClassRepository { private final MetaClassDao metaClassDao; private final Map<String, MetaClass> cache = new ConcurrentHashMap<>(); private final Map<Long, String> names = new ConcurrentHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Environment environment; @Autowired public MetaClassRepositoryImpl(MetaClassDao metaClassDao, Environment environment) { this.metaClassDao = metaClassDao; this.environment = environment; } @PostConstruct public void init() { // не будем кешировать мета классы в режиме разработчика потому что тормозит /*if (Arrays.stream(environment.getActiveProfiles()).anyMatch(env -> (env.equalsIgnoreCase("dev")))) return;*/ loadMetaClasses(); } private void loadMetaClasses() { lock.readLock().lock(); List<MetaClass> metaClassList; try { metaClassList = metaClassDao.loadAll(); } finally { lock.readLock().unlock(); } lock.writeLock().lock(); try { for (MetaClass tmpMeta : metaClassList) { cache.put(tmpMeta.getClassName(), tmpMeta); names.put(tmpMeta.getId(), tmpMeta.getClassName()); } } finally { lock.writeLock().unlock(); } } @Override public MetaClass getMetaClass(String className) { lock.readLock().lock(); MetaClass metaClass; try { metaClass = cache.get(className); } finally { lock.readLock().unlock(); } if (metaClass == null) { lock.readLock().lock(); try { metaClass = metaClassDao.load(className); } finally { lock.readLock().unlock(); } if (metaClass != null) { lock.writeLock().lock(); try { cache.put(className, metaClass); names.put(metaClass.getId(), className); } finally { lock.writeLock().unlock(); } } } return metaClass; } @Override public MetaClass getMetaClass(long id) { String className; lock.readLock().lock(); try { className = names.get(id); } finally { lock.readLock().unlock(); } MetaClass metaClass = null; if (className != null) { lock.readLock().lock(); try { metaClass = cache.get(className); } finally { lock.readLock().unlock(); } } if (metaClass == null) { lock.readLock().lock(); try { metaClass = metaClassDao.load(id); } finally { lock.readLock().unlock(); } if (metaClass != null) { lock.writeLock().lock(); try { cache.put(metaClass.getClassName(), metaClass); names.put(metaClass.getId(), metaClass.getClassName()); } finally { lock.writeLock().unlock(); } } } return metaClass; } @Override public List<MetaClass> getMetaClasses() { List<MetaClass> metaClassList = new ArrayList<>(); lock.readLock().lock(); try { if (cache.isEmpty()) loadMetaClasses(); for (Map.Entry<String, MetaClass> entry : cache.entrySet()) metaClassList.add(entry.getValue()); } finally { lock.readLock().unlock(); } return metaClassList; } @Override public void saveMetaClass(MetaClass metaClass) { long id; lock.writeLock().lock(); try { id = metaClassDao.save(metaClass); metaClass = metaClassDao.load(id); names.put(id, metaClass.getClassName()); cache.put(metaClass.getClassName(), metaClass); List<Long> classIds = metaClassDao.loadClassesWithReference(id); for (long classId: classIds) { metaClass = metaClassDao.load(classId); names.put(metaClass.getId(), metaClass.getClassName()); cache.put(metaClass.getClassName(), metaClass); } } finally { lock.writeLock().unlock(); } } @Override public void resetCache() { lock.writeLock().lock(); try { cache.clear(); names.clear(); } finally { lock.writeLock().unlock(); } try { init(); } catch (Exception ex) { ex.printStackTrace(); } } @Override public boolean delMetaClass(Long classId) { MetaClass meta = getMetaClass(classId); if (meta != null) { lock.writeLock().lock(); try { metaClassDao.remove(meta); cache.remove(meta.getClassName()); names.remove(meta.getId()); } finally { lock.writeLock().unlock(); } return true; } return false; } } <file_sep>package kz.bsbnb.usci.report.dao; import kz.bsbnb.usci.report.crosscheck.CrossCheck; import kz.bsbnb.usci.report.crosscheck.CrossCheckMessageDisplayWrapper; import kz.bsbnb.usci.report.crosscheck.Message; import java.time.LocalDate; import java.util.List; public interface CrossCheckDao { List<CrossCheck> getCrossChecks(List<Long> creditorIds, LocalDate reportDate, Long productId); void crossCheck(Long userId, Long creditorId, LocalDate reportDate, long productId, String executeClause); void crossCheckAll(Long userId, LocalDate reportDate, long productId, String executeClause); List<CrossCheckMessageDisplayWrapper> getCrossCheckMessages( Long crossCheckId); LocalDate getFirstNotApprovedDate(Long creditorId); LocalDate getLastApprovedDate(Long creditorId); CrossCheck getCrossCheck(Long crossCheckId); Message getMessage(Long messageId); } <file_sep>package kz.bsbnb.usci.brms.model; import java.io.Serializable; //TODO: избавиться можно без него //??????????? public class Pair implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String name; private String title; public Pair(long id, String name) { this.id = id; this.name = name; } public Pair(long id, String name, String title) { this.id = id; this.name = name; this.title = title; } public Pair(long id, String title, boolean another) { this.id = id; this.title = title; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } <file_sep>var label_ERROR = 'Ошибка'; var label_SAVE = 'Сохранить'; var label_FIELDS = 'Заполните необходимые поля'; var label_SAVING = 'Идет сохранение...'; var label_CANCEL = 'Отмена'; var label_NAME = 'Наименование'; var label_PRODUCT = 'Продукт'; var label_DOWN = 'Скачать XSD файл'; var label_XSD = 'Сгенерировать xsd для всех продуктов'; var label_XSDING = 'Идет генерация xsd продуктов...'; var label_INFO = 'Информация'; var label_XSD_END = 'Генерация xsd продуктов завершена'; var label_CODE = 'Код'; var label_ADD = 'Добавить'; var label_NO_DATA = 'Нет данных для отображения'; var label_DELETE = 'Удалить'; var label_PRODUCTS = 'Продукты'; var label_META = 'Выбранные мета классы'; var label_AVA_META = 'Доступные мета классы'; <file_sep>package kz.bsbnb.usci.brms.dao; import kz.bsbnb.usci.brms.model.PackageVersion; import kz.bsbnb.usci.brms.model.Rule; import kz.bsbnb.usci.brms.model.RulePackage; import kz.bsbnb.usci.brms.model.SimpleTrack; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.sql.PreparedStatement; import java.sql.Timestamp; import java.time.LocalDate; import java.util.*; /** * @author <NAME> * @author <NAME> */ @Repository public class RuleDaoImpl implements RuleDao { private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; public RuleDaoImpl(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) { this.jdbcTemplate = jdbcTemplate; this.npJdbcTemplate = npJdbcTemplate; } public List<Rule> load(PackageVersion packageVersion) { String query = "SELECT rules.ID, rules.RULE, rules.TITLE, rules.OPEN_DATE, rules.CLOSE_DATE FROM USCI_RULE.RULE_ rules,\n" + " USCI_RULE.RULE_PACKAGE rulePkg\n" + " WHERE rules.ID = rulePkg.rule_ID\n" + " AND rules.OPEN_DATE <= :reportDate \n" + " AND (rules.CLOSE_DATE > :reportDate OR rules.CLOSE_DATE is null)\n" + " AND rulePkg.PACKAGE_ID = :packageId "; List<Rule> ruleList = new ArrayList<>(); MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("reportDate", SqlJdbcConverter.convertToSqlDate(packageVersion.getReportDate())); params.addValue("packageId", packageVersion.getRulePackage().getId()); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); for(Map<String,Object> row : rows) { Rule rule = getRule(row); ruleList.add(rule); } return ruleList; } @Override @Transactional public long update(Rule rule) { if (rule.getId() < 1L){ throw new UsciException("Правило не имеет id."); } npJdbcTemplate.update("UPDATE USCI_RULE.RULE_\n" + " SET TITLE = :title ,\n" + " RULE = :rule ,\n" + " OPEN_DATE = :openDate\n" + " WHERE ID = :id", new MapSqlParameterSource("title", rule.getTitle()) .addValue("rule", rule.getRule()) .addValue("openDate", SqlJdbcConverter.convertToSqlDate(rule.getOpenDate())) .addValue("id", rule.getId())); return rule.getId(); } @Override public List<Rule> getAllRules() { String query = "select * from USCI_RULE.RULE_ order by id"; return jdbcTemplate.query(query, new BeanPropertyRowMapper(Rule.class)); } @Override public List<SimpleTrack> getRuleTitles(Long packageId, LocalDate reportDate) { String query = "SELECT rules.ID, rules.RULE, rules.TITLE, rules.OPEN_DATE, rules.CLOSE_DATE FROM USCI_RULE.RULE_ rules,\n" + " USCI_RULE.RULE_PACKAGE rulePkg\n" + " WHERE rules.ID = rulePkg.rule_ID\n" + " AND rules.OPEN_DATE <= :reportDate \n" + " AND (rules.CLOSE_DATE > :reportDate OR rules.CLOSE_DATE is null)\n" + " AND rulePkg.PACKAGE_ID = :packageId"; List<SimpleTrack> ret = new ArrayList<>(); MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("reportDate", SqlJdbcConverter.convertToSqlDate(reportDate)); params.addValue("packageId", packageId); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); for(Map<String,Object> row: rows) { SimpleTrack s = new SimpleTrack(); s.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); s.setName((String) row.get("TITLE")); s.setIsActive(true); ret.add(s); } return ret; } @Override public List<SimpleTrack> getRuleTitles(Long packageId, LocalDate reportDate, String searchText) { searchText = searchText.toLowerCase(); String query = "SELECT rules.ID, rules.TITLE AS NAME, rules.RULE FROM USCI_RULE.RULE_ rules, USCI_RULE.RULE_PACKAGE rulePkg\n" + " WHERE rules.ID = rulePkg.rule_ID\n" + " AND rules.OPEN_DATE <= :reportDate \n" + " AND (rules.CLOSE_DATE > :reportDate OR rules.CLOSE_DATE is null)\n" + " AND (LOWER(rules.rule) LIKE :searchText OR LOWER(rules.title) LIKE :searchText)\n" + " AND rulePkg.PACKAGE_ID = :packageId "; List<SimpleTrack> ret = new ArrayList<>(); MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("reportDate", SqlJdbcConverter.convertToSqlDate(reportDate)); params.addValue("packageId", packageId); params.addValue("searchText","%"+searchText+"%"); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); for(Map<String,Object> row: rows) { SimpleTrack s = new SimpleTrack(); s.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); s.setName((String) row.get("NAME")); s.setIsActive(true); ret.add(s); } return ret; } @Override @Transactional public long save(Rule rule, PackageVersion packageVersion){ SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_RULE") .withTableName("RULE_") .usingGeneratedKeyColumns("ID"); Number id = simpleJdbcInsert.executeAndReturnKey(new MapSqlParameterSource() .addValue("TITLE", rule.getTitle()) .addValue("RULE", rule.getRule()) .addValue("OPEN_DATE", SqlJdbcConverter.convertToSqlDate(packageVersion.getReportDate()))); rule.setId(id.longValue()); return id.longValue(); } @Override public Rule getRule(Rule rule) { if(rule.getId()< 1L || rule.getOpenDate() == null) throw new RuntimeException("Ид или отчетная дата указаны неверно"); String query = "SELECT ID, RULE, TITLE, OPEN_DATE, CLOSE_DATE FROM USCI_RULE.RULE_ rules\n" + " WHERE rules.ID = :ruleId" + " AND rules.OPEN_DATE <= :reportDate \n" + " AND (rules.CLOSE_DATE > :reportDate OR rules.CLOSE_DATE is null)"; MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("ruleId", rule.getId()); params.addValue("reportDate", SqlJdbcConverter.convertToSqlDate(rule.getOpenDate())); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); return getRule(rows.iterator().next()); } @Override @Transactional public void deleteRule(long ruleId, RulePackage rulePackage) { int count = npJdbcTemplate.update("delete from USCI_RULE.RULE_PACKAGE " + " where PACKAGE_ID = :packageId\n " + " and RULE_ID = :ruleId", new MapSqlParameterSource("packageId", rulePackage.getId()) .addValue("ruleId",ruleId)); if (count != 1) throw new UsciException("Ошибка удаления из таблицы USCI_RULE.RULE_PACKAGE"); int countR = npJdbcTemplate.update("delete from USCI_RULE.RULE_ " + " where ID = :ruleId ", new MapSqlParameterSource("ruleId", ruleId)); if (countR != 1) throw new UsciException("Ошибка удаления из таблицы USCI_RULE.RULE_"); } @Override @Transactional public long createEmptyRule(final String title){ KeyHolder keyHolder = new GeneratedKeyHolder(); final String defaultRuleBody = "rule \" rule_" + (new Random().nextInt()) + "\"\nwhen\nthen\nend"; jdbcTemplate.update(connection -> { PreparedStatement ps = connection.prepareStatement("INSERT INTO USCI_RULE.RULE_ (title, rule) " + "VALUES(?, ?)", new String[]{"id"}); ps.setString(1,title); ps.setString(2, defaultRuleBody); return ps; }, keyHolder); return keyHolder.getKey().longValue(); } @Override @Transactional public void saveInPackage(Rule rule, PackageVersion packageVersion) { SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_RULE") .withTableName("RULE_PACKAGE") .usingGeneratedKeyColumns("ID"); simpleJdbcInsert.executeAndReturnKey(new MapSqlParameterSource() .addValue("RULE_ID", rule.getId()) .addValue("PACKAGE_ID", packageVersion.getRulePackage().getId())); } @Override public RulePackage getPackage(String name) { String query = "select * from USCI_RULE.PACKAGE_ WHERE NAME = :name"; MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("name", name); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); if (rows.size() < 1) throw new IllegalArgumentException("Отсутствует пакет: " + name); Map<String,Object> row = rows.iterator().next(); RulePackage ret = new RulePackage(); ret.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); ret.setName(name); return ret; } @Override @Transactional public void updateBody(Rule rule) { int count = npJdbcTemplate.update("update USCI_RULE.RULE_\n" + " set RULE = :rule\n" + " where ID = :id " + " and OPEN_DATE = :openDate", new MapSqlParameterSource("rule", rule.getRule()) .addValue("id", rule.getId()) .addValue("openDate", SqlJdbcConverter.convertToSqlDate(rule.getOpenDate()))); if (count != 1) throw new RuntimeException("Ошибка update записи в таблице USCI_RULE.RULE_"); } @Override @Transactional public long createRule(Rule rule, PackageVersion packageVersion) { SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_RULE") .withTableName("RULE_") .usingGeneratedKeyColumns("ID"); Number id = simpleJdbcInsert.executeAndReturnKey(new MapSqlParameterSource() .addValue("TITLE", rule.getTitle()) .addValue("RULE", rule.getRule()) .addValue("OPEN_DATE", SqlJdbcConverter.convertToSqlDate(packageVersion.getReportDate()))); rule.setId(id.longValue()); return id.longValue(); } @Override @Transactional public void renameRule(long ruleId, String title) { String sql = "update USCI_RULE.RULE_ set title = ? where id = ?"; jdbcTemplate.update(sql, title, ruleId); } @Override @Transactional public void clearAllRules() { jdbcTemplate.update("delete from USCI_RULE.RULE_PACKAGE"); jdbcTemplate.update("delete from USCI_RULE.RULE_"); } @Override public List<PackageVersion> getPackageVersions(RulePackage rulePackage) { String query = "SELECT DISTINCT RULES.OPEN_DATE \n"+ " FROM (SELECT r.ID, \n"+ " r.RULE, \n"+ " r.TITLE, \n"+ " r.OPEN_DATE, \n"+ " r.CLOSE_DATE \n"+ " FROM USCI_RULE.RULE_ r,\n"+ " USCI_RULE.RULE_PACKAGE rulePkg \n"+ " where r.ID = rulePkg.RULE_ID \n"+ " and rulePkg.PACKAGE_ID = :packageId) rules"; MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("packageId", rulePackage.getId()); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query, params); Set<LocalDate> dates = new HashSet<>(); for (Map<String,Object> row: rows) { dates.add(SqlJdbcConverter.convertToLocalDate((Timestamp) row.get("OPEN_DATE"))); } query = "SELECT DISTINCT RULES.CLOSE_DATE \n" + " FROM (SELECT r.ID, \n" + " r.RULE, \n" + " r.TITLE, \n" + " r.OPEN_DATE, \n" + " r.CLOSE_DATE \n" + " FROM USCI_RULE.RULE_ r, \n" + " USCI_RULE.RULE_PACKAGE rulePkg \n" + " where r.ID = rulePkg.RULE_ID \n" + " and rulePkg.PACKAGE_ID = :packageId and r.CLOSE_DATE is not null) rules"; rows = npJdbcTemplate.queryForList(query, params); for(Map<String,Object> row: rows) { dates.add(SqlJdbcConverter.convertToLocalDate((Timestamp) row.get("CLOSE_DATE"))); } List<PackageVersion> ret = new LinkedList<>(); for(LocalDate date: dates) { ret.add(new PackageVersion(rulePackage, date)); } Collections.sort(ret, new Comparator<PackageVersion>() { @Override public int compare(PackageVersion o1, PackageVersion o2) { return o1.getReportDate().compareTo(o2.getReportDate()); } }); return ret; } @Override public List<Rule> getRuleHistory(long ruleId) { String query = getRuleHistoryTable(); query = query + " WHERE rules.ID = :ruleId"; MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("ruleId",ruleId); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query,params); List<Rule> ruleList = new ArrayList<>(); long t = 1; for(Map<String,Object> row : rows) { Rule rule = getRule(row); rule.setId(t++ ); ruleList.add(rule); } return ruleList; } @Override public List<RulePackage> getRulePackages(Rule rule) { String query = "select PACKAGE_ID from USCI_RULE.RULE_PACKAGE where RULE_ID = :ruleId"; MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("ruleId", rule.getId()); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(query,params); List<RulePackage> rulePackageList = new ArrayList<>(); for (Map<String, Object> row : rows) { RulePackage rulePackage = new RulePackage(); rulePackage.setId(SqlJdbcConverter.convertToLong(row.get("PACKAGE_ID"))); rulePackageList.add(rulePackage); } return rulePackageList; } private Rule getRule(Map<String,Object> row){ Rule rule = new Rule(); rule.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); rule.setRule((String) row.get("RULE")); rule.setOpenDate(SqlJdbcConverter.convertToLocalDate((Timestamp) row.get("OPEN_DATE"))); rule.setTitle((String) row.get("TITLE")); rule.setCloseDate(SqlJdbcConverter.convertToLocalDate((Timestamp) row.get("CLOSE_DATE"))); return rule; } private String getRuleHistoryTable(){ return "SELECT RULES.* FROM (SELECT ID, RULE, TITLE, OPEN_DATE, CLOSE_DATE FROM USCI_RULE.RULE_\n"+ "UNION ALL\n"+ "SELECT RULE_ID as ID, RULE, TITLE, OPEN_DATE, CLOSE_DATE FROM USCI_RULE.RULE_HIS) rules\n"; } } <file_sep>name=Admin portlet module-group-id=usci module-incremental-version=1 tags= short-description= change-log= page-url=http://www.bsbnb.kz author=<NAME> licenses=LGPL liferay-versions=6.1.1<file_sep>/** * @author <NAME> */ Ext.onReady(function() { function showConfirmWindow() { var profilesStore = Ext.create('Ext.data.Store', { id: 'profilesStore', fields: ['name'], data : [ {"name":"Нажмите на кнопку \"Загрузить профили\" ..."} ], autoload: false }); var certificatesStore = Ext.create('Ext.data.Store', { id: 'certificatesStore', fields: ['name'], data : [ {"name":"Нажмите на кнопку \"Получить сертификаты из профиля\" ..."} ], autoload: false }); var signingPanel = Ext.create('Ext.panel.Panel', { id: 'signingPanel', margin: 0, width: '100%', height: 400, autoScroll: true, title: 'ЭЦП', titleCollapse: false, listeners: { afterrender: function () { Ext.getCmp('profilesCombo').setValue(profilesStore.getAt(0).data.name); Ext.getCmp('certsCombo').setValue(certificatesStore.getAt(0).data.name); } }, items: [{ xtype: 'button', margin: '10 0 0 10', text: label_DOWN_PRO, listeners: { click: function () { var profiles = getProfiles(); var selectedValue = ''; var store = Ext.getCmp('profilesCombo').getStore(); store.removeAll(); Ext.getCmp('profilesCombo').setValue(null); store.commitChanges(); for (var i = 0; i < profiles.length; i++) { store.add({name: profiles[i]}); if (profiles[i] === 'profile://FSystem') { selectedValue = profiles[i]; } } if (!isEmpty(selectedValue)) { Ext.getCmp('profilesCombo').setValue(selectedValue); } store.commitChanges(); } } }, { xtype: 'combobox', id: 'profilesCombo', store: profilesStore, margin: '10 0 0 10', labelWidth: '40%', width: '60%', editable : false, valueField: 'name', displayField: 'name', fieldLabel: label_SPISOK, labelAlign: 'left', labelStyle: 'font-weight: bold;' }, { xtype: 'checkboxfield', margin: '10 0 0 10', cls: 'checkBox', fieldLabel: '', boxLabel: label_PROTECTED, listeners: { change: function (field, newValue, oldValue, options) { passfield = Ext.getCmp('profilePasword'); if (newValue == '1') { passfield.show(); } else if (newValue == '0') { passfield.hide(); } } } }, { xtype: 'textfield', id: 'profilePasword', hidden: true, margin: '10 0 0 10', fieldLabel: 'Пароль профиля', labelWidth: '40%', width: '60%', inputType: 'password' }, { xtype: 'button', margin: '10 0 0 10', text: label_GET_SERT, listeners: { click: function () { var profile = Ext.getCmp('profilesCombo').getValue(); var password = Ext.getCmp('profilePasword').getValue(); var certificates = getCertificates(profile, password); if (!certificates || (certificates.length === 0)) { Ext.Msg.alert(label_GET_ERROR); return; } var store = Ext.getCmp('certsCombo').getStore(); store.removeAll(); Ext.getCmp('certsCombo').setValue(null); store.commitChanges(); for (var i = 0; i < certificates.length; i++) { store.add({name: certificates[i]}); } Ext.getCmp('certsCombo').setValue(store.getAt(0)); } } }, { xtype: 'combobox', id: 'certsCombo', store: certificatesStore, margin: '10 0 0 10', labelWidth: '40%', width: '60%', editable : false, valueField: 'name', displayField: 'name', fieldLabel: 'Сертификат', labelAlign: 'left', labelStyle: 'font-weight: bold;' }] }); var windowId = 'windowConfirm'; if (Ext.getCmp(windowId)) Ext.getCmp(windowId).destroy(); var buttonConfirm = Ext.create('Ext.button.Button', { text: label_SIGN, handler: function() { var profile = Ext.getCmp('profilesCombo').getValue(); if (isEmpty(profile) || profile.indexOf(label_PRESS) != -1) { Ext.Msg.alert(label_ERROR, label_CHOOSE_P); return; } var certificate = Ext.getCmp('certsCombo').getValue(); if (isEmpty(certificate) || certificate.indexOf(label_PRESS) != -1) { Ext.Msg.alert(label_ERROR, label_CHOOSE_S); return; } var password = Ext.getCmp('profilePasword').getValue(); var loadMask = new Ext.LoadMask(Ext.getCmp(windowId), {msg: label_WAIT}); loadMask.show(); var confirmData = confirmGrid.getSelectionModel().getLastSelected().data; var documentHash = null; var userName = getUserNameByCertificate(certificate); // получаем хэш документа чтобы подписывать Ext.Ajax.request({ async: false, url: dataUrl + '/core/confirm/getConfirmDocumentHash', method: 'GET', params: { userId: userId, confirmId: confirmData.id, userName: userName }, success: function(response, opts) { var data = response.responseText; documentHash = data; }, failure: function(response, opts) { loadMask.hide(); var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); return; } }); var pkcs7 = signHash(documentHash, certificate, profile, password); Ext.Ajax.request({ url: dataUrl + '/core/confirm/approve', method: 'POST', params: { userId: userId, confirmId: confirmData.id, documentHash: documentHash, signature: pkcs7, userName: userName }, success: function (response, opts) { loadMask.hide(); // вызываем метод чтобы заново вытащить текущий статус отчета // то есть после операций в бэке необходимо обновить реквизиты showConfirmInfo(); Ext.Msg.alert(label_INFO, label_REP_CONFIRMED); window.close(); }, failure: function (response, opts) { loadMask.hide(); var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } }); } }); var window = new Ext.Window({ id: windowId, modal: 'true', bodyPadding: '2', width: 600, closable: true, title: label_CONFIRM, items: [ signingPanel ], tbar: [ buttonConfirm, { text: label_SHOW, handler: function() { var profile = Ext.getCmp('profilesCombo').getValue(); if (isEmpty(profile) || profile.indexOf(label_PRESS) != -1) { Ext.Msg.alert(label_ERROR, label_CHOOSE_P); return; } var certificate = Ext.getCmp('certsCombo').getValue(); if (isEmpty(certificate) || certificate.indexOf(label_PRESS) != -1) { Ext.Msg.alert(label_ERROR, label_CHOOSE_S); return; } var confirmData = confirmGrid.getSelectionModel().getLastSelected().data; var loadMask = new Ext.LoadMask(Ext.getCmp(windowId), {msg: label_WAIT}); loadMask.show(); var userName = getUserNameByCertificate(certificate); var xhr = new XMLHttpRequest(); xhr.open('GET', dataUrl + '/core/confirm/createConfirmDocument?confirmId=' + confirmData.id + '&userId='+userId + '&userName=' + userName, true); xhr.responseType = 'arraybuffer'; xhr.onload = function (oEvent) { if (xhr.status == 200) { var responseArray = new Uint8Array(this.response); var blob = new Blob([responseArray], {type: 'application/pdf'}); saveAs(blob, 'Соглашение.pdf'); } else { Ext.Msg.alert(label_ERROR,''); } loadMask.hide(); }; xhr.send(); } }] }); window.show(); } function showConfirmInfo() { Ext.getCmp('buttonBack').setVisible(true); var confirmData = confirmGrid.getSelectionModel().getLastSelected().data; var messageGrid = Ext.getCmp('messageGrid'); messageGrid.store.load({ params: { confirmId: confirmData.id }, scope: this }); messageGrid.getView().refresh(); var confirmStageGrid = Ext.getCmp('confirmStageGrid'); confirmStageGrid.store.load({ params: { confirmId: confirmData.id }, scope: this }); confirmStageGrid.getView().refresh(); Ext.Ajax.request({ url: dataUrl + '/core/confirm/getConfirmJson', method: 'GET', params: { confirmId: confirmData.id }, reader: { type: 'json', root: 'data' }, success: function (response, opts) { var confirm = Ext.decode(response.responseText); buttonConfirm.setDisabled(confirm.statusId == 300); var firstBatchLoadTime = null; if (confirm.firstBatchLoadTime) firstBatchLoadTime = Ext.Date.format(new Date(confirm.firstBatchLoadTime), 'd.m.Y H:i:s'); var lastBatchLoadTime = null; if (confirm.lastBatchLoadTime) lastBatchLoadTime = Ext.Date.format(new Date(confirm.lastBatchLoadTime), 'd.m.Y H:i:s'); var reportDate = Ext.Date.format(new Date(confirm.reportDate), 'd.m.Y'); Ext.getCmp('edConfirmRespName').setText(confirmData.respondentName); Ext.getCmp('edConfirmRepDate').setText(reportDate); Ext.getCmp('edConfirmProduct').setText(confirm.productName?confirm.productName: label_UNKNOWN); Ext.getCmp('edConfirmStatusName').setText(confirm.statusName?confirm.statusName: label_UNKNOWN); Ext.getCmp('edConfirmFirstBatchLoadTime').setText(firstBatchLoadTime); Ext.getCmp('edConfirmLastBatchLoadTime').setText(lastBatchLoadTime); Ext.getCmp('edConfirmCrossCheckResult').setText(confirm.crossCheckStatusName?confirm.crossCheckStatusName:label_UNKNOWN); }, failure: function (response, opts) { Ext.Msg.alert(label_ERROR,''); } }); var layout = Ext.getCmp('mainPanel').getLayout(); if (layout.getNext()) { layout.next(); } } var uploadStore = Ext.create('Ext.data.Store', { fields: ['name', 'size', 'file', 'status'] }); Ext.define('fileModel', { extend: 'Ext.data.Model', fields: ['id', 'fileName'] }); Ext.define('respondentModel', { extend: 'Ext.data.Model', fields: ['id', 'name', 'shortName', 'code', 'subjectType'] }); Ext.define('confirmModel', { extend: 'Ext.data.Model', fields: ['respondentId', 'respondentName', 'statusId', 'reportDate', 'firstBatchLoadTime', 'lastBatchLoadTime', 'editTime', 'userName', 'statusName', 'productName'] }); Ext.define('confirmStageModel', { extend: 'Ext.data.Model', fields: ['id', 'statusName', 'stageDate', 'userId', 'userName', 'userPosName'] }); Ext.define('messageModel', { extend: 'Ext.data.Model', fields: ['id', 'userName', 'sendDate', 'text', 'confirmId', 'files'] }); var bankRFilter = new Ext.util.Filter({ filterFn: function (item) { var obj = item.get('subjectType'); return obj.id != '9' ? true : false; } }); var bvuFilter = new Ext.util.Filter({ filterFn: function (item) { var obj = item.get('subjectType'); return obj.id != '3' ? true : false; } }); var bpuFilter = new Ext.util.Filter({ filterFn: function (item) { var obj = item.get('subjectType'); return obj.id != '4' ? true : false; } }); var elseorgFilter = new Ext.util.Filter({ filterFn: function (item) { var obj = item.get('subjectType'); return obj.id != '1' ? true : false; } }); var ipotechFilter = new Ext.util.Filter({ filterFn: function (item) { var obj = item.get('subjectType'); return obj.id != '2' ? true : false; } }); var messageStore = Ext.create('Ext.data.Store', { id: 'messageStore', model: 'messageModel', autoLoad: false, listeners: { load: function () { messageGrid.getSelectionModel().select(0); }, scope: this }, proxy: { type: 'ajax', url: dataUrl + '/core/confirm/getMessagesByConfirmId', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } } }); var fileStore = Ext.create('Ext.data.Store', { id: 'fileStore', model: 'fileModel', autoLoad: false, proxy: { type: 'ajax', url: dataUrl + '/core/confirm/getFilesByMessageId', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } } }); var messageGrid = Ext.create('Ext.grid.Panel', { id: 'messageGrid', store: messageStore, multiSelect: true, viewConfig: { emptyText: label_NO_DATA }, height: 100, title: label_MESSAGES, columns: [{ text: label_SENDLER, dataIndex: 'userName', flex: 1 }, { text: label_TEXT, flex: 1, dataIndex: 'text', renderer: function(value, metaData, record, rowIndex, colIndex, store, view) { return !value? label_NO_MESSAGE: value; } }, { text: label_DATE_TIME, flex: 1, dataIndex: 'sendDate', renderer: Ext.util.Format.dateRenderer('d.m.Y H:i:s') }, { text: label_ATTACH_FILES, flex: 1, dataIndex: 'files', renderer: function(value, metaData, record, rowIndex, colIndex, store, view) { var text = ''; for (var i = 0; i < value.length; i++) { var file = value[i]; if (i > 0) text += ', '; text += file.fileName; } return text; } }], listeners: { cellclick: function (grid, td, cellIndex, newValue, tr, rowIndex, e, eOpts, but) { var messageData = messageGrid.getSelectionModel().getLastSelected().data; fileGrid.store.load({ params: { messageId: messageData.id }, scope: this }); fileGrid.getView().refresh(); } } }); var fileGrid = Ext.create('Ext.grid.Panel', { id: 'fileGrid', store: fileStore, height: 100, viewConfig: { emptyText: label_NO_ATTACH }, title: label_ATTACH_FILES, columns: [{ header: label_FILE_NAME, dataIndex: 'fileName', flex: 1 }, { header: label_DOWNLOAD, xtype: 'actioncolumn', width: 40, flex: 1, sortable: false, items: [{ icon: contextPathUrl + '/pics/download.png', tooltip: label_DOWNLOAD, handler: function (grid, rowIndex, colIndex) { var file = fileStore.getAt(rowIndex).data; var xhr = new XMLHttpRequest(); xhr.open('GET', dataUrl + '/core/confirm/getMessageFileContent?fileId=' + file.id, true); xhr.responseType = 'arraybuffer'; xhr.onload = function (oEvent) { if (xhr.status == 200) { var responseArray = new Uint8Array(this.response); var blob = new Blob([responseArray]); saveAs(blob, file.fileName); } else { Ext.Msg.alert(label_ERROR,''); } }; xhr.send(); } }] }] }); var respondentStore = Ext.create('Ext.data.Store', { id: 'respondentStore', model: 'respondentModel', remoteSort: true, autoLoad: true, listeners: { load: function () { respondentGrid.getSelectionModel().selectAll(); }, scope: this }, proxy: { type: 'ajax', url: dataUrl + '/core/respondent/getRespondentList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } } }); var confirmStageStore = Ext.create('Ext.data.Store', { id: 'confirmStageStore', model: 'confirmStageModel', autoLoad: false, proxy: { type: 'ajax', url: dataUrl + '/core/confirm/getConfirmStageJsonList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: '', totalProperty: 'total' } } }); var confirmStageGrid = Ext.create('Ext.grid.Panel', { title: label_HISTORY, viewConfig: { emptyText: label_NO_DATA }, id: 'confirmStageGrid', height: 150, store: confirmStageStore, columns: [{ text: label_USER, dataIndex: 'userName', width: 200, heigt: 200, flex: 1 }, { text: label_POSITION, dataIndex: 'userPosName', flex: 1 }, { text: label_STATUS, dataIndex: 'statusName', flex: 1 }, { text: label_D_T, dataIndex: 'stageDate', renderer: Ext.util.Format.dateRenderer('d.m.Y H:i:s'), flex: 1 }, { header: label_DOWNLOAD_CON, xtype: 'actioncolumn', width: 40, flex: 1, sortable: false, items: [{ icon: contextPathUrl + '/pics/download.png', tooltip: label_DOWNLOAD, handler: function (grid, rowIndex, colIndex) { var confirmStage = confirmStageStore.getAt(rowIndex).data; var xhr = new XMLHttpRequest(); xhr.open('GET', dataUrl + '/core/confirm/getConfirmDocument?id=' + confirmStage.id, true); xhr.responseType = 'arraybuffer'; xhr.onload = function (oEvent) { if (xhr.status == 200) { var responseArray = new Uint8Array(this.response); var blob = new Blob([responseArray]); saveAs(blob, 'Соглашение.pdf'); } else { Ext.Msg.alert(label_ERROR,''); } }; xhr.send(); } }] }] }); var respondentGrid = Ext.create('Ext.grid.Panel', { id: 'respondentGrid', multiSelect: true, hideHeaders: true, store: respondentStore, columns: [{ text: label_RESP, dataIndex: 'name', width: 200, heigt: 200, flex: 1 }] }); var confirmStore = Ext.create('Ext.data.Store', { id: 'confirmStore', multiSelect: true, model: 'confirmModel', remoteSort: true, autoLoad: !isNb, proxy: { type: 'ajax', url: dataUrl + '/core/confirm/getConfirmList', actionMethods: { read: 'GET' }, extraParams: { userId: userId, isNb: isNb }, reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); var confirmGrid = Ext.create('Ext.grid.Panel', { id: 'confirmGrid', multiSelect: true, store: confirmStore, viewConfig: { emptyText: label_NO_DATA }, columns: [{ text: label_RESP_NAME, dataIndex: 'respondentName', flex: 1 }, { text: label_PRODUCT, dataIndex: 'productName', flex: 1 }, { text: label_STATUS, dataIndex: 'statusName', flex: 1 }, { text: label_REP_DATE, dataIndex: 'reportDate', format: 'Y.m.d', renderer: Ext.util.Format.dateRenderer('d.m.Y'), flex: 1 }, { text: label_FIRST_DATE, dataIndex: 'firstBatchLoadTime', format: 'd.m.Y H:i:s', renderer: Ext.util.Format.dateRenderer('d.m.Y H:i:s'), flex: 1 }, { text: label_LAST_DATE, dataIndex: 'lastBatchLoadTime', format: 'd.m.Y H:i:s', renderer: Ext.util.Format.dateRenderer('d.m.Y H:i:s'), flex: 1 }], listeners: { cellclick: function (grid, td, cellIndex, newValue, tr, rowIndex, e, eOpts, but) { showConfirmInfo(); } } }); var buttonShowConfirms = Ext.create('Ext.button.Button', { id: 'buttonShowConfirms', text: label_VIEW, handler: function() { if (isNb) { Ext.getCmp('downPanel').setVisible(true); var respondentIds = []; for (var i = 0; i < respondentGrid.store.getCount(); i++) { if (respondentGrid.getSelectionModel().isSelected(i)) { respondentIds.push(respondentGrid.store.getAt(i).data.id); } } confirmGrid.store.load({ params: { userId: userId, isNb: isNb, respondentIds: respondentIds, reportDate: Ext.Date.format(Ext.getCmp('edRepDate').getValue(), 'Y-m-d') }, scope: this }); } else { confirmGrid.store.load({ params: { userId: userId, isNb: isNb, reportDate: Ext.Date.format(Ext.getCmp('edRepDate').getValue(), 'Y-m-d') }, scope: this }); } confirmGrid.getView().refresh(); } }); var buttonConfirm = Ext.create('Ext.button.Button', { id: 'buttonConfirm', text: label_CONF, handler: function() { showConfirmWindow(); } }); if (isNb) { // кнопки регулятора не доступны респондентам buttonConfirm.setVisible(false); } var buttonBack = Ext.create('Ext.button.Button', { id: 'buttonBack', hidden: true, text: label_BACK, handler: function() { Ext.getCmp('buttonBack').setVisible(false); var layout = mainPanel.getLayout(); if (layout.getPrev()) { layout.prev(); } } }); var buttonAddMessage = Ext.create('Ext.button.Button', { id: 'buttonAddMessage', text: label_ADD_MESS, handler: function() { var text = Ext.getCmp('newMessageText').getValue(); if (text.length == 0) { Ext.Msg.alert(label_ERROR, label_FILL); return; } var loadMask = new Ext.LoadMask(Ext.getCmp('mainPanel'), {msg: label_WAIT}); loadMask.show(); var xhr = new XMLHttpRequest(); var formData = new FormData(); var confirmData = Ext.getCmp('confirmGrid').getSelectionModel().getLastSelected().data; var uploadUrl = dataUrl + '/core/confirm/addConfirmMessage?confirmId=' + confirmData.id + '&userId=' + userId + '&text=' + text; xhr.open('POST', uploadUrl, true); xhr.onreadystatechange = function() { loadMask.hide(); if (xhr.readyState == 4 && xhr.status == 200) { Ext.Msg.alert(label_INFO, label_SENDED_MESS); } else if (xhr.readyState == 4 && xhr.status != 200) { Ext.Msg.alert(label_ERROR,''); } messageGrid.getStore().reload(); messageGrid.getView().refresh(); var lblAttachments = Ext.getCmp('lblAttachments'); lblAttachments.setText(''); }; for (var i = 0; i < uploadStore.data.items.length; i++) { var data = uploadStore.getAt(i).data; formData.append('file', data.file); } // удаляю все прикрепленные файлы uploadStore.reload(); xhr.send(formData); } }); var newMessagePanel = Ext.create('Ext.Panel', { xtype: 'panel', autoScroll: true, id: 'messagePanel', title: label_NEW_MESS, layout: 'vbox', tbar: [buttonAddMessage, {xtype: 'label', text: label_ATTACHES}, {xtype: 'label', id: 'lblAttachments', text: label_NO_FILES} ], bbar: [{ xtype: 'filefield', name: 'file', id: 'attachFile', buttonOnly: true, hideLabel: true, buttonText: label_ATTACHING, msgTarget: 'side', listeners: { afterrender: function(cmp) { cmp.fileInputEl.set({ multiple:'multiple' }); }, change: function (cmp) { var lblAttachments = Ext.getCmp('lblAttachments'); lblAttachments.setText(''); uploadStore.reload(); var attachments = ''; Ext.Array.forEach(Ext.Array.from(cmp.fileInputEl.dom.files), function (file) { uploadStore.add({ file: file, name: file.name, size: file.size }); if (attachments.length > 0) attachments += ', '; attachments += file.name; }); lblAttachments.setText(attachments); } } }], items: [{ xtype: 'htmleditor', id: 'newMessageText', width: '100%', height: 100 }] }); var confirmInfoPanel = Ext.create('Ext.Panel', { title: label_DETAILS, height: 200, width: '100%', layout: { type: 'table', columns: 2, tableAttrs: { style: { width: '60%' } } }, items: [{ xtype: 'label', text: label_RESPONDENT }, { xtype: 'label', id: 'edConfirmRespName' }, { xtype: 'label', text: label_FIRST_DATE }, { xtype: 'label', id: 'edConfirmFirstBatchLoadTime' }, { xtype: 'label', text: label_LAST_DATE }, { xtype: 'label', id: 'edConfirmLastBatchLoadTime' }, { xtype: 'label', text: label_PRODUCT }, { xtype: 'label', id: 'edConfirmProduct' }, { xtype: 'label', text: label_CROSSCHECK }, { xtype: 'label', id: 'edConfirmCrossCheckResult' }, { xtype: 'label', text: label_REP_DATE }, { xtype: 'label', id: 'edConfirmRepDate' }, { xtype: 'label', text: label_STATUS }, { xtype: 'label', id: 'edConfirmStatusName' }, buttonConfirm] }); var confirmDataPanel = Ext.create('Ext.Panel', { title: '', items: [confirmInfoPanel, confirmStageGrid, messageGrid, fileGrid, newMessagePanel] }); var filterPanel = Ext.create('Ext.Panel', { title: label_RESP, hidden: !isNb, height: 50, layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'checkbox', boxLabel: label_R, id: 'cbBankDev', checked: 'true', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp('respondentGrid'); if (newValue == '1') { grid.store.removeFilter(bankRFilter); } else if (newValue == '0') { grid.store.addFilter(bankRFilter); } } } }, { xtype: 'checkbox', boxLabel: label_VU, id: 'cbBankSecondLev', checked: 'true', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp('respondentGrid'); if (newValue == '1') { grid.store.removeFilter(bvuFilter); } else if (newValue == '0') { grid.store.addFilter(bvuFilter); } } } }, { xtype: 'checkbox', boxLabel: label_PU, id: 'cbBankFirstLev', checked: 'true', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp('respondentGrid'); if (newValue == '1') { grid.store.removeFilter(bpuFilter); } else if (newValue == '0') { grid.store.addFilter(bpuFilter); } } } }, { xtype: 'checkbox', boxLabel: label_IO, id: 'cbIpotekaOrg', checked: 'true', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp('respondentGrid'); if (newValue == '1') { grid.store.removeFilter(elseorgFilter); } else if (newValue == '0') { grid.store.addFilter(elseorgFilter); } } } }, { xtype: 'checkbox', boxLabel: label_OTHER, id: 'cbOtherOrg', checked: 'true', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp('respondentGrid'); if (newValue == '1') { grid.store.removeFilter(ipotechFilter); } else if (newValue == '0') { grid.store.addFilter(ipotechFilter); } } } }, { xtype: 'button', text: label_SELECT_ALL, id: 'btnChooseAll', heigt: 20, listeners: { click: function () { Ext.getCmp('cbBankDev').setValue(true); Ext.getCmp('cbBankSecondLev').setValue(true); Ext.getCmp('cbBankFirstLev').setValue(true); Ext.getCmp('cbIpotekaOrg').setValue(true); Ext.getCmp('cbOtherOrg').setValue(true); } } }, { xtype: 'button', text: label_OFF_SELECTED, id: 'btnDeSelectAll', heigt: 20, listeners: { click: function () { Ext.getCmp('cbBankDev').setValue(false); Ext.getCmp('cbBankSecondLev').setValue(false); Ext.getCmp('cbBankFirstLev').setValue(false); Ext.getCmp('cbIpotekaOrg').setValue(false); Ext.getCmp('cbOtherOrg').setValue(false); } } }] }); var edRespSearch = { xtype: 'textfield', id: 'textfield', hidden: !isNb, name: 'searchfield', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp('respondentGrid'); if (newValue == '') { grid.store.clearFilter(); if (Ext.getCmp('cbBankDev').checked == false) { grid.store.addFilter(bankRFilter) }; if (Ext.getCmp('cbBankSecondLev').checked == false) { grid.store.addFilter(bvuFilter) }; if (Ext.getCmp('cbBankFirstLev').checked == false) { grid.store.addFilter(bpuFilter) }; if (Ext.getCmp('cbOtherOrg').checked == false) { grid.store.addFilter(elseorgFilter) }; if (Ext.getCmp('cbIpotekaOrg').checked == false) { grid.store.addFilter(ipotechFilter) }; grid.getView().refresh(); } else { grid.store.filter([{ property: 'name', value: newValue, anyMatch: true, caseSensitive: false }]); } } } }; var confirmListPanel = Ext.create('Ext.Panel', { title: '', items: [{ xtype: 'panel', title: '', layout: { type: 'vbox', align: 'stretch' }, items: [ filterPanel, edRespSearch, // панель кредиторов { xtype: 'panel', id: 'respondents', hidden: !isNb, title: '', height: 200, overflowY: 'scroll', items: [respondentGrid] }, // панель управления { xtype: 'panel', title: '', hidden: !isNb, height: 50, items: [{ xtype: 'button', text: label_ALL, id: 'btnChooseAllRespondent', height: 30, width: 200, listeners: { click: function () { Ext.getCmp('respondentGrid').getSelectionModel().selectAll(); } } }] }, { xtype: 'panel', title: '', height: 35, items: [ { xtype: 'label', type: 'vbox', text: label_REP_DATE }, { xtype: 'datefield', id: 'edRepDate', format: 'd.m.Y', anchor: '100%', width: 200, maxValue: new Date() } ] }, { xtype: 'panel', title: '', height: 25, layout: { type: 'hbox' }, items: [buttonShowConfirms] }, { xtype: 'panel', id: 'downPanel', title: '', overflowY: 'scroll', height: 400, items: [confirmGrid] } ] }] }); var mainPanel = Ext.create('Ext.Panel', { title: label_CONFIRMATION, id: 'mainPanel', width: 1160, layout: 'card', items: [confirmListPanel, confirmDataPanel], tbar: [ buttonBack ], renderTo: 'confirm-content' }); }); <file_sep>package kz.bsbnb.usci.receiver.batch.service; import kz.bsbnb.usci.receiver.model.BatchEntry; import java.util.List; public interface BatchEntryService { Long save(BatchEntry batchEntry); BatchEntry load(Long batchEntryId); List<BatchEntry> getBatchEntriesByUserId(Long userId); void delete(Long batchEntryId); void confirmBatchEntries(Long userId, boolean isNb); } <file_sep>package kz.bsbnb.usci.receiver.batch.service; public interface BatchMaintenanceService { void confirmBatchMaintenance(Long batchId); } <file_sep>package kz.bsbnb.usci.mail.controller; import kz.bsbnb.usci.mail.model.UserMailTemplate; import kz.bsbnb.usci.mail.model.UserMailTemplateList; import kz.bsbnb.usci.mail.model.dto.MailMessageDto; import kz.bsbnb.usci.mail.service.MailService; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author <NAME> */ @RestController @RequestMapping(value = "mail") public class MailController { private final MailService mailService; public MailController(MailService mailService) { this.mailService = mailService; } @PutMapping(value = "sendMail") public void sendMail(@RequestBody MailMessageDto mailMessageDto) { mailService.sendMail(mailMessageDto); } @GetMapping(value = "getUserMailTemplateList") public List<UserMailTemplate> getUserMailTemplateList(@RequestParam(name = "userId") Long userId) { return mailService.getUserMailTemplateList(userId); } @PostMapping(value = "saveUserMailTemplateList") public void saveUserMailTemplateList(@RequestBody UserMailTemplateList userMailTemplateList) { mailService.saveUserMailTemplateList(userMailTemplateList.getUserMailTemplateList()); } } <file_sep>group = 'kz.bsbnb.usci.util' version '0.1.0' dependencies { compile project(':model') compile project(':util:util-api') compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-jdbc") compile("com.oracle:${ojdbcVersion}") } jar { baseName = 'usci-util-core' enabled = true } bootJar { enabled = false } <file_sep>var label_ERROR = 'Ошибка'; var label_REP_DATE = 'Отчетная дата'; var label_DOWN_PRO = 'Загрузить профили'; var label_SPISOK = 'Список профилей'; var label_PROTECTED = 'Профиль защищен паролем'; var label_PASSWORD = '<PASSWORD>'; var label_GET_SERT = 'Получить сертификаты из профиля'; var label_GET_ERROR = 'Не удалось получить список сертификатов'; var label_SERTIFICATE = 'Сертификат'; var label_SIGN = 'Подписать'; var label_PRESS = 'Нажмите'; var label_CHOOSE_P = 'Выберите профиль'; var label_CHOOSE_S = 'Выберите сертификат'; var label_WAIT = 'Подождите...'; var label_INFO = 'Информация'; var label_REP_CONFIRMED = 'Отчет подтвержден'; var label_CONFIRM = 'Подтвердить'; var label_SHOW = 'Показать соглашение'; var label_UNKNOWN = 'Не известен'; var label_NO_DATA = 'Нет данных для отображения'; var label_MESSAGES = 'Сообщения'; var label_SENDLER = 'Отправитель'; var label_TEXT = 'Текст сообщения'; var label_NO_MESSAGE = 'Без сообщения'; var label_DATE_TIME = 'Дата/Время отправки'; var label_ATTACH_FILES = 'Прикреленные файлы'; var label_NO_ATTACH = 'Нет прикрепленных файлов'; var label_FILE_NAME = 'Наименование файла'; var label_DOWNLOAD = 'Скачать'; var label_HISTORY = 'История подтверждения'; var label_USER = 'Пользователь'; var label_POSITION = ''; var label_STATUS = 'Статус'; var label_D_T = 'Дата/Время'; var label_DOWNLOAD_CON = 'Скачать соглашение'; var label_RESP = 'Респонденты'; var label_RESP_NAME = 'Наименование респондента'; var label_PRODUCT = 'Продукт'; var label_FIRST_DATE = 'Дата первого приема информации'; var label_LAST_DATE = 'Дата последнего приема информации'; var label_VIEW = 'Показать'; var label_CONF = 'Утвердить'; var label_BACK = '<- Вернуться к списку'; var label_ADD_MESS = 'Добавить сообщение'; var label_FILL = 'Заполните текст сообщения'; var label_SENDED_MESS = 'Сообщение отправлено'; var label_NEW_MESS = 'Новое сообщение'; var label_ATTACHES = 'Прикрепленные файлы:'; var label_NO_FILES = 'Нет файлов'; var label_ATTACHING = 'Прикрепить файлы'; var label_DETAILS = 'Реквизиты'; var label_RESPONDENT = 'Респондент:'; var label_CROSSCHECK = 'Результат межформенного контроля:'; var label_R = 'Банк развития'; var label_VU = 'Банк второго уровня'; var label_PU = 'Банк первого уровня'; var label_IO = 'Ипотечная организация'; var label_OTHER = 'Прочие организации, осуществляющие отдельные виды банковских операций'; var label_SELECT_ALL = 'Выбрать все'; var label_OFF_SELECTED = 'Снять выделение'; var label_ALL = 'Выделить все'; var label_CONFIRMATION = 'Подтверждение'; <file_sep> package kz.bsbnb.usci.wsclient.jaxb.kgd; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for statusType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="statusType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="code" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="date" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "statusType", propOrder = { "code", "description", "date" }) public class StatusType { @XmlElement(required = true) protected String code; @XmlElement(required = true) protected String description; @XmlElement(required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar date; /** * Gets the value of the code property. * * @return * possible object is * {@link String } * */ public String getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link String } * */ public void setCode(String value) { this.code = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the date property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDate() { return date; } /** * Sets the value of the date property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDate(XMLGregorianCalendar value) { this.date = value; } } <file_sep>package kz.bsbnb.usci.portlet.queue_portlet; import com.liferay.util.bridges.mvc.MVCPortlet; public class QueuePortlet extends MVCPortlet { } <file_sep>package kz.bsbnb.usci.receiver.parser.impl; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseValue; import kz.bsbnb.usci.receiver.parser.BatchParser; import kz.bsbnb.usci.receiver.parser.exceptions.UnknownTagException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.xml.sax.SAXException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.time.LocalDate; import java.time.format.DateTimeParseException; /** * @author <NAME> * @author <NAME> */ @Component @Scope("prototype") public class ChangeParser extends BatchParser { @Autowired private ChangeTurnoverParser changeTurnoverParser; @Autowired private ChangeRemainsParser changeRemainsParser; @Autowired private ChangeCreditFlowParser changeCreditFlowParser; private BaseValue maturityDate; private BaseValue prolongationDate; public ChangeParser() { super(); } @Override public void init() { currentBaseEntity = new BaseEntity(metaClassRepository.getMetaClass("change"), respondentId, batch.getReportDate(), batch.getId()); maturityDate = null; prolongationDate = null; } @Override public boolean startElement(XMLEvent event, StartElement startElement, String localName) throws SAXException { switch (localName) { case "change": break; case "turnover": changeTurnoverParser.parse(xmlReader, batch, index, respondentId); currentBaseEntity.put("turnover", new BaseValue(changeTurnoverParser.getCurrentBaseEntity())); break; case "remains": changeRemainsParser.parse(xmlReader, batch, index, respondentId); currentBaseEntity.put("remains", new BaseValue(changeRemainsParser.getCurrentBaseEntity())); break; case "credit_flow": changeCreditFlowParser.parse(xmlReader, batch, index, respondentId); currentBaseEntity.put("credit_flow", new BaseValue(changeCreditFlowParser.getCurrentBaseEntity())); break; case "maturity_date": { event = (XMLEvent) xmlReader.next(); String dateRaw = trim(event.asCharacters().getData()); try { maturityDate = new BaseValue(LocalDate.parse(dateRaw)); } catch (DateTimeParseException e) { currentBaseEntity.addValidationError("Неправильная дата: " + dateRaw); } break; } case "prolongation_date": { event = (XMLEvent) xmlReader.next(); String dateRaw = trim(event.asCharacters().getData()); try { prolongationDate = new BaseValue(LocalDate.parse(dateRaw)); } catch (DateTimeParseException e) { currentBaseEntity.addValidationError("Неправильная дата: " + dateRaw); } break; } default: throw new UnknownTagException(localName); } return false; } @Override public boolean endElement(String localName) throws SAXException { switch (localName) { case "change": return true; case "turnover": break; case "remains": for (String e : changeRemainsParser.getCurrentBaseEntity().getValidationErrors()) getCurrentBaseEntity().addValidationError(e); changeRemainsParser.getCurrentBaseEntity().clearValidationErrors(); break; case "credit_flow": break; case "maturity_date": break; case "prolongation_date": break; default: throw new UnknownTagException(localName); } return false; } BaseValue getMaturityDate() { return maturityDate; } BaseValue getProlongationDate() { return prolongationDate; } } <file_sep>package kz.bsbnb.usci.eav.model.meta.json; import kz.bsbnb.usci.model.batch.Product; import java.util.HashSet; import java.util.Set; /** * @author <NAME> * @author <NAME> */ public class ProductJson { private Long id; private String code; private String name; private Boolean confirmWithApproval = false; private Boolean confirmWithSignature = false; private Set<Long> confirmPositionIds = new HashSet<>(); private String crosscheckPackageName; public ProductJson() { super(); } public ProductJson(Product product) { this.id = product.getId(); this.code = product.getCode(); this.name = product.getName(); this.crosscheckPackageName = product.getCrosscheckPackageName(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean getConfirmWithApproval() { return confirmWithApproval; } public void setConfirmWithApproval(boolean confirmWithApproval) { this.confirmWithApproval = confirmWithApproval; } public boolean getConfirmWithSignature() { return confirmWithSignature; } public void setConfirmWithSignature(boolean confirmWithSignature) { this.confirmWithSignature = confirmWithSignature; } public Set<Long> getConfirmPositionIds() { return confirmPositionIds; } public void setConfirmPositionIds(Set<Long> confirmPositionIds) { this.confirmPositionIds = confirmPositionIds; } public String getCrosscheckPackageName() { return crosscheckPackageName; } public void setCrosscheckPackageName(String crosscheckPackageName) { this.crosscheckPackageName = crosscheckPackageName; } } <file_sep>Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.selection.CellModel', 'Ext.grid.*', 'Ext.data.*' ]); var ruleListGrid = null; var packageStore = null; function deleteRule(rowIndex){ Ext.Ajax.request({ url: dataUrl+'/rule/deleteRule', method: 'POST', waitMsg: 'adding', params : { ruleId: editor.ruleId, packageId: Ext.getCmp('elemComboPackage').value, pkgName: Ext.getCmp('elemComboPackage').getRawValue(), date: Ext.getCmp('elemPackageVersionCombo').value }, reader: { type: 'json', root: 'data' }, success: function(response, opts) { Ext.Msg.alert('', label_DELETED); rowIndex = (typeof rowIndex === 'undefined') ? -1 : rowIndex; ruleListGrid.store.removeAt(rowIndex); if (ruleListGrid.store.data.length == 0) reset(); else { ruleListGrid.getSelectionModel().select(0); ruleListGrid.fireEvent("cellclick", ruleListGrid, null, 1, ruleListGrid.getSelectionModel().getLastSelected()); } }, failure: function(response, opts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); } function initGrid(){ var store = Ext.create('Ext.data.ArrayStore', { fields: ['id','name','isActive'], proxy: { type: 'ajax', url : dataUrl+'/rule/getRuleTitles', reader: { type: 'json', root: 'data' } } }); ruleListGrid = Ext.create('Ext.grid.Panel', { store: store, columns: [ { text : label_NAME, dataIndex: 'name', width: 200, flex: 1, field: { allowBlank: false } } ], listeners : { cellclick: function(grid, td, cellIndex, newValue, tr, rowIndex, e, eOpts){ Ext.Ajax.request({ url: dataUrl+'/rule/getRule', method: 'GET', waitMsg: 'adding', params: { ruleId: newValue.data.id, date: Ext.getCmp('elemPackageVersionCombo').value }, reader: { type: 'json', root: 'data' }, success: function(response, opts) { var obj = JSON.parse(response.responseText); editor.title = obj.title; editor.backup = obj.rule; editor.ruleId = newValue.data.id; editor.infIndex = newValue.index; editor.setValue(obj.rule, -1); editor.$readOnly = false; }, failure: function(response, opts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); } }, plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 2 })], dockedItems: [{ xtype: 'toolbar', items: [{ text: label_ADD, hidden: !isDataManager, icon: contextPathUrl + '/pics/add.png', id: 'btnNewRule', //hidden: readOnly, handler: function(e1,e2){ newRuleForm().show(); require(['ace/ace'],function(ace){ newRuleEditor = ace.edit('bknew-rule'); }); } }, { text: label_CANCEL, hidden: !isDataManager, icon: contextPathUrl + '/pics/bin.png', // hidden: readOnly, id: 'btnFlush', handler: function(){ var loadMask = new Ext.LoadMask(Ext.getBody(), { msg: label_WAIT }); loadMask.show(); Ext.Ajax.request({ url: dataUrl+'/rule/reloadCache', method: 'POST', waitMsg: 'adding', reader: { type: 'json' }, actionMethods: { read: 'POST', root: 'data' }, success: function(response, opts) { loadMask.hide(); Ext.Msg.alert(label_INFO, label_CACHE); }, failure: function(response, opts) { loadMask.hide(); var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERR_CACHE, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); } },{ text: label_HISTORY, id: 'btnHistory', icon: contextPathUrl + '/pics/copy2.png', hidden: true, disabled: true, handler: function(){ //createRuleForm().show(); historyForm(ruleListGrid.getSelectionModel().getLastSelected().data.id).show(); } },{ text: lable_REFRESH, id: 'btnRefresh', icon: contextPathUrl + '/pics/refresh.png', handler: function(){ updateRules(); } },{ text: label_POCKETS, hidden: !isDataManager, id: 'btnPackages', //hidden: readOnly, handler: function(){ packageControlForm().show(); } },{ text: label_SEARCH, id: 'btnSearch', icon: contextPathUrl + '/pics/search.png', handler: function(){ Ext.getCmp('txtSearch').show(); Ext.getCmp('txtSearch').focus(false,200); } },{ xtype: 'textfield', id: 'txtSearch', hidden: true, listeners: { render: function(cmd) { cmd.getEl().on('click',function(){Ext.EventObject.stopPropagation();}); }, scope: this, specialkey: function(f,e) { if(e.getKey() == e.ENTER) { updateRules(Ext.getCmp('txtSearch').value); } else if(e.getKey() == e.ESC) { Ext.getCmp('txtSearch').hide(); } } } }] }], height: '75%', region: 'south' }); ruleListGrid.on('edit', function(e,r){ if(readOnly) return; Ext.Ajax.request({ url: dataUrl+'/rule/renameRule', method: 'PUT', waitMsg: 'adding', params : { ruleId: ruleListGrid.getSelectionModel().getLastSelected().data.id, title: r.value }, reader: { type: 'json', root: 'data' }, success: function(response, opts) { }, failure: function(response, opts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); }, this); return ruleListGrid; } function reset(){ editor.setValue("",-1); editor.$readOnly = true; editor.batchVersionId = -1; editor.backup = ""; Ext.getCmp('btnCancel').setDisabled(true); Ext.getCmp('btnSave').setDisabled(true); Ext.getCmp('btnDel').setDisabled(true); ruleListGrid.store.loadData([],false); } function updateRules(searchText){ if(Ext.getCmp('elemComboPackage').value == null || Ext.getCmp('elemPackageVersionCombo').value == null) return; reset(); ruleListGrid.store.load( { params: { packageId:Ext.getCmp('elemComboPackage').value, date: Ext.getCmp('elemPackageVersionCombo').value, searchText: searchText }, callback: function(a,b,success){ if(success == false){ Ext.Msg.alert('',label_NO_VERSION); reset(); }else{ editor.batchVersionId = Ext.decode(b.response.responseText).batchVersionId; } }, scope: this } ); ruleListGrid.getView().refresh(); } Ext.onReady(function(){ Ext.define('packageListModel',{ extend: 'Ext.data.Model', fields: ['name'] }); var map1 = new Ext.util.KeyMap(document,{ key: "s", ctrl: true, shift: true, fn: function(){ if(editor.isFocused()){ Ext.getCmp('btnSave').handler(); } } } ); var map2 = new Ext.util.KeyMap(document,{ key: "a", ctrl: true, shift: true, fn: function(){ Ext.getCmp('btnNewRule').handler(); } } ); var map3 = new Ext.util.KeyMap(document,{ key: "e", ctrl: true, shift: true, fn: function(){ Ext.getCmp('btnRun').handler(); } } ); var map4 = new Ext.util.KeyMap(document,{ key: "f", ctrl: true, shift: true, fn: function(){ Ext.getCmp('btnFlush').handler(); } } ); packageStore = Ext.create('Ext.data.Store',{ id: 'packageStore', model: 'packageListModel', proxy: { type: 'ajax', url: dataUrl+'/package/getAllPackages', listeners : { exception: function(proxy, response, operation, eOpts) { var r = JSON.parse(response.responseText); if(r.errorMessage) { Ext.Msg.show({ title: label_ERROR, msg: r.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); } } }, reader: { type: 'json', root: 'data' } }, autoLoad: true, listeners: { load: function(me, records, options) { if (records.length > 0) Ext.getCmp('elemComboPackage').setValue(records[0].get('id')); } } }); packageVersionStore = Ext.create('Ext.data.Store',{ id: 'packageVersionStore', model: 'packageListModel', proxy: { type: 'ajax', url: dataUrl+'/rule/getPackageVersions', reader: { type: 'json', root: 'data' } } }); var panel = Ext.create('Ext.panel.Panel',{ title : '', width : '100%', height : 600, renderTo: 'brms-content', layout : 'border', id: 'MainPanel', defaults : { split: true }, items: [ { region: 'east', id: 'elemRuleBody', width: '75%', html: "<div id='bkeditor'>function(){}</div>", tbar: [ { text : label_CAN, hidden: !isDataManager, //hidden: readOnly, id: 'btnCancel', icon: contextPathUrl + '/pics/undo.png', handler: function(){ editor.setValue(editor.backup, -1); }, disabled: true}, { text: label_SAVE, hidden: !isDataManager, id: 'btnSave', icon: contextPathUrl + '/pics/save.png', disabled: true, //hidden: readOnly, handler: function(){ Ext.Ajax.request({ url: dataUrl+'/rule/updateRule', method: 'PUT', waitMsg: 'adding', params : { ruleBody: editor.getSession().getValue(), ruleId: editor.ruleId, date: Ext.getCmp('elemPackageVersionCombo').value, pkgName: Ext.getCmp('elemComboPackage').getRawValue(), packageId: Ext.getCmp('elemComboPackage').value }, reader: { type: 'json', root: 'data' }, success: function(response, opts) { Ext.Msg.alert('', label_REFRESHED); ruleListGrid.fireEvent('cellclick', ruleListGrid, null, 1, ruleListGrid.getSelectionModel().getLastSelected()); //cellclick: function(grid, td, cellIndex, newValue, tr, rowIndex, e, eOpts){ }, failure: function(response, opts) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); } }, {text: label_DEL, hidden: !isDataManager, id: 'btnDel', icon: contextPathUrl + '/pics/crop2.png', disabled: true, //hidden: readOnly, handler: function(){ //Ext.Msg.alert("Сообщение","Вы точно хотите удалить правило ?"); Ext.Msg.show({ title: label_CONFIRM, msg: label_WANT_DEL, buttons: Ext.Msg.OKCANCEL, fn: function(btn){ if(btn=='ok') deleteRule(ruleListGrid.store.indexOf(ruleListGrid.getSelectionModel().getLastSelected())); } }); } }] },{ xtype: 'panel', region: 'center', layout: 'border', defaults : { split: true }, items: [ { xtype: 'panel', region: 'center', bodyStyle: 'padding: 15px', items: [ { xtype : 'combobox', id: 'elemComboPackage', editable: false, store: packageStore, valueField:'id', displayField:'name', fieldLabel: label_CHOOSE_POCK, listeners: { change: function(){ packageVersionStore.load({ params: { packageId: Ext.getCmp('elemComboPackage').value }}); } } }, { xtype: 'combobox', id: 'elemPackageVersionCombo', store: packageVersionStore, displayField: 'name', valueField: 'name', fieldLabel: label_DATE, listeners: { change: function(){ updateRules(); } } } ] }, initGrid() ] },{ region: 'south', html: label_NO_ERRORS, id: 'errorPanel', collapsible: true, collapsed: true, height: '10%' } ] } ); //end of panel });<file_sep>group = 'kz.bsbnb.usci.report' version = '0.1.0' dependencies { compile project(':report:report-api') compile project(':util:util-api') compile project(':core:core-api') compile project(':wsclient:wsclient-api') compile ('org.json:json:20090211') compile ('net.sourceforge.jexcelapi:jxl:2.6.12') compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-jdbc") compile group: 'org.apache.poi', name: 'poi', version: '4.0.1' compile group: 'org.apache.poi', name: 'poi-ooxml', version: '4.0.1' compile("com.oracle:${ojdbcVersion}") } jar { baseName = 'usci-report-core' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>package kz.bsbnb.usci.core.controller; import kz.bsbnb.usci.core.service.SubjectService; import kz.bsbnb.usci.model.respondent.SubjectType; import kz.bsbnb.usci.util.json.ext.ExtJsJson; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = "/subject") public class SubjectRestController { private final SubjectService subjectService; public SubjectRestController(SubjectService subjectService) { this.subjectService = subjectService; } @GetMapping(value = "getSubjectTypeProductPeriod") public String getSubjectTypeProductPeriod(@RequestParam(name = "subjectTypeId") Long subjectTypeId, @RequestParam(name = "productId") Long productId) { return subjectService.getSubjectTypeProductPeriod(subjectTypeId, productId); } @GetMapping(value = "getSubjectTypeList") public List<SubjectType> getSubjectTypeList() { return subjectService.getSubjectTypeList(); } @PostMapping(value = "updateSubjectType") public ExtJsJson updateSubjectTypeProductPeriod(@RequestParam(name = "subjectTypeId") Long subjectTypeId, @RequestParam(name = "productId") Long productId, @RequestParam(name = "periodId") Long periodId) { subjectService.updateSubjectTypeProductPeriod(subjectTypeId, productId, periodId); return new ExtJsJson(true); } } <file_sep>package kz.bsbnb.usci.receiver.parser.impl; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseSet; import kz.bsbnb.usci.eav.model.base.BaseValue; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.eav.model.meta.MetaDataType; import kz.bsbnb.usci.eav.model.meta.MetaValue; import kz.bsbnb.usci.receiver.parser.BatchParser; import kz.bsbnb.usci.receiver.parser.exceptions.UnknownTagException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** * @author <NAME> * @author <NAME> */ @Component @Scope("prototype") public class SubjectPersonParser extends BatchParser { @Autowired private SubjectPersonDocsParser subjectPersonDocsParser; public SubjectPersonParser() { super(); } private BaseSet names; private BaseEntity currentName; private BaseSet addresses; private BaseEntity currentAddress; private BaseSet contacts; private BaseSet bankRelations; private BaseEntity personInfo; private MetaClass refCountryMeta, refOffshoreMeta, bankRelationMeta, refBankRelationMeta, addressMeta, refRegionMeta, contactMeta, refContactTypeMeta, personNameMeta, documentMeta; @Override public void init() { currentBaseEntity = new BaseEntity(metaClassRepository.getMetaClass("subject"), respondentId, batch.getReportDate(), batch.getId()); personInfo = new BaseEntity(metaClassRepository.getMetaClass("person_info"), respondentId, batch.getReportDate(), batch.getId()); names = null; currentName = null; addresses = null; currentAddress = null; bankRelations = null; refCountryMeta = metaClassRepository.getMetaClass("ref_country"); refOffshoreMeta = metaClassRepository.getMetaClass("ref_offshore"); bankRelationMeta = metaClassRepository.getMetaClass("bank_relation"); refBankRelationMeta = metaClassRepository.getMetaClass("ref_bank_relation"); addressMeta = metaClassRepository.getMetaClass("address"); refRegionMeta = metaClassRepository.getMetaClass("ref_region"); contactMeta = metaClassRepository.getMetaClass("contact"); refContactTypeMeta = metaClassRepository.getMetaClass("ref_contact_type"); personNameMeta = metaClassRepository.getMetaClass("person_name"); documentMeta = metaClassRepository.getMetaClass("document"); } @Override public boolean startElement(XMLEvent event, StartElement startElement, String localName) throws SAXException { switch (localName) { case "person": break; case "country": event = (XMLEvent) xmlReader.next(); BaseEntity country = new BaseEntity(refCountryMeta, respondentId, batch.getReportDate(), batch.getId()); country.put("code_numeric", new BaseValue(new Integer(trim(event.asCharacters().getData())))); personInfo.put("country", new BaseValue(country)); break; case "offshore": event = (XMLEvent) xmlReader.next(); BaseEntity ref_offshore = new BaseEntity(refOffshoreMeta, respondentId, batch.getReportDate(), batch.getId()); ref_offshore.put("code", new BaseValue(trim(event.asCharacters().getData()))); personInfo.put("offshore", new BaseValue(ref_offshore)); break; case "bank_relations": bankRelations = new BaseSet(bankRelationMeta); break; case "bank_relation": event = (XMLEvent) xmlReader.next(); BaseEntity bankRelation = new BaseEntity(bankRelationMeta, respondentId, batch.getReportDate(), batch.getId()); BaseEntity refBankRelation = new BaseEntity(refBankRelationMeta, respondentId, batch.getReportDate(), batch.getId()); refBankRelation.put("code", new BaseValue(trim(event.asCharacters().getData()))); bankRelation.put("bank_relation", new BaseValue(refBankRelation)); bankRelations.put(new BaseValue(bankRelation)); break; case "addresses": addresses = new BaseSet(addressMeta); break; case "address": currentAddress = new BaseEntity(addressMeta, respondentId, batch.getReportDate(), batch.getId()); currentAddress.put("type", new BaseValue(event.asStartElement().getAttributeByName(new QName("type")).getValue())); break; case "region": event = (XMLEvent) xmlReader.next(); BaseEntity region = new BaseEntity(refRegionMeta, respondentId, batch.getReportDate(), batch.getId()); region.put("code", new BaseValue(trim(event.asCharacters().getData()))); currentAddress.put("region", new BaseValue(region)); break; case "details": event = (XMLEvent) xmlReader.next(); currentAddress.put("details", new BaseValue(trim(event.asCharacters().getData()))); break; case "contacts": contacts = new BaseSet(contactMeta); break; case "contact": BaseEntity currentContact = new BaseEntity(contactMeta, respondentId, batch.getReportDate(), batch.getId()); BaseEntity contactType = new BaseEntity(refContactTypeMeta, respondentId, batch.getReportDate(), batch.getId()); contactType.put("code", new BaseValue(event.asStartElement().getAttributeByName(new QName("contact_type")).getValue())); currentContact.put("contact_type",new BaseValue(contactType)); BaseSet contactDetails = new BaseSet(new MetaValue(MetaDataType.STRING)); event = (XMLEvent) xmlReader.next(); contactDetails.put(new BaseValue(trim(event.asCharacters().getData()))); currentContact.put("details", new BaseValue(contactDetails)); contacts.put(new BaseValue(currentContact)); break; case "names": names = new BaseSet(personNameMeta); break; case "name": currentName = new BaseEntity(personNameMeta, respondentId, batch.getReportDate(), batch.getId()); currentName.put("lang", new BaseValue(event.asStartElement().getAttributeByName(new QName("lang")).getValue())); break; case "firstname": event = (XMLEvent) xmlReader.next(); currentName.put("firstname", new BaseValue(trim(event.asCharacters().getData()))); break; case "lastname": event = (XMLEvent) xmlReader.next(); currentName.put("lastname", new BaseValue(trim(event.asCharacters().getData()))); break; case "middlename": event = (XMLEvent) xmlReader.next(); currentName.put("middlename", new BaseValue(trim(event.asCharacters().getData()))); break; case "docs": BaseSet personDocs = new BaseSet(documentMeta); while (true) { subjectPersonDocsParser.parse(xmlReader, batch, index, respondentId); if (subjectPersonDocsParser.hasMore()) { personDocs.put(new BaseValue(subjectPersonDocsParser.getCurrentBaseEntity())); } else break; } currentBaseEntity.put("docs",new BaseValue(personDocs)); break; default: throw new UnknownTagException(localName); } return false; } @Override public boolean endElement(String localName) throws SAXException { switch (localName) { case "person": currentBaseEntity.put("person_info", new BaseValue(personInfo)); currentBaseEntity.put("is_person", new BaseValue(true)); currentBaseEntity.put("is_organization", new BaseValue(false)); currentBaseEntity.put("is_creditor", new BaseValue(false)); return true; case "country": break; case "offshore": break; case "bank_relations": personInfo.put("bank_relations", new BaseValue(bankRelations)); break; case "bank_relation": break; case "addresses": personInfo.put("addresses", new BaseValue(addresses)); break; case "address": addresses.put(new BaseValue(currentAddress)); break; case "region": break; case "details": break; case "contacts": personInfo.put("contacts", new BaseValue(contacts)); break; case "contact": break; case "names": personInfo.put("names", new BaseValue(names)); break; case "name": names.put(new BaseValue(currentName)); break; case "firstname": break; case "lastname": break; case "middlename": break; case "docs": break; default: throw new UnknownTagException(localName); } return false; } } <file_sep>package kz.bsbnb.usci.eav.service; import com.google.common.collect.Lists; import kz.bsbnb.usci.eav.dao.BaseEntityRegistryDao; import kz.bsbnb.usci.eav.dao.BaseEntityStatusDao; import kz.bsbnb.usci.eav.model.Constants; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseEntityRegistry; import kz.bsbnb.usci.eav.model.core.BaseEntityStatus; import kz.bsbnb.usci.eav.model.meta.MetaAttribute; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.eav.model.meta.MetaType; import kz.bsbnb.usci.eav.repository.MetaClassRepository; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.util.Collections; import java.util.List; import java.util.Objects; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ @Service public class EntityServiceImpl implements EntityService { private static final Logger logger = LoggerFactory.getLogger(BaseEntityProcessorImpl.class); private final JdbcTemplate jdbcTemplate; private final MetaClassRepository metaClassRepository; private final BaseEntityRegistryDao baseEntityRegistryDao; private final BaseEntityStatusDao baseEntityStatusDao; public EntityServiceImpl(JdbcTemplate jdbcTemplate, MetaClassRepository metaClassRepository, BaseEntityRegistryDao baseEntityRegistryDao, BaseEntityStatusDao baseEntityStatusDao) { this.jdbcTemplate = jdbcTemplate; this.metaClassRepository = metaClassRepository; this.baseEntityRegistryDao = baseEntityRegistryDao; this.baseEntityStatusDao = baseEntityStatusDao; } /** * метод проверят имеется ли сущность за отчетную дату в таблице БД * запрос выполняется за INDEX RANGE SCAN, COST = 1 * (сочетание ENTITY_ID, REPORT_DATE, CREDITOR_ID является PRIMARY KEY) * */ @Override public boolean existsBaseEntity(BaseEntity baseEntity, LocalDate reportDate) { Objects.requireNonNull(baseEntity.getId(), String.format("Отсутствует ID у сущности %s", baseEntity)); Objects.requireNonNull(baseEntity.getRespondentId(), String.format("Отсутствует ID кредитора у сущности %s", baseEntity)); Objects.requireNonNull(baseEntity.getMetaClass(), String.format("Отсутствует мета класс у сущности %s", baseEntity)); Objects.requireNonNull(reportDate, "Отчетная дата не задана"); MetaClass metaClass = baseEntity.getMetaClass(); String query = String.format("select ENTITY_ID from %s.%s where REPORT_DATE = ? and ENTITY_ID = ? and CREDITOR_ID = ? and rownum < 2", metaClass.getSchemaData(), metaClass.getTableName()); List<Long> rows = jdbcTemplate.queryForList(query, new Object[] {SqlJdbcConverter.convertToSqlDate(reportDate), baseEntity.getId(), baseEntity.getRespondentId()}, Long.class); if (rows.size() > 1) throw new UsciException(String.format("Найдено более одной записи %s", baseEntity)); return rows.size() == 1; } @Override public long countBaseEntityEntries(BaseEntity baseEntity) { Objects.requireNonNull(baseEntity.getId(), String.format("Отсутствует ID у сущности %s", baseEntity)); Objects.requireNonNull(baseEntity.getRespondentId(), String.format("Отсутствует ID кредитора у сущности %s", baseEntity)); Objects.requireNonNull(baseEntity.getMetaClass(), String.format("Отсутствует мета класс у сущности %s", baseEntity)); MetaClass metaClass = baseEntity.getMetaClass(); String query = String.format("select count(ENTITY_ID) from %s.%s where ENTITY_ID = ? and CREDITOR_ID = ?", metaClass.getSchemaData(), metaClass.getTableName()); return jdbcTemplate.queryForObject(query, new Object[] {baseEntity.getId(), baseEntity.getRespondentId()}, Long.class); } /** * определяет существую ли ссылки на сущность из других сущностей * */ @Override public boolean hasReference(BaseEntity baseEntity) { for (MetaClass metaClass : metaClassRepository.getMetaClasses()) { for (MetaAttribute metaAttribute : metaClass.getAttributes()) { MetaType metaType = metaAttribute.getMetaType(); if (!metaType.isComplex() || metaType.isSet()) continue; MetaClass childMetaClass = (MetaClass) metaType; if (!childMetaClass.getId().equals(baseEntity.getMetaClass().getId())) continue; List<Long> list = jdbcTemplate.queryForList(String.format("select ENTITY_ID from EAV_DATA.%s where %s = ? and rownum < 2", metaClass.getTableName(), metaAttribute.getColumnName()), Long.class, baseEntity.getId()); if (list.size() > 0) return true; } } return false; } @Override public void insert(List<BaseEntityRegistry> baseEntityRegistries) { List<List<BaseEntityRegistry>> partitions = Lists.partition(baseEntityRegistries, Constants.OPTIMAL_BATCH_SIZE[1]); for (List<BaseEntityRegistry> partition: partitions) { if (partition.size() >= Constants.OPTIMAL_BATCH_SIZE[0] && partition.size() <= Constants.OPTIMAL_BATCH_SIZE[1]) baseEntityRegistryDao.insert(partition); else { for (BaseEntityRegistry baseEntityRegistry : partition) baseEntityRegistryDao.insert(Collections.singletonList(baseEntityRegistry)); } } } @Override public Long addEntityStatus(BaseEntityStatus entityStatus) { return baseEntityStatusDao.insert(entityStatus).getId(); } } <file_sep>package kz.bsbnb.usci.brms; import kz.bsbnb.usci.brms.dao.PackageDao; import kz.bsbnb.usci.brms.dao.RuleDao; import kz.bsbnb.usci.brms.exception.BrmsException; import kz.bsbnb.usci.brms.model.PackageVersion; import kz.bsbnb.usci.brms.model.Rule; import kz.bsbnb.usci.brms.model.RulePackage; import kz.bsbnb.usci.brms.model.RulePackageError; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.repository.MetaClassRepository; import kz.bsbnb.usci.eav.service.BaseEntityLoadService; import kz.bsbnb.usci.eav.service.BaseEntityProcessor; import kz.bsbnb.usci.model.exception.UsciException; import org.drools.core.command.runtime.rule.FireAllRulesCommand; import org.drools.core.impl.InternalKnowledgeBase; import org.drools.core.impl.KnowledgeBaseFactory; import org.kie.api.KieBase; import org.kie.api.command.Command; import org.kie.api.io.ResourceType; import org.kie.api.runtime.StatelessKieSession; import org.kie.api.runtime.rule.AgendaFilter; import org.kie.api.runtime.rule.Match; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.command.CommandFactory; import org.kie.internal.io.ResourceFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.ByteArrayInputStream; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * @author <NAME> * @author <NAME> */ @Component public class RulesSingleton { private final Logger logger = LoggerFactory.getLogger(RulesSingleton.class); private KieBase kieBase; private InternalKnowledgeBase kbase; public static final DateTimeFormatter ruleDateFormat = DateTimeFormatter.ofPattern("dd_MM_yyyy"); private final PackageDao packageDao; private BaseEntityProcessor baseEntityProcessor; private BaseEntityLoadService baseEntityLoadService; private MetaClassRepository metaClassRepository; protected Map<String, BaseEntity> creditorCache; private class RuleCacheEntry implements Comparable { private LocalDate repDate; private String rules; private RuleCacheEntry(LocalDate repDate, String rules) { this.repDate = repDate; this.rules = rules; } @Override public int compareTo(Object obj) { if (obj == null) return 0; if (!(getClass().equals(obj.getClass()))) return 0; return (repDate.compareTo(((RuleCacheEntry) obj).getRepDate())); } private LocalDate getRepDate() { return repDate; } private void setRepDate(LocalDate repDate) { this.repDate = repDate; } private String getRules() { return rules; } private void setRules(String rules) { this.rules = rules; } } private HashMap<String, ArrayList<RuleCacheEntry>> ruleCache = new HashMap<>(); public ArrayList<RulePackageError> rulePackageErrors = new ArrayList<>(); private RuleDao ruleDao; public StatelessKieSession getSession() { return kieBase.newStatelessKieSession(); } public RulesSingleton(PackageDao packageDao, BaseEntityProcessor baseEntityProcessor, BaseEntityLoadService baseEntityLoadService, MetaClassRepository metaClassRepository, RuleDao ruleDao) { this.packageDao = packageDao; this.baseEntityProcessor = baseEntityProcessor; this.baseEntityLoadService = baseEntityLoadService; this.metaClassRepository = metaClassRepository; this.ruleDao = ruleDao; creditorCache = new ConcurrentHashMap<>(); } @PostConstruct public void init() { reloadCache(); } public void reloadCache() { fillPackagesCache(); } public void setRules(String rules) { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newInputStreamResource(new ByteArrayInputStream(rules.getBytes())), ResourceType.DRL); if (kbuilder.hasErrors()) { throw new IllegalArgumentException(kbuilder.getErrors().toString()); } kbase.addPackages(kbuilder.getKnowledgePackages()); } public String getRuleErrors(String rule) { String packages = ""; packages += "package test \n"; packages += "dialect \"mvel\"\n"; packages += "import kz.bsbnb.usci.eav.model.base.BaseEntity;\n"; packages += "import kz.bsbnb.usci.brms.BRMSHelper;\n"; rule = packages + rule; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newInputStreamResource(new ByteArrayInputStream(rule.getBytes())), ResourceType.DRL); if (kbuilder.hasErrors()) { return kbuilder.getErrors().toString(); } return null; } public String getPackageErrorsOnRuleUpdate(Rule rule, PackageVersion packageVersion) { List<Rule> rules = ruleDao.load(packageVersion); String packages = ""; packages += "package test\n"; packages += "dialect \"mvel\"\n"; packages += "import kz.bsbnb.usci.eav.model.base.BaseEntity;\n"; packages += "import kz.bsbnb.usci.brms.BRMSHelper;\n"; for (Rule r : rules) { if (!r.getId().equals(rule.getId())) packages += r.getRule() + "\n"; else { packages += rule.getRule() + "\n"; } } KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newInputStreamResource(new ByteArrayInputStream(packages.getBytes())), ResourceType.DRL); if (kbuilder.hasErrors()) { return kbuilder.getErrors().toString(); } return null; } private class PackageAgendaFilter implements AgendaFilter { private String pkgName = ""; public PackageAgendaFilter(String pkgName) { this.pkgName = pkgName.trim(); } @Override public boolean accept(Match match) { return pkgName.equals(match.getRule().getPackageName()); } } public void runRules(BaseEntity entity, String pkgName) { runRules(entity, pkgName, LocalDate.now()); } synchronized public void fillPackagesCache() { kbase = KnowledgeBaseFactory.newKnowledgeBase(); List<RulePackage> packages = packageDao.getAllPackages(); rulePackageErrors.clear(); ruleCache.clear(); creditorCache.clear(); for (RulePackage curPackage : packages) { List<PackageVersion> versions = ruleDao.getPackageVersions(curPackage); ArrayList<RuleCacheEntry> ruleCacheEntries = new ArrayList<>(); for (PackageVersion version : versions) { List<Rule> rules = ruleDao.load(version); StringBuilder droolPackage = new StringBuilder(); droolPackage.append("package ").append(curPackage.getName()).append("_") .append(version.getReportDate().format(ruleDateFormat)).append("\n"); droolPackage.append("dialect \"mvel\"\n"); droolPackage.append("import kz.bsbnb.usci.brms.BRMSHelper;\n"); for (Rule r : rules) { if (r.isActive() || true) droolPackage.append(r.getRule()).append("\n"); } logger.debug(droolPackage.toString()); try { setRules(droolPackage.toString()); } catch (Exception e) { rulePackageErrors.add(new RulePackageError(curPackage.getName() + "_" + version, e.getMessage())); logger.error("Ошибка компиляции пакета бизнес-правил : " + curPackage.getName() + "\n" + e.getMessage() ); //throw new UsciException("Ошибка компиляции пакета бизнес-правил : " + curPackage.getName(), e); } ruleCacheEntries.add(new RuleCacheEntry(version.getReportDate(), curPackage.getName() + "_" + version)); } Collections.sort(ruleCacheEntries); ruleCache.put(curPackage.getName(), ruleCacheEntries); } } public void runRules(BaseEntity entity, String pkgName, LocalDate repDate) { kieBase = kbase; StatelessKieSession kSession = getSession(); kSession.setGlobal("baseEntityProcessor", baseEntityProcessor); kSession.setGlobal("baseEntityLoadService", baseEntityLoadService); kSession.setGlobal("metaClassRepository", metaClassRepository); kSession.setGlobal("creditorCache", creditorCache); ArrayList<RuleCacheEntry> versions = ruleCache.get(pkgName); String packageName = null; if (versions == null) { try { logger.info("В данный момент идет обновление кэша бизнес - правил"); Thread.sleep(3000); } catch (InterruptedException e) { } } versions = ruleCache.get(pkgName); for (RuleCacheEntry version : versions) { if (version.getRepDate().compareTo(repDate) <= 0) { packageName = pkgName + "_" + version.getRepDate().format(ruleDateFormat); } else { break; } } if (packageName == null) return; @SuppressWarnings("rawtypes") List<Command> commands = new ArrayList<>(); commands.add(CommandFactory.newInsert(entity)); commands.add(new FireAllRulesCommand(new PackageAgendaFilter(packageName))); kSession.execute(CommandFactory.newBatchExecution(commands)); } public void runRules(BaseEntity entity) { StatelessKieSession kSession = getSession(); kSession.execute(entity); } public String getPackageErrorsOnRuleInsert(PackageVersion packageVersion, String title, String ruleBody) { List<Rule> rules = ruleDao.load(packageVersion); String packages = ""; packages += "package test\n"; packages += "dialect \"mvel\"\n"; packages += "import kz.bsbnb.usci.eav.model.base.BaseEntity;\n"; packages += "import kz.bsbnb.usci.brms.BRMSHelper;\n"; for (Rule r : rules) packages += r.getRule() + "\n"; packages += ruleBody + "\n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newInputStreamResource(new ByteArrayInputStream(packages.getBytes())), ResourceType.DRL); if (kbuilder.hasErrors()) { return kbuilder.getErrors().toString(); } return null; } public String getPackageErrors(List<Rule> rules) { StringBuilder packages = new StringBuilder(); packages.append("package test\n"); packages.append("dialect \"mvel\"\n"); packages.append("import kz.bsbnb.usci.eav.model.base.BaseEntity;\n"); packages.append("import kz.bsbnb.usci.brms.BRMSHelper;\n"); for (Rule r : rules) packages.append(r.getRule()).append("\n"); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newInputStreamResource(new ByteArrayInputStream(packages.toString().getBytes())), ResourceType.DRL); if (kbuilder.hasErrors()) { return kbuilder.getErrors().toString(); } return null; } public String getPackageErrorsOnRuleDelete(Rule rule) { List<RulePackage> rulePackages = ruleDao.getRulePackages(rule); for (RulePackage rulePackage : rulePackages) { List<PackageVersion> packageVersions = ruleDao.getPackageVersions(rulePackage); for (PackageVersion packageVersion : packageVersions) { if (packageVersion.getReportDate().compareTo(rule.getOpenDate()) > 0) continue; List<Rule> rules = ruleDao.load(packageVersion); Iterator<Rule> iterator = rules.iterator(); while(iterator.hasNext()) { if (iterator.next().getId().equals(rule.getId())) { iterator.remove(); break; } } String curResult = getPackageErrors(rules); if (curResult != null) return curResult; } } return null; } } <file_sep>package kz.bsbnb.usci.sync.config; import kz.bsbnb.usci.sync.service.SyncService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.remoting.rmi.RmiServiceExporter; import static kz.bsbnb.usci.model.Constants.SYNC_RMI_PORT; /** * @author <NAME> */ @Configuration public class RmiConfig { @Bean public RmiServiceExporter exporter(SyncService impl) { RmiServiceExporter exporter = new RmiServiceExporter(); exporter.setServiceInterface(SyncService.class); exporter.setService(impl); exporter.setServiceName("syncService"); exporter.setRegistryPort(SYNC_RMI_PORT); return exporter; } } <file_sep>var label_ERROR = 'Қате'; var label_QUEUE = 'Тізім'; var label_ORGS = 'Ұйым'; var label_SELECT_ALL = 'Барлығын белгілеу'; var label_DOWN_Q = 'Тізімді жүктеу'; var label_AUTO = 'Автоматты жаңарту'; var label_FILES = 'Файлдар'; var label_FILE_INFO = 'Файлдардар туралы ақпарат'; var label_ORG_NAME = 'Ұйымның атауы'; var label_FILE_NAME = 'Файл атауы'; var label_PRODUCT = 'Өнім'; var label_STATUS = 'Статус'; var label_REC_TIME = 'Қабылдау уақыты'; var label_AMOUNT = 'Өңделген жазбалардың саны'; var label_REP_DATE = 'Есепті күн'; var label_EXCEL = 'Excel түсіру'; var label_RESUME = 'Резюме'; var label_FILES_IN_Q = 'Тізімдегі файлдар'; var label_Q_CONTROL = 'Тізімдерді басқару'; var label_SETTINGS = 'Өңдеу тәртібі'; var label_CHOOSE_P = 'Басымдық ұйымдарды таңдау'; var label_SAVE = 'Сақтау'; var label_CONFIRMED = 'Мақұлданды'; var label_CONFIG = 'Receiver конфигурациясы жаңартылды'; var label_VIEW = 'Өңдеу тәртібін алдын-ала қарау'; <file_sep>function getColomnList(tableName) { var columnList = Ext.getCmp('FIELD_ID'); var columnClass = null; Ext.Ajax.request({ url: dataUrl + '/report/report/getValueList', method: 'GET', params: { userId: userId, tableName: tableName, procedureName:'REPORTER.INPUT_PARAMETER_SC_FIELDS' }, success: function(response) { columnClass = JSON.parse(response.responseText); columnList.removeAll(); for(var i=0; i < columnClass.length; i++) { columnList.add({ xtype: 'checkbox', cls: 'checkBox', width: 300, inputValue: columnClass[i].value, boxLabel: columnClass[i].displayName, checked: false, name: 'myGroup' }); } } }); columnList.doLayout(); } function addFilter(tableName){ var columnList = Ext.getCmp('FIELD_ID'); var filterPanel = Ext.getCmp('filterPanel'); var columnClass = null; var columnStore = Ext.create('Ext.data.Store', { id: 'columnStore', model: 'valueModel', autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/report/report/getValueList', method: 'GET', extraParams: { userId: userId, tableName: tableName, procedureName:'REPORTER.INPUT_PARAMETER_SC_FIELDS' }, actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } } }); var filterValuePanel = Ext.create('Ext.form.Panel', { layout:'hbox', border: false, items: [ { xtype: 'combobox', name: 'columnName', store: columnStore, valueField:'displayName', displayField:'displayName', fieldLabel: 'Показатель', margin: '0 5 0 0', listeners: { change: function () { var record = columnStore.findRecord('displayName', this.getValue()); var cmpPanel = this.up('panel').id; console.log(cmpPanel); addFilterConfig(record.data.value, cmpPanel); } } } ,{ xtpye: 'panel', border: false, margin: '0 5 0 0', layout: 'hbox' }, ,{ xtype: 'button', html: 'Удалить фильтр', handler: function() { this.up('panel').destroy(); } }] }); filterPanel.add(filterValuePanel); } function addFilterConfig(columntype, panelName) { var filterValuePanel = Ext.getCmp(panelName); var filterPanel = Ext.getCmp('filterPanel'); if (columntype == 'DATE') { var operation = ["=", "<>", "<=", ">=", "<", ">"]; var valueComp = Ext.create('Ext.form.field.Date', { name: 'filterValue', anchor: '100%', format: 'd.m.Y', fieldLabel: 'Значение', maxValue: new Date() }); } else if (columntype == 'BOOLEAN') { var operation = ["="]; var possibleValue = ["TRUE", "FALSE"]; var valueComp = Ext.create('Ext.form.field.ComboBox', { name: 'filterValue', store: possibleValue, valueField:'value', displayField:'value', fieldLabel: 'Заначение' }); } else { if (columntype == 'VARCHAR2') { var operation = ["=", "<>"]; } else { var operation = ["=", "<>", "<=", ">=", "<", ">"]; } var valueComp = Ext.create('Ext.form.field.Text', { fieldLabel: 'Значение', name: 'filterValue' }); } var operationComp = Ext.create('Ext.form.field.ComboBox', { name:'operationValue', store: operation, margin: '0 10 0 0', valueField: 'value', displayField: 'value', fieldLabel: 'Фильтр' }); filterValuePanel.add(operationComp); filterValuePanel.add(valueComp); filterPanel.show(); } <file_sep>package kz.bsbnb.usci.report.model.json; public class InputParametersJson { private Long order; private String name; private String display; private Object value; private String type; public String getType() { return type; } public void setType(String type) { this.type = type; } public Long getOrder() { return order; } public void setOrder(Long order) { this.order = order; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplay() { return display; } public void setDisplay(String display) { this.display = display; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } <file_sep>package kz.bsbnb.usci.receiver.parser.impl; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.base.BaseValue; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.receiver.parser.BatchParser; import kz.bsbnb.usci.receiver.parser.exceptions.UnknownTagException; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** * @author <NAME> * @author <NAME> */ @Component @Scope("prototype") public class SubjectOrganizationHeadDocsParser extends BatchParser { public SubjectOrganizationHeadDocsParser() { super(); } private MetaClass refDocTypeMeta; @Override public void init() { currentBaseEntity = new BaseEntity(metaClassRepository.getMetaClass("document"), respondentId, batch.getReportDate(), batch.getId()); refDocTypeMeta = metaClassRepository.getMetaClass("ref_doc_type"); } @Override public boolean startElement(XMLEvent event, StartElement startElement, String localName) throws SAXException { switch (localName) { case "docs": break; case "doc": BaseEntity docType = new BaseEntity(refDocTypeMeta, respondentId, batch.getReportDate(), batch.getId()); docType.put("code", new BaseValue(event.asStartElement().getAttributeByName(new QName("doc_type")).getValue())); currentBaseEntity.put("doc_type", new BaseValue(docType)); break; case "name": event = (XMLEvent) xmlReader.next(); currentBaseEntity.put("name", new BaseValue(trim(event.asCharacters().getData()))); break; case "no": event = (XMLEvent) xmlReader.next(); currentBaseEntity.put("no", new BaseValue(trim(event.asCharacters().getData()))); break; default: throw new UnknownTagException(localName); } return false; } @Override public boolean endElement(String localName) throws SAXException { switch (localName) { case "docs": hasMore = false; return true; case "doc": hasMore = true; return true; case "name": break; case "no": break; default: throw new UnknownTagException(localName); } return false; } } <file_sep>package kz.bsbnb.usci.receiver.batch.controller; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.receiver.batch.service.BatchJsonService; import kz.bsbnb.usci.receiver.batch.service.BatchMaintenanceService; import kz.bsbnb.usci.receiver.batch.service.BatchService; import kz.bsbnb.usci.receiver.model.BatchFile; import kz.bsbnb.usci.receiver.model.BatchStatus; import kz.bsbnb.usci.receiver.model.BatchStatusJsonList; import kz.bsbnb.usci.receiver.model.BatchStatusType; import kz.bsbnb.usci.receiver.model.json.BatchJson; import kz.bsbnb.usci.receiver.model.json.BatchJsonList; import kz.bsbnb.usci.receiver.model.json.BatchSignJson; import kz.bsbnb.usci.receiver.model.json.BatchSignJsonList; import kz.bsbnb.usci.receiver.processor.BatchReceiver; import kz.bsbnb.usci.receiver.queue.BatchQueueHolder; import kz.bsbnb.usci.receiver.sign.SignatureChecker; import kz.bsbnb.usci.util.json.ext.ExtJsList; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Set; /** * @author <NAME> * @author <NAME> */ @RestController @RequestMapping(value = "/batch") public class BatchController { private static final Logger logger = LoggerFactory.getLogger(BatchController.class); private final BatchService batchService; private final BatchReceiver batchReceiver; private final BatchQueueHolder batchQueueHolder; private final BatchJsonService batchJsonService; private final BatchMaintenanceService batchMaintenanceService; public BatchController(BatchService batchService, BatchReceiver batchProcessor, BatchQueueHolder batchQueueHolder, BatchJsonService batchJsonService, BatchMaintenanceService batchMaintenanceService) { this.batchService = batchService; this.batchReceiver = batchProcessor; this.batchQueueHolder = batchQueueHolder; this.batchJsonService = batchJsonService; this.batchMaintenanceService = batchMaintenanceService; } @PostMapping(value = "endBatch") public void endBatch(@RequestParam(name = "batchId") Long batchId) { batchService.endBatch(batchId); } @PostMapping(value = "incrementActualCounts") public boolean incrementActualCounts(@RequestBody Map<Long, Long> batchesToUpdate) { return batchService.incrementActualCounts(batchesToUpdate); } @PostMapping(value = "uploadBatch") public void uploadBatch(@RequestParam("file") MultipartFile[] files, @RequestParam(name = "isNb") Boolean isNb, @RequestParam(name = "userId") Long userId) { for (MultipartFile uploadedFile : files) { BatchFile batchFile = new BatchFile(); batchFile.setNb(isNb); batchFile.setUserId(userId); try { batchFile.setFileContent(uploadedFile.getBytes()); batchFile.setFileName(uploadedFile.getOriginalFilename()); } catch (IOException e) { throw new UsciException("Ошибка загрузки батча"); } batchReceiver.receiveBatch(batchFile); } } @GetMapping(value = "getBatchList") public ExtJsList getBatchList(@RequestParam(name = "respondentIds") List<Long> respondentIds, @RequestParam(name = "userId") Long userId, @RequestParam(name = "isNb") Boolean isNb, @RequestParam(name = "reportDate") @DateTimeFormat(pattern = "dd.MM.yyyy") LocalDate reportDate, @RequestParam(name = "page") Integer pageIndex, @RequestParam(name = "limit") Integer pageSize) { return batchJsonService.getBatchList(respondentIds, userId, isNb, reportDate, pageIndex, pageSize); } @GetMapping(value = "getBatchStatusList") public ExtJsList getBatchStatusList(@RequestParam(name = "batchId") Long batchId, @RequestParam(name = "statusTypes") List<String> statusTypes) { return batchJsonService.getBatchStatusList(batchId, statusTypes); } @GetMapping(value = "getBatchContent") public byte[] getBatchContent(@RequestParam(name = "batchId") Long batchId) { return batchService.getBatch(batchId).getContent(); } @PostMapping(value = "getBatchExcelContent") public byte[] getBatchExcelContent(@RequestBody BatchJsonList batchJsonList) { return batchJsonService.getExcelFromBatch(batchJsonList.getBatchList(), batchJsonList.getColumnList()); } @PostMapping(value = "getProtocolExcelContent") public byte[] getProtocolExcelContent(@RequestBody BatchStatusJsonList batchStatusJsonList) { return batchJsonService.getExcelFromProtocol(batchStatusJsonList.getProtocolList(), batchStatusJsonList.getColumnList()); } @GetMapping(value = "getPendingBatchList") public List<BatchJson> getPendingBatchList(@RequestParam(name = "respondentIds") List<Long> respondentIds) { return batchJsonService.getPendingBatchList(respondentIds); } @GetMapping(value = "getMaintenanceBatchList") public List<BatchJson> getMaintenanceBatchList(@RequestParam(name = "respondentIds") List<Long> respondentIds, @RequestParam(name = "reportDate") @DateTimeFormat(pattern = "dd.MM.yyyy") LocalDate reportDate, @RequestParam(name = "userId") Long userId) { return batchJsonService.getMaintenanceBatchList(respondentIds, reportDate, userId); } @PostMapping(value = "approveAndSendMaintenance") public void approveAndSendMaintenance(@RequestParam(name = "batchIds") List<Long> batchIds) { batchService.approveMaintenanceBatchList(batchIds); for (Long batchId : batchIds) { batchReceiver.processBatch(batchId); } } @PostMapping(value = "declineAndSendMaintenance") public void declineAndSendMaintenance(@RequestParam(name = "batchIds") List<Long> batchIds) { batchService.declineMaintenanceBatchList(batchIds); for (Long batchId : batchIds) { batchReceiver.declineMaintenanceBatch(batchId); } } @PostMapping(value = "reloadQueueConfig") public void reloadQueueConfig() { batchQueueHolder.reloadConfig(); } @GetMapping(value = "getQueuePreviewBatches") public ExtJsList getQueuePreviewBatches(@RequestParam(name = "respondentsWithPriority") Set<Long> respondentsWithPriority, @RequestParam(name = "queueAlgo") String queueAlgo) { return new ExtJsList(batchQueueHolder.getOrderedBatches(respondentsWithPriority, queueAlgo)); } @PostMapping(value = "getQueueBatchExcelContent") public byte[] getQueueBatchExcelContent(@RequestBody BatchJsonList batchJsonList) { return batchJsonService.getExcelFromQueueBatch(batchJsonList.getBatchList(), batchJsonList.getColumnList()); } @GetMapping(value = "getBatchListToSign") public List<BatchJson> getBatchListToSign(@RequestParam(name = "respondentId") Long respondentId, @RequestParam(name = "userId") Long userId) { return batchJsonService.getBatchListToSign(respondentId, userId); } @PostMapping(value = "saveSignedBatchList") public void saveSignedBatchList(@RequestParam(name = "respondentBin") String respondentBin, @RequestBody BatchSignJsonList batchSignJsonList) { String ocspServiceUrl = "http://172.16.31.10:62255"; SignatureChecker checker = new SignatureChecker(respondentBin, ocspServiceUrl); for (BatchSignJson batch : batchSignJsonList.getBatchList()) { try { checker.checkAndUpdate(batch); batchService.signBatch(batch.getId(), batch.getSignature(), batch.getInformation(), batch.getSigningTime()); batchReceiver.processBatch(batch.getId()); } catch (UsciException e) { logger.error("По батчу обнаружены ошибки id = {}, ошибка = {}", batch.getId(), e); batchService.addBatchStatus(new BatchStatus() .setBatchId(batch.getId()) .setStatus(BatchStatusType.ERROR) .setText(e.getMessage()) .setExceptionTrace(e != null? ExceptionUtils.getStackTrace(e): null) .setReceiptDate(LocalDateTime.now())); batchService.endBatch(batch.getId()); } } } @PostMapping(value = "cancelBatch") public void cancelBatch(@RequestParam(name = "batchIds") List<Long> batchIds) { for (Long batchId : batchIds) { batchService.cancelBatch(batchId); } } @PostMapping(value = "removeBatchFromQueue") public void removeBatchFromQueue(@RequestParam(name = "batchId") Long batchId) { batchQueueHolder.removeBatch(batchId); } @GetMapping(value = "getBatchListToApprove") public List<BatchJson> getBatchListToApprove(@RequestParam(name = "productId") Long productId, @RequestParam(name = "respondentId") Long respondentId) { return batchJsonService.getBatchListToApprove(productId, respondentId); } }<file_sep>package kz.bsbnb.usci.eav.model.core; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author <NAME> */ public enum EntityStatusType { ERROR(8), COMPLETED(15), MAINTENANCE(9); int id; EntityStatusType(int id) { this.id = id; } public int getId() { return id; } private static final Map<Integer, EntityStatusType> map = new ConcurrentHashMap<>(); static { for (EntityStatusType entityStatusType : EntityStatusType.values()) { map.put(entityStatusType.getId(), entityStatusType); } } public static EntityStatusType getEntityStatus(int id) { return map.get(id); } } <file_sep>package kz.bsbnb.usci.model.respondent; import kz.bsbnb.usci.model.persistence.Persistable; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; /** * @author <NAME> */ public class ConfirmMessage extends Persistable { private Confirm confirm; private Long confirmId; private Long userId; private LocalDateTime sendDate; private String text; private List<ConfirmMessageFile> files = new ArrayList<>(); public Confirm getConfirm() { return confirm; } public void setConfirm(Confirm confirm) { this.confirm = confirm; } public Long getConfirmId() { return confirmId; } public void setConfirmId(Long confirmId) { this.confirmId = confirmId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public LocalDateTime getSendDate() { return sendDate; } public void setSendDate(LocalDateTime sendDate) { this.sendDate = sendDate; } public String getText() { return text; } public void setText(String text) { this.text = text; } public List<ConfirmMessageFile> getFiles() { return files; } public void setFiles(List<ConfirmMessageFile> files) { this.files = files; } } <file_sep>package kz.bsbnb.usci.eav.service; import kz.bsbnb.usci.brms.exception.BrmsException; import kz.bsbnb.usci.eav.model.base.*; import kz.bsbnb.usci.eav.model.core.BaseEntityStatus; import kz.bsbnb.usci.eav.model.core.EntityStatusType; import kz.bsbnb.usci.eav.model.meta.*; import kz.bsbnb.usci.eav.model.meta.json.EntityExtJsTreeJson; import kz.bsbnb.usci.model.exception.UsciException; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; import org.springframework.jdbc.UncategorizedSQLException; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; @Service public class BaseEntityApprovalServiceImpl implements BaseEntityApprovalService { private static final Logger logger = LoggerFactory.getLogger(BaseEntityApprovalServiceImpl.class); private final BaseEntityProcessor baseEntityProcessor; private final BaseEntityStatusService baseEntityStatusService; private final BaseEntityLoadXmlService baseEntityLoadXmlService; private final MetaClassService metaClassService; BaseEntityApprovalServiceImpl (BaseEntityProcessor baseEntityProcessor, BaseEntityStatusService baseEntityStatusService, BaseEntityLoadXmlService baseEntityLoadXmlService, MetaClassService metaClassService) { this.baseEntityProcessor = baseEntityProcessor; this.baseEntityStatusService = baseEntityStatusService; this.baseEntityLoadXmlService = baseEntityLoadXmlService; this.metaClassService = metaClassService; } @Override public void approveEntityMaintenance(List<BaseEntityJson> baseEntityList, Long batchId) { List<BaseEntityJson> syncedBaseEntityList = Collections.synchronizedList(baseEntityList); synchronized (syncedBaseEntityList) { syncedBaseEntityList.parallelStream().forEach(baseEntityJson -> { if (baseEntityJson.isPreApproved()) { long startTime = System.currentTimeMillis(); MetaClass metaClass = metaClassService.getMetaClass(baseEntityJson.getMetaClassId()); EntityExtJsTreeJson entityJson = baseEntityLoadXmlService.loadBaseEntity(baseEntityJson.getId()); BaseEntity mockEntity = baseEntityLoadXmlService.getBaseEntityFromJsonTree(baseEntityJson.getRespondentId(), baseEntityJson.getReportDate(), entityJson, metaClass, batchId); mockEntity.setOperation(baseEntityJson.getOperType()); try { //logger.info("Начинаем обработку сущности {}", mockEntity); BaseEntity baseEntityApplied = baseEntityProcessor.processBaseEntity(mockEntity); BaseEntityStatus baseEntityStatus = new BaseEntityStatus() .setEntityId(baseEntityApplied.getId()) .setBatchId(baseEntityApplied.getBatchId()) .setApprovedEntityId(mockEntity.getEavXmlId()) .setStatus(EntityStatusType.COMPLETED) .setErrorMessage("Обработано после одобрения") .setOperation(baseEntityApplied.getOperation()) .setSystemDate(LocalDateTime.now()); baseEntityStatusService.update(baseEntityStatus); //baseEntityLoadXmlService.updateBaseEntity(baseEntityJson, true); baseEntityLoadXmlService.deleteBaseEntity(baseEntityJson.getId()); logger.info("Завершена обработка сущности после одобрения, время {} {}", (System.currentTimeMillis() - startTime), baseEntityApplied); } catch (BrmsException be) { String entityText = BaseEntityOutput.getEntityAsString(mockEntity, true); // ошибка бизнес правил: заливаем в базу все ошибки по сущности for (String errorText : be.getErrorMessages()) { String stackTrace = null; if (errorText.contains("----")) { stackTrace = errorText.substring(errorText.indexOf("-----")); errorText = errorText.substring(0, errorText.indexOf("-----")); } BaseEntityStatus baseEntityStatus = new BaseEntityStatus() .setEntityId(mockEntity.getId()) .setMetaClassId(mockEntity.getMetaClass().getId()) .setBatchId(mockEntity.getBatchId()) .setIndex(mockEntity.getBatchIndex()) .setEntityText(entityText) .setStatus(EntityStatusType.ERROR) .setOperation(mockEntity.getOperation()) .setErrorMessage(errorText) .setErrorCode("Ошибка бизнес правил") .setExceptionTrace(stackTrace) .setSystemDate(LocalDateTime.now()); baseEntityStatusService.insert(baseEntityStatus); baseEntityLoadXmlService.updateBaseEntity(baseEntityJson, true); } logger.error("Ошибка проверки сущности на бизнес правила {}", mockEntity); } catch (UsciException ue) { BaseEntityStatus baseEntityStatus = new BaseEntityStatus() .setEntityId(mockEntity.getId()) .setMetaClassId(mockEntity.getMetaClass().getId()) .setBatchId(mockEntity.getBatchId()) .setIndex(mockEntity.getBatchIndex()) .setEntityText(BaseEntityOutput.getEntityAsString(mockEntity, true)) .setStatus(EntityStatusType.ERROR) .setOperation(mockEntity.getOperation()) .setErrorMessage(ue.getMessage()) .setErrorCode(ue.getErrorCode()) .setExceptionTrace(ExceptionUtils.getStackTrace(ue)) .setSystemDate(LocalDateTime.now()); baseEntityStatusService.insert(baseEntityStatus); baseEntityLoadXmlService.updateBaseEntity(baseEntityJson, true); logger.error("Ошибка обработки сущности {} ", mockEntity); } catch (Exception e) { String errorText = null; if (e instanceof DuplicateKeyException) { errorText = "Ошибка дублирования сущности"; } else if (e instanceof UncategorizedSQLException) { errorText = "Ошибка БД"; } // прочие ошибки (по БД, программные, разработчика) ловим здесь BaseEntityStatus baseEntityStatus = new BaseEntityStatus() .setEntityId(mockEntity.getId()) .setMetaClassId(mockEntity.getMetaClass().getId()) .setBatchId(mockEntity.getBatchId()) .setIndex(mockEntity.getBatchIndex()) .setEntityText(BaseEntityOutput.getEntityAsString(mockEntity, true)) .setStatus(EntityStatusType.ERROR) .setOperation(mockEntity.getOperation()) .setErrorMessage((e instanceof DuplicateKeyException || e instanceof UncategorizedSQLException) ? errorText : e.getMessage()) .setExceptionTrace(ExceptionUtils.getStackTrace(e)) .setSystemDate(LocalDateTime.now()); baseEntityStatusService.insert(baseEntityStatus); baseEntityLoadXmlService.updateBaseEntity(baseEntityJson, true); logger.error("Ошибка обработки сущности {} ", mockEntity); } } else if (baseEntityJson.isPreDeclined()){ BaseEntityStatus baseEntityStatus = new BaseEntityStatus() .setEntityId(baseEntityJson.getEntityId()) .setApprovedEntityId(baseEntityJson.getEntityId()) .setBatchId(batchId) .setStatus(EntityStatusType.ERROR) .setErrorMessage("Отклонено после одобрения") .setSystemDate(LocalDateTime.now()); baseEntityStatusService.update(baseEntityStatus); baseEntityLoadXmlService.updateBaseEntity(baseEntityJson, false); logger.error("Сущность отклонена после одобрения {} ", baseEntityJson); } }); } } } <file_sep> package kz.bsbnb.usci.wsclient.jaxb.kgd; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for exceptionMessage complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="exceptionMessage"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Fault"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="code" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="message" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="date" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="sessionId" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "exceptionMessage", propOrder = { "fault" }) public class ExceptionMessage { @XmlElement(name = "Fault", required = true) protected ExceptionMessage.Fault fault; /** * Gets the value of the fault property. * * @return * possible object is * {@link ExceptionMessage.Fault } * */ public ExceptionMessage.Fault getFault() { return fault; } /** * Sets the value of the fault property. * * @param value * allowed object is * {@link ExceptionMessage.Fault } * */ public void setFault(ExceptionMessage.Fault value) { this.fault = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="code" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="message" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="date" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="sessionId" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "code", "message", "date", "sessionId" }) public static class Fault { @XmlElement(required = true) protected String code; @XmlElement(required = true) protected String message; @XmlElement(required = true) protected String date; @XmlElement(required = true) protected String sessionId; /** * Gets the value of the code property. * * @return * possible object is * {@link String } * */ public String getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link String } * */ public void setCode(String value) { this.code = value; } /** * Gets the value of the message property. * * @return * possible object is * {@link String } * */ public String getMessage() { return message; } /** * Sets the value of the message property. * * @param value * allowed object is * {@link String } * */ public void setMessage(String value) { this.message = value; } /** * Gets the value of the date property. * * @return * possible object is * {@link String } * */ public String getDate() { return date; } /** * Sets the value of the date property. * * @param value * allowed object is * {@link String } * */ public void setDate(String value) { this.date = value; } /** * Gets the value of the sessionId property. * * @return * possible object is * {@link String } * */ public String getSessionId() { return sessionId; } /** * Sets the value of the sessionId property. * * @param value * allowed object is * {@link String } * */ public void setSessionId(String value) { this.sessionId = value; } } } <file_sep>group = 'kz.bsbnb.usci.receiver' version = '0.1.0' dependencies { compile project(':model') compile project(':util:util-api') compile project(':eav:eav-core') compile project(':eav:eav-meta') compile project(':core:core-api') compile project(':sync:sync-api') compile project(':mail:mail-api') compile('org.springframework.boot:spring-boot-starter-batch') compile('org.springframework.cloud:spring-cloud-starter-openfeign') compile("org.springframework.kafka:spring-kafka:${springKafkaVersion}") compile('org.springframework.cloud:spring-cloud-starter-netflix-ribbon') compile('org.apache.commons:commons-compress:1.16.1') compile('kz.gamma:crypto-common10') compile('kz.gamma:gammaprov11') } jar { baseName = 'usci-receiver-core' version = '0.1.0' enabled = true } bootJar { enabled = false } <file_sep>group = 'kz.bsbnb.usci.wsclient' version = '0.1.0' dependencies { compile project(':model') compile('org.springframework.cloud:spring-cloud-starter-openfeign') } jar { baseName = 'usci-wsclient-api' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>package kz.bsbnb.usci.eav.model.meta; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.model.persistence.Persistable; import java.util.Objects; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ public class MetaSet extends Persistable implements MetaType { private static final long serialVersionUID = -8685213083933324775L; private MetaType metaType; private SetKeyType keyType = SetKeyType.ALL; private String nestedTable; public MetaSet() { /*Пустой конструктор*/ } public MetaSet(MetaType metaType) { Objects.requireNonNull(metaType, "MetaType не может быть null"); this.metaType = metaType; } @Override public boolean isSet() { return true; } @Override public boolean isComplex() { return metaType.isComplex(); } @Override public boolean isDictionary() { return metaType.isDictionary(); } public void setMetaType(MetaType metaType) { Objects.requireNonNull(metaType, "MetaType не может быть null"); this.metaType = metaType; } public MetaType getMetaType() { return metaType; } public SetKeyType getKeyType() { return keyType; } public void setKeyType(SetKeyType keyType) { this.keyType = keyType; } public MetaDataType getMetaDataType() { if (isComplex() || metaType.isSet()) throw new UsciException("Массив не простой"); return ((MetaValue) metaType).getMetaDataType(); } public String getNestedTable() { return nestedTable; } public void setNestedTable(String nestedTable) { this.nestedTable = nestedTable; } @Override public String toString() { return toString(""); } @Override public String toString(String prefix) { return "metaSet(" + getId() + "), " + metaType.toString(prefix); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MetaSet)) return false; MetaSet metaSet = (MetaSet) o; if (!metaType.equals(metaSet.metaType)) return false; if (keyType != metaSet.keyType) return false; return true; } @Override public int hashCode() { int result = metaType.hashCode(); result = 31 * result + (keyType != null ? keyType.hashCode() : 0); return result; } } <file_sep>package kz.bsbnb.usci.core.service; import kz.bsbnb.usci.model.adm.User; import kz.bsbnb.usci.model.batch.Product; import kz.bsbnb.usci.model.respondent.Respondent; import java.util.List; import java.util.Optional; import java.util.Set; /** * @author <NAME> */ public interface UserService { List<User> getUserList(); List<Respondent> getUserRespondentList(long userId); List<User> getRespondentUserList(long respondentId); User getUser(long userId); void addUserRespondent(Long userId, List<Long> respondentIds); void deleteUserRespondent(Long userId, List<Long> respondentIds); List<User> getNationalBankUsers(long respondentId); void addUserProduct(Long userId, List<Long> productIds); void deleteUserProduct(Long userId, List<Long> productIds); List<Product> getUserProductList(long userId); void synchronize(List<User> users); Optional<Set<Long>> getUserProductPositionIds(Long userId, Long productId); void addMailTemplatesToNewUser(List<User> users); } <file_sep>/** * @author <NAME> * @author <NAME> * @author <NAME> */ function createMetaModels() { Ext.define('metaClassModel', { extend: 'Ext.data.Model', fields: ['id', 'name', 'title'] }); Ext.define('attributeModel', { extend: 'Ext.data.Model', fields: [ {name: 'title', type: 'string'}, {name: 'name', type: 'string'}, {name: 'classId', type: 'number'}, {name: 'simple', type: 'boolean'}, {name: 'array', type: 'boolean'}, {name: 'dictionary', type: 'boolean'}, {name: 'typeCode', type: 'string'}, {name: 'metaType', type: 'string'}, {name: 'key', type: 'boolean'}, {name: 'required', type: 'boolean'}, {name: 'refClassId', type: 'number'}, {name: 'refMetaType', type: 'string'}, {name: 'value', type: 'auto'} ] }); Ext.define('entityModel', { extend: 'Ext.data.Model', fields: [ {name: 'title', type: 'string'}, {name: 'name', type: 'string'}, {name: 'classId', type: 'number'}, {name: 'simple', type: 'boolean'}, {name: 'array', type: 'boolean'}, {name: 'dictionary', type: 'boolean'}, {name: 'typeCode', type: 'string'}, {name: 'metaType', type: 'string'}, {name: 'key', type: 'boolean'}, {name: 'required', type: 'boolean'}, {name: 'cumulative', type: 'boolean'}, {name: 'refClassId', type: 'number'}, {name: 'refType', type: 'string'}, {name: 'openDate', type: 'date', format: 'd.m.Y'}, {name: 'closeDate', type: 'date', format: 'd.m.Y'}, {name: 'value', type: 'auto'}, {name: 'newNode', type: 'boolean'} ] }); } function loadAttributes(metaClassId, callback) { Ext.Ajax.request({ url: dataUrl + '/core/meta/getMetaClassAttributesList', params : { metaClassId: metaClassId }, method: 'GET', success: function(result) { var attributes = JSON.parse(result.responseText); callback(attributes); } }); }<file_sep>package kz.bsbnb.usci.model.persistence; import java.io.Serializable; import java.util.Objects; /** * @author <NAME> */ public class Persistable implements Serializable { protected Long id; protected Persistable() { super(); } protected Persistable(Long id) { this.id = id; } public Long getId() { return id; } public Persistable setId(Long id) { this.id = id; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Persistable)) return false; Persistable that = (Persistable) o; return Objects.equals(id, that.id); } @Override public int hashCode() { if (id == null) return 0; return (int) (id ^ (id >>> 32)); } }<file_sep>rootProject.name = 'usci' include ':eureka' include ':model' include ':zuul' include ':fstore' include ':brms' include ':brms:brms-api' include ':brms:brms-core' include ':sync' include ':sync:sync-core' include ':sync:sync-boot' include ':sync:sync-api' include ':util' include ':util:util-api' include ':util:util-boot' include ':util:util-core' include ':receiver' include ':receiver:receiver-boot' include ':receiver:receiver-core' include ':receiver:receiver-api' include ':core' include ':core:core-api' include ':core:core-core' include ':core:core-boot' include ':eav' include ':eav:eav-api' include ':eav:eav-core' include ':eav:eav-meta' include ':portlet' include ':portlet:brms_portlet' include ':portlet:static' include ':portlet:upload_portlet' include ':portlet:protocol_portlet' include ':portlet:queue_portlet' include ':portlet:crosscheck_portlet' include ':portlet:meta-editor' include ':portlet:administration' include ':portlet:entity-approval' include ':portlet:entity-editor' include ':portlet:batch_entry' include ':portlet:signing' include ':portlet:notification_portlet' include ':portlet:product_portlet' include ':portlet:report_portlet' include ':portlet:confirm-portlet' include ':portlet:maintenance-approval' include ':portlet:wsprotocol' include ':mail' include ':mail:mail-api' include ':mail:mail-boot' include ':mail:mail-core' include ':report' include ':report:report-api' include ':report:report-boot' include ':report:report-core' include ':wsclient' include ':wsclient:wsclient-api' include ':wsclient:wsclient-core' include ':wsclient:wsclient-boot' <file_sep>package kz.bsbnb.usci.wsclient.dao; import kz.bsbnb.usci.util.SqlJdbcConverter; import kz.bsbnb.usci.wsclient.model.currency.CurrencyEntityCustom; import kz.bsbnb.usci.wsclient.model.currency.HolidayEntityCustom; import kz.bsbnb.usci.wsclient.model.currency.NSIEntity; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.sql.Date; import java.time.LocalDate; import java.util.*; @Repository public class NSIDaoImpl implements NSIDao { private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; public NSIDaoImpl(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) { this.jdbcTemplate = jdbcTemplate; this.npJdbcTemplate = npJdbcTemplate; } @Override public void saveCurrencyRates(List<NSIEntity> currList) { /*HashMap<Long, NSIEntity> currencyFromDB = new HashMap<>(); HashMap<Long, NSIEntity> currencyFromWS = new HashMap<>(); String query = "SELECT t.* from USCI_WS.NSI_CURRENCY t"; List<Map<String, Object>> rows = jdbcTemplate.queryForList(query); for (Map<String, Object> row : rows) { NSIEntity currencyEntity = new NSIEntity(); NSIEntitySystem currencyEntitySystem = new NSIEntitySystem(); CurrencyEntityCustom currencyEntityCustom = new CurrencyEntityCustom(); currencyEntity.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); currencyEntitySystem.setOperType(SqlJdbcConverter.convertObjectToString(row.get("OPER_TYPE"))); currencyEntitySystem.setEntityID(SqlJdbcConverter.convertToLong(row.get("ENTITY_ID"))); currencyEntitySystem.setOperDate(SqlJdbcConverter.convertToLocalDate((Timestamp) row.get("OPER_DATE"))); currencyEntitySystem.setBeginDate(SqlJdbcConverter.convertToLocalDate((Timestamp) row.get("BEGIN_DATE"))); currencyEntitySystem.setEndDate(SqlJdbcConverter.convertToLocalDate((Timestamp) row.get("END_DATE"))); currencyEntity.setNSIEntitySystem(currencyEntitySystem); currencyEntityCustom.setCurrId(SqlJdbcConverter.convertToLong(row.get("CURRENCY_ID"))); currencyEntityCustom.setCurrCode(SqlJdbcConverter.convertObjectToString(row.get("CURRENCY_CODE"))); currencyEntityCustom.setCourseDate(SqlJdbcConverter.convertToLocalDate((Timestamp) row.get("COURSE_DATE"))); currencyEntityCustom.setCourseKind(SqlJdbcConverter.convertToLong(row.get("COURSE_KIND"))); currencyEntityCustom.setCourse(SqlJdbcConverter.convertToDouble(row.get("COURSE"))); currencyEntityCustom.setCorellation(SqlJdbcConverter.convertToLong(row.get("CORELLATION"))); currencyEntityCustom.setWdKind(SqlJdbcConverter.convertToLong(row.get("WD_KIND"))); currencyEntity.setCurrencyEntityCustom(currencyEntityCustom); currencyFromDB.put(currencyEntity.getNSIEntitySystem().getEntityID(), currencyEntity); } for (NSIEntity currencyEntity : currList) { currencyFromWS.put(currencyEntity.getNSIEntitySystem().getEntityID(), currencyEntity); } Set<Long> toAdd = SetUtils.difference(currencyFromWS.keySet(), currencyFromDB.keySet()); List<NSIEntity> currListToAdd = new ArrayList<>(); for (Long id : toAdd) { NSIEntity currencyEntity = currencyFromWS.get(id); currListToAdd.add(currencyEntity); }*/ SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_WS") .withTableName("NSI_CURRENCY") .usingGeneratedKeyColumns("ID"); List<Map<String, Object>> batchValues = new ArrayList<>(currList.size()); for (NSIEntity NSIEntity : currList) { Map<String, Object> map = new HashMap<>(); map.put("OPER_TYPE", NSIEntity.getNSIEntitySystem().getOperType()); map.put("ENTITY_ID", NSIEntity.getNSIEntitySystem().getEntityID()); map.put("OPER_DATE", SqlJdbcConverter.convertToSqlDate(NSIEntity.getNSIEntitySystem().getOperDate())); map.put("BEGIN_DATE", SqlJdbcConverter.convertToSqlDate(NSIEntity.getNSIEntitySystem().getBeginDate())); map.put("END_DATE", SqlJdbcConverter.convertToSqlDate(NSIEntity.getNSIEntitySystem().getEndDate())); map.put("CURRENCY_ID", ((CurrencyEntityCustom) NSIEntity.getNSIEntityCustom()).getCurrId()); map.put("CURRENCY_CODE", ((CurrencyEntityCustom) NSIEntity.getNSIEntityCustom()).getCurrCode()); map.put("COURSE_DATE", SqlJdbcConverter.convertToSqlDate(((CurrencyEntityCustom) NSIEntity.getNSIEntityCustom()).getCourseDate())); map.put("COURSE_KIND", ((CurrencyEntityCustom) NSIEntity.getNSIEntityCustom()).getCourseKind()); map.put("COURSE", ((CurrencyEntityCustom) NSIEntity.getNSIEntityCustom()).getCourse()); map.put("CORELLATION", ((CurrencyEntityCustom) NSIEntity.getNSIEntityCustom()).getCorellation()); map.put("WD_KIND", ((CurrencyEntityCustom) NSIEntity.getNSIEntityCustom()).getWdKind()); batchValues.add(map); } simpleJdbcInsert.executeBatch(batchValues.toArray(new Map[currList.size()])); } @Override public LocalDate getMaxCourseDate() { return SqlJdbcConverter.convertToLocalDate(jdbcTemplate.queryForObject("select max(COURSE_DATE) from usci_ws.nsi_currency", Date.class)); } @Override public void saveHolidayDates(List<NSIEntity> currList) { SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_WS") .withTableName("NSI_HOLIDAY") .usingGeneratedKeyColumns("ID"); List<Map<String, Object>> batchValues = new ArrayList<>(currList.size()); for (NSIEntity NSIEntity : currList) { Map<String, Object> map = new HashMap<>(); map.put("OPER_TYPE", NSIEntity.getNSIEntitySystem().getOperType()); map.put("ENTITY_ID", NSIEntity.getNSIEntitySystem().getEntityID()); map.put("OPER_DATE", SqlJdbcConverter.convertToSqlDate(NSIEntity.getNSIEntitySystem().getOperDate())); map.put("BEGIN_DATE", SqlJdbcConverter.convertToSqlDate(NSIEntity.getNSIEntitySystem().getBeginDate())); map.put("END_DATE", SqlJdbcConverter.convertToSqlDate(NSIEntity.getNSIEntitySystem().getEndDate())); map.put("HOLIDAY_DATE", SqlJdbcConverter.convertToSqlDate(((HolidayEntityCustom) NSIEntity.getNSIEntityCustom()).getHolidayDate())); map.put("HOLIDAY_TYPE", ((HolidayEntityCustom) NSIEntity.getNSIEntityCustom()).getHolidayType()); batchValues.add(map); } simpleJdbcInsert.executeBatch(batchValues.toArray(new Map[currList.size()])); } } <file_sep>group = 'kz.bsbnb.usci.core' version = '0.1.0' dependencies { compile project(':core:core-core') compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.boot:spring-boot-starter-jdbc') compile('org.springframework.boot:spring-boot-starter-batch') compile("org.springframework.boot:spring-boot-starter-actuator") compile('org.apache.commons:commons-compress:1.16.1') } bootJar { baseName = 'usci-core-boot' version = '0.1.0' } springBoot { mainClassName = 'kz.bsbnb.usci.core.CoreApplication' }<file_sep>var label_DELETED = 'Правило удалено'; var label_ERROR = 'Ошибка'; var label_NAME = 'Название'; var label_ADD = 'добавить'; var label_CANCEL = 'сброс'; var label_WAIT = 'Подождите…'; var label_INFO = 'Информация'; var label_CACHE = 'Кэш очищен'; var label_ERR_CACHE = 'Ошибка. Кэш не очищен'; var label_HISTORY = 'история'; var lable_REFRESH = 'обновить'; var label_POCKETS = 'пакеты'; var label_SEARCH = 'Поиск'; var label_NO_VERSION = 'Нет версии пакета'; var label_CAN = 'отменить'; var label_SAVE = 'сохранить'; var label_REFRESHED = 'Правило обновлено'; var label_DEL = 'удалить'; var label_CONFIRM = 'Потверждение'; var label_WANT_DEL = 'Вы точно хотите удалить правило ?'; var label_CHOOSE_POCK = 'Выберите пакет'; var label_DATE = 'дата'; var label_NO_ERRORS = 'ошибок нет'; var label_OPEN_DATE = 'Дата открытия'; var label_END_DATE = 'Дата закрытия'; var label_HIS = 'История'; var label_NEW_RULE = 'Новое правило'; var label_POCK = 'пакет'; var label_NAME_LIL = 'название'; var label_ADD_BIG = 'Добавить'; var label_ADDED = 'Правило добавлено'; var label_PACK_CON = 'Управление пакетами'; var label_PACK_NAME = 'Название пакета: '; var label_NEW_PACK = 'Новый пакет добавлен'; var label_DEL_BIG = 'Удалить'; var label_REFRESH_BIG = 'Обновить'; <file_sep>buildscript { ext { springBootVersion = '2.0.0.RELEASE' springCloudVersion = 'Finchley.M9' gsonVersion = '2.8.2' ojdbcVersion = 'ojdbc8' feignVersion = '2.0.1.RELEASE' springKafkaVersion = '2.1.4.RELEASE' slf4jVersion = '1.7.25' modelMapperVersion = '0.7.5' ribbonCoreVersion = '2.7.16' ribbonLoadBalancerVersion = '2.7.16' } repositories { mavenLocal() mavenCentral() maven { url "https://repo.spring.io/milestone" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath( "io.spring.gradle:dependency-management-plugin:1.0.3.RELEASE") } } allprojects { group = "kz.bsbnb.usci" version = '0.1.0' apply plugin: 'java' apply plugin: 'idea' compileJava.options.encoding = 'UTF-8' sourceCompatibility = 1.8 targetCompatibility = 1.8 } subprojects { repositories { flatDir { // некоторых библиотек нет в публичных репозиториях, поэтому держим локально dirs "${rootProject.projectDir}/libs" } mavenLocal() mavenCentral() maven { url "https://repo.spring.io/milestone" } } sourceCompatibility = 1.8 targetCompatibility = 1.8 apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' dependencyManagement { imports { mavenBom("org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}") mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") mavenBom("org.springframework.cloud:spring-cloud-openfeign:${feignVersion}") } } dependencies { compile("org.apache.httpcomponents:httpclient:4.5.3") compile("com.google.code.gson:gson:${gsonVersion}") compile("org.slf4j:slf4j-api:${slf4jVersion}") compile("org.springframework.boot:spring-boot-configuration-processor") testCompile("org.springframework.boot:spring-boot-starter-test") } }<file_sep>group = 'kz.bsbnb.usci.sync' version = '0.1.0' dependencies { compile project(':sync:sync-core') compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.cloud:spring-cloud-starter-openfeign') compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-jdbc") compile("org.springframework.boot:spring-boot-starter-actuator") compile("com.oracle:${ojdbcVersion}") } bootJar { baseName = 'usci-sync-boot' version = '0.1.0' } springBoot { mainClassName = 'kz.bsbnb.usci.sync.SyncApplication' }<file_sep>package kz.bsbnb.usci.wsclient.service; import kz.bsbnb.usci.wsclient.jaxb.ctr.Entities; import kz.bsbnb.usci.wsclient.model.ctrkgd.Request; import java.time.LocalDate; import java.util.List; public interface KGDService { void testRequestKgd(); void ctrRequest(LocalDate reportDate, Long id, boolean isUpdate); List<Request> getCtrRequestList(LocalDate reportDate); } <file_sep>Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.selection.CellModel', 'Ext.grid.*', 'Ext.data.*' ]); Ext.onReady(function () { var periodName; Ext.define('Respondent', { extend: 'Ext.data.Model', fields: ['id', 'name', 'shortName', 'code', 'shutdownDate', 'changeDate', 'bin', 'rnn', 'bik', 'mainOffice', 'branches', 'subjectType'] }); Ext.define('User', { extend: 'Ext.data.Model', fields: ['id', 'userId', 'screenName', 'emailAddress', 'firstName', 'lastName', 'middleName', 'modifiedDate', 'isActive', 'respondents', 'isNb'] }); function createStoreCloneToAnother(sourceStore, targetStore) { var records = []; Ext.each(sourceStore.getRange(), function (record) { records.push(record.copy()); }); targetStore.add(records); } function createStoreClone(sourceStore) { var targetStore = Ext.create('Ext.data.Store', { model: sourceStore.model }); var records = []; Ext.each(sourceStore.getRange(), function (record) { records.push(record.copy()); }); targetStore.add(records); return targetStore; } var leftRespondentsStore = Ext.create('Ext.data.Store', { id: 'leftRespondentsStore', fields: ['id', 'name', 'shortName', 'code', 'shutdownDate', 'changeDate', 'bin', 'rnn', 'bik', 'mainOffice', 'branches', 'subjectType'], autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/core/respondent/getRespondentJsonList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, listeners: { load: function (me, records, options) { rightRespondentsStore.load(); } }, sorters: [{ property: 'name', direction: 'asc' }] }); var rightRespondentsStore = Ext.create('Ext.data.Store', { id: 'rightRespondentsStore', fields: ['id', 'name', 'shortName', 'code', 'shutdownDate', 'changeDate', 'bin', 'rnn', 'bik', 'mainOffice', 'branches', 'subjectType'], autoLoad: false, listeners: { load: function (me, records, options) { createStoreCloneToAnother(leftRespondentsStore, rightRespondentsStore); Ext.Ajax.request({ url: dataUrl + '/utils/config/getDigitalSigningOrgIds', method: 'GET', reader: { type: 'json', root: 'data' }, success: function (response) { var signingRespondentIds = JSON.parse(response.responseText); var records = []; var storeItems = rightRespondentsStore.getRange(); for (var i = 0; i < storeItems.length; i++) { if (Ext.Array.contains(signingRespondentIds, storeItems[i].get('id'))) { leftRespondentsStore.remove(leftRespondentsStore.getById(storeItems[i].get('id'))); records.push(rightRespondentsStore.getById(storeItems[i].get('id'))); } } rightRespondentsStore.removeAll(true); Ext.getCmp('rightRespondentsGrid').getView().refresh(); Ext.getCmp('rightRespondentsGrid').store.add(records); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width: 300, buttons: Ext.MessageBox.YES }); } }); } }, sorters: [{ property: 'name', direction: 'asc' }] }); var respondentStore = Ext.create('Ext.data.Store', { id: 'respondentStore', model: 'Respondent', autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/core/respondent/getRespondentJsonList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, listeners: { load: function (me, records, options) { var userId = Ext.getCmp('userGrid').getSelectionModel().getLastSelected().data.userId; avlRespondentsGrid.reconfigure(createStoreClone(respondentStore)); avlRespondentsGrid.getView().refresh(); selRespondentsGrid.store.load({ params: { userId: userId }, scope: this }); selRespondentsGrid.getView().refresh(); } }, sorters: [{ property: 'name', direction: 'asc' }] }); var userStore = Ext.create('Ext.data.Store', { id: 'userStore', model: 'User', autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/core/user/getUserList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'emailAddress', direction: 'asc' }] }); userStore.on('load', function (s) { if (userGrid.store.getCount() > 0) { Ext.getCmp('userGrid').getSelectionModel().select(0); } Ext.getCmp('userProducts').getStore().load(); }); var selStore = Ext.create('Ext.data.Store', { id: 'selStore', model: 'Respondent', autoLoad: false, proxy: { type: 'ajax', url: dataUrl + '/core/respondent/getUserRespondentList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'name', direction: 'asc' }] }); selStore.on('load', function (s) { if (selRespondentsGrid.store.getCount() > 0) { var records = selRespondentsGrid.store.snapshot || selRespondentsGrid.store.data; for (var i = 0; i < records.items.length; i++) { var founded = avlRespondentsGrid.store.findRecord('name', records.items[i].data.name) if (founded != null) { avlRespondentsGrid.store.remove(founded); } } avlRespondentsGrid.getView().refresh(); } }); var productsStore = Ext.create('Ext.data.Store', { id: 'productsStore', fields: ['id', 'code', 'name'], autoLoad: false, proxy: { type: 'ajax', url: dataUrl + '/core/product/getProductList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'id', direction: 'asc' }], listeners: { load: function (me, records, options) { if (records.length > 0) { Ext.getCmp('userProducts').setValue(records[0].get('id')); } } } }); var allProductsStore = Ext.create('Ext.data.Store', { id: 'allProductsStore', fields: ['id', 'code', 'name'], autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/core/product/getProductList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, listeners: { load: function (me, records, options) { var userId = Ext.getCmp('userGrid').getSelectionModel().getLastSelected().data.userId; Ext.getCmp('userAllProductsGrid').reconfigure(createStoreClone(allProductsStore)); Ext.getCmp('userAllProductsGrid').getView().refresh(); Ext.getCmp('userProductsGrid').store.load({ params: { userId: userId }, scope: this }); Ext.getCmp('userProductsGrid').getView().refresh(); } }, sorters: [{ property: 'id', direction: 'asc' }] }); var userProductsStore = Ext.create('Ext.data.Store', { id: 'userProductsStore', fields: ['id', 'code', 'name'], autoLoad: false, proxy: { type: 'ajax', url: dataUrl + '/core/user/getUserProductJsonList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'id', direction: 'asc' }] }); userProductsStore.on('load', function (s) { if (Ext.getCmp('userProductsGrid').store.getCount() > 0) { var records = Ext.getCmp('userProductsGrid').store.snapshot || Ext.getCmp('userProductsGrid').store.data; for (var i = 0; i < records.items.length; i++) { var founded = Ext.getCmp('userAllProductsGrid').store.findRecord('name', records.items[i].data.name) if (founded != null) { Ext.getCmp('userAllProductsGrid').store.remove(founded); } } Ext.getCmp('userAllProductsGrid').getView().refresh(); } }); var subjectProductsStore = Ext.create('Ext.data.Store', { id: 'subjectProductsStore', fields: ['id', 'code', 'name'], autoLoad: false, proxy: { type: 'ajax', url: dataUrl + '/core/product/getProductList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'id', direction: 'asc' }], listeners: { load: function (me, records, options) { if (records.length > 0) { Ext.getCmp('subjectProducts').setValue(records[0].get('id')); } } } }); var positionsStore = Ext.create('Ext.data.Store', { id: 'positionsStore', fields: ['id', 'nameRu', 'nameKz', 'shortNameRu', 'shortNameKz', 'level'], autoLoad: false, proxy: { type: 'ajax', url: dataUrl + '/core/position/getPositionList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'id', direction: 'asc' }] }); var userPositionsStore = Ext.create('Ext.data.Store', { id: 'userPositionsStore', fields: ['id', 'nameRu', 'nameKz', 'shortNameRu', 'shortNameKz', 'level'], autoLoad: false, proxy: { type: 'ajax', url: dataUrl + '/core/position/getUserPositionListByProduct', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'id', direction: 'asc' }] }); var subjectTypeStore = Ext.create('Ext.data.Store', { id: 'subjectTypeStore', fields: ['id', 'code', 'nameRu', 'nameKz'], autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/core/subject/getSubjectTypeList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'nameRu', direction: 'asc' }] }); var periodTypeStore = Ext.create('Ext.data.Store', { id: 'periodTypeStore', fields: ['id', 'type', 'code', 'nameRu', 'nameKz'], autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/utils/text/getTextListByType', method: 'GET', extraParams: { types: ['PERIOD_TYPE'] }, reader: { type: 'json', root: '' } }, sorters: [{ property: 'id', direction: 'asc' }], listeners: { load: function (me, records, options) { if (records.length > 0) Ext.getCmp('periodTypeCombo').setValue(records[0].get('id')); } } }); var avlRespondentsGrid = Ext.create('Ext.grid.Panel', { id: 'avlRespondentsGrid', multiSelect: true, listeners: { deselect: function (grid, record) { Ext.getCmp('DeleteButton').setDisabled(true); }, select: function (grid, record) { Ext.getCmp('DeleteButton').setDisabled(true); Ext.getCmp('AddButton').setDisabled(false); } }, columns: [{ dataIndex: 'name', flex: 1 }] }); var selRespondentsGrid = Ext.create('Ext.grid.Panel', { id: 'selRespondentsGrid', multiSelect: true, store: selStore, listeners: { deselect: function (grid, record) { Ext.getCmp('AddButton').setDisabled(true); }, select: function (grid, record) { Ext.getCmp('AddButton').setDisabled(true); Ext.getCmp('DeleteButton').setDisabled(false); } }, columns: [{ dataIndex: 'name', flex: 1 }], }); var userGrid = Ext.create('Ext.grid.Panel', { id: 'userGrid', store: userStore, hideHeaders: true, columns: [{ dataIndex: 'emailAddress', flex: 1 }], listeners: { cellclick: function (grid, td, cellIndex, newValue, tr, rowIndex, e, eOpts) { avlRespondentsGrid.reconfigure(createStoreClone(respondentStore)); avlRespondentsGrid.getView().refresh(); var userId = newValue.data.userId; selRespondentsGrid.store.load({ params: { userId: userId }, scope: this }); selRespondentsGrid.getView().refresh(); if (Ext.getCmp('userProducts').getValue() != '') { var positions = []; positionsStore.load({ callback: function () { for (var i = 0; i < Ext.getCmp('positionsGrid').getStore().getRange().length; i++) { positions.push(Ext.getCmp('positionsGrid').getStore().getRange()[i].get('id')); } Ext.getCmp('positionsGrid').getView().refresh(); var productId = Ext.getCmp('userProducts').getValue(); userPositionsStore.load({ params: { userId: userId, productId: productId }, callback: function () { var userPositions = userPositionsStore.getRange(); for (var i = 0; i < userPositions.length; i++) { if (Ext.Array.contains(positions, userPositions[i].get('id'))) { positionsStore.remove(positionsStore.getById(userPositions[i].get('id'))); } } Ext.getCmp('positionsGrid').getView().refresh(); } }); Ext.getCmp('userPositionsGrid').getView().refresh(); Ext.getCmp('positionsGrid').getView().refresh(); } }); } else { Ext.Msg.alert('', 'Выберите продукт!'); } Ext.getCmp('userAllProductsGrid').reconfigure(createStoreClone(allProductsStore)); Ext.getCmp('userAllProductsGrid').getView().refresh(); Ext.getCmp('userProductsGrid').store.load({ params: { userId: userId }, scope: this }); Ext.getCmp('userProductsGrid').getView().refresh(); } }, tbar: [{ xtype: 'textfield', padding: 3, width: 350, listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp("userGrid"); if (newValue == '') { grid.store.clearFilter(); grid.getView().refresh(); } else { grid.store.filter([{ property: "emailAddress", value: newValue, anyMatch: true, caseSensitive: false }]); } } } }, { xtype: 'tbseparator', }] }); var subjectTypeGrid = Ext.create('Ext.grid.Panel', { id: 'subjectTypeGrid', store: subjectTypeStore, columns: [{ dataIndex: 'nameRu', flex: 1 }], listeners: { viewready: function (thisGrid) { Ext.getCmp('subjectTypeGrid').getSelectionModel().select(0); Ext.getCmp('subjectProducts').getStore().load(); }, cellclick: function () { if (Ext.getCmp('subjectProducts').getValue() != '') { Ext.Ajax.request({ url: dataUrl + '/core/subject/getSubjectTypeProductPeriod', method: 'GET', params: { subjectTypeId: subjectTypeGrid.getSelectionModel().getLastSelected().data.id, productId: Ext.getCmp('subjectProducts').getValue() }, reader: { type: 'json', root: 'data' }, success: function (response) { periodName = response.responseText; Ext.getCmp('periodTypeCombo').setValue(periodName); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: 'Ошибка', msg: error.errorMessage, width: 300, buttons: Ext.MessageBox.YES }); Ext.getCmp('periodTypeCombo').setValue("Регулярный"); periodName = ""; } }); } else { Ext.Msg.alert('', label_CHOOSE_PRODUCT); } } } }); var panel = Ext.create('Ext.tab.Panel', { height: 700, width: 1200, renderTo: 'admin-content', title: label_TITLE, padding: 10, id: 'MainTabPanel', items: [{ xtype: 'panel', title: label_SETUP_USERS, width: 1100, height: 600, layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'panel', title: label_USERS, width: 200, split: true, autoScroll: true, flex: 1, items: [{ xtype: 'button', padding: 3, id: 'sync', flex: 1, text: label_SYNC_USERS, listeners: { click: function () { Ext.Ajax.request({ url: dataUrlforUsers, method: 'POST', params: { op: 'SYNCUSERS' }, reader: { type: 'json', root: 'data' }, success: function () { Ext.Msg.alert(label_SYNC); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width: 300, buttons: Ext.MessageBox.YES }); } }); } } }, userGrid ] }, { xtype: 'tabpanel', width: 800, items: [{ xtype: 'panel', title: label_SETUP_RESP, width: 790, layout: { type: 'vbox', align: 'stretch' }, items: [{ xtype: 'panel', title: label_APPOINTED_RESP, autoScroll: true, height: 300, items: [avlRespondentsGrid] }, { xtype: 'panel', height: 24, layout: { align: 'middle', pack: 'center', type: 'hbox' }, items: [{ xtype: 'button', id: 'AddButton', flex: 1, icon: contextPathUrl + '/icons/down_1.png', text: label_ADD, listeners: { click: function (grid, td, cellIndex, newValue, tr, rowIndex, e, eOpts) { var credIds = []; //TODO: временно убрал , пока в таблице нет значения isNb //var isNb = userGrid.getSelectionModel().getLastSelected().data.isNb; for (var i = 0; i < avlRespondentsGrid.store.getCount(); i++) { if (avlRespondentsGrid.getSelectionModel().isSelected(i)) { credIds.push(avlRespondentsGrid.store.getAt(i).data.id); } } var isNb = false; var portalUsers = Ext.decode(users); Ext.Array.each(portalUsers[userGrid.getSelectionModel().getLastSelected().data.userId], function (rec) { if (rec === 'NationalBankEmployee' || rec === 'Administrator') { isNb = true; } }); if (isNb === false && credIds.length >= 1 && selStore.data.length > 0) { Ext.Msg.alert(label_ERROR, label_IMPOSSIBLE_ADDING); } else { Ext.Ajax.request({ url: dataUrl + '/core/respondent/addUserRespondent', method: 'PUT', params: { userId: userGrid.getSelectionModel().getLastSelected().data.userId, respondentIds: credIds }, reader: { type: 'json', root: 'data' }, success: function () { if (Ext.getCmp('avlRespondentsGrid').getSelectionModel().hasSelection()) { var records = Ext.getCmp('avlRespondentsGrid').getSelectionModel().getSelection(); selStore.add(records); avlRespondentsGrid.store.remove(records); } selRespondentsGrid.getView().refresh(); avlRespondentsGrid.getView().refresh(); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width: 300, buttons: Ext.MessageBox.YES }); } }); selRespondentsGrid.getView().refresh(); } } } }, { xtype: 'button', id: 'DeleteButton', flex: 1, icon: contextPathUrl + '/icons/up_1.png', text: label_DELETE, listeners: { click: function () { if (Ext.getCmp('selRespondentsGrid').getSelectionModel().hasSelection()) { var credIds = []; for (var i = 0; i < selRespondentsGrid.store.getCount(); i++) { if (selRespondentsGrid.getSelectionModel().isSelected(i)) { credIds.push(selRespondentsGrid.store.getAt(i).data.id); } } Ext.Ajax.request({ url: dataUrl + '/core/respondent/delUserRespondent', method: 'POST', params: { userId: userGrid.getSelectionModel().getLastSelected().data.userId, respondentIds: credIds }, reader: { type: 'json', root: 'data' }, success: function () { if (Ext.getCmp('selRespondentsGrid').getSelectionModel().hasSelection()) { var records = Ext.getCmp('selRespondentsGrid').getSelectionModel().getSelection(); selStore.remove(records); avlRespondentsGrid.store.add(records); } avlRespondentsGrid.store.sort('name', 'ASC'); selRespondentsGrid.getView().refresh(); avlRespondentsGrid.getView().refresh(); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width: 300, buttons: Ext.MessageBox.YES }); } }) }; selRespondentsGrid.getView().refresh(); } } }] }, { xtype: 'panel', title: label_AVAILABLE_RESP, autoScroll: true, height: 280, items: [selRespondentsGrid] }] }, { xtype: 'panel', title: label_SETUP_POST, autoScroll: true, width: 800, height: 600, layout: { type: 'vbox', align: 'center' }, items: [{ xtype: 'combobox', id: 'userProducts', store: productsStore, margin: '10 0 0 0', width: 450, editable: false, valueField: 'id', displayField: 'name', labelWidth: 130, fieldLabel: label_SELECTED_PROD, labelAlign: 'left', labelStyle: 'font-weight: bold; text-align:center;', listeners: { change: function () { if (userGrid.getSelectionModel().hasSelection()) { var positions = []; positionsStore.load({ callback: function () { for (var i = 0; i < Ext.getCmp('positionsGrid').getStore().getRange().length; i++) { positions.push(Ext.getCmp('positionsGrid').getStore().getRange()[i].get('id')); } Ext.getCmp('positionsGrid').getView().refresh(); var productId = Ext.getCmp('userProducts').getValue(); var userId = userGrid.getSelectionModel().getLastSelected().data.userId; userPositionsStore.load({ params: { userId: userId, productId: productId }, callback: function () { var userPositions = userPositionsStore.getRange(); for (var i = 0; i < userPositions.length; i++) { if (Ext.Array.contains(positions, userPositions[i].get('id'))) { positionsStore.remove(positionsStore.getById(userPositions[i].get('id'))); } } Ext.getCmp('positionsGrid').getView().refresh(); } }); Ext.getCmp('userPositionsGrid').getView().refresh(); Ext.getCmp('positionsGrid').getView().refresh(); } }); } else { Ext.Msg.alert('', label_CHOOSE_USER); } } } }, { xtype: 'label', margin: '10 0 0 0', style: 'font-weight: bold;', text: label_CHOOSE_POST }, { xtype: 'panel', border: false, height: 184, margin: '5 0 0 0', width: '100%', title: '', layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'container', width: '45%', items: [{ xtype: 'gridpanel', id: 'positionsGrid', store: positionsStore, multiSelect: true, height: 176, padding: 5, autoScroll: true, title: label_AVAILABLE_POST, hideHeaders: true, scroll: 'vertical', columns: [{ xtype: 'gridcolumn', width: '100%', dataIndex: 'nameRu', text: '' }], viewConfig: { autoScroll: false } }] }, { xtype: 'container', width: '10%', layout: { type: 'vbox', align: 'center', pack: 'center' }, items: [{ xtype: 'button', margin: '0 0 20 0', text: label_ADD, listeners: { click: function () { var posIds = []; for (var i = 0; i < Ext.getCmp('positionsGrid').store.getCount(); i++) { if (Ext.getCmp('positionsGrid').getSelectionModel().isSelected(i)) { posIds.push(Ext.getCmp('positionsGrid').store.getAt(i).data.id); } } Ext.Ajax.request({ url: dataUrl + '/core/position/addUserPosition', method: 'PUT', params: { userId: userGrid.getSelectionModel().getLastSelected().data.userId, productId: Ext.getCmp('userProducts').getValue(), positionIds: posIds }, reader: { type: 'json', root: 'data' }, success: function () { if (Ext.getCmp('positionsGrid').getSelectionModel().hasSelection()) { var records = Ext.getCmp('positionsGrid').getSelectionModel().getSelection(); Ext.getCmp('positionsGrid').getStore().remove(records); Ext.getCmp('userPositionsGrid').getStore().add(records); } Ext.getCmp('positionsGrid').getView().refresh(); Ext.getCmp('userPositionsGrid').getView().refresh(); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width: 300, buttons: Ext.MessageBox.YES }); } }); Ext.getCmp('userPositionsGrid').getView().refresh(); } } }, { xtype: 'button', text: label_DELETE, listeners: { click: function () { if (Ext.getCmp('userPositionsGrid').getSelectionModel().hasSelection()) { var posIds = []; for (var i = 0; i < Ext.getCmp('userPositionsGrid').store.getCount(); i++) { if (Ext.getCmp('userPositionsGrid').getSelectionModel().isSelected(i)) { posIds.push(Ext.getCmp('userPositionsGrid').store.getAt(i).data.id); } } Ext.Ajax.request({ url: dataUrl + '/core/position/delUserPosition', method: 'POST', params: { userId: userGrid.getSelectionModel().getLastSelected().data.userId, productId: Ext.getCmp('userProducts').getValue(), positionIds: posIds }, reader: { type: 'json', root: 'data' }, success: function () { if (Ext.getCmp('userPositionsGrid').getSelectionModel().hasSelection()) { var records = Ext.getCmp('userPositionsGrid').getSelectionModel().getSelection(); Ext.getCmp('userPositionsGrid').getStore().remove(records); Ext.getCmp('positionsGrid').getStore().add(records); } Ext.getCmp('positionsGrid').getView().refresh(); Ext.getCmp('userPositionsGrid').getView().refresh(); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width: 300, buttons: Ext.MessageBox.YES }); } }) }; Ext.getCmp('userPositionsGrid').getView().refresh(); } } }] }, { xtype: 'container', width: '45%', items: [{ xtype: 'gridpanel', id: 'userPositionsGrid', store: userPositionsStore, multiSelect: true, height: 176, padding: 5, autoScroll: true, title: label_APPOINTED_POST, hideHeaders: true, scroll: 'vertical', columns: [{ xtype: 'gridcolumn', width: '100%', dataIndex: 'nameRu', text: '' }], viewConfig: { autoScroll: false } }] }] }] }, { xtype: 'panel', title: label_SETUP_PRODUCTS, autoScroll: true, width: 800, height: 600, layout: { type: 'vbox', align: 'center' }, items: [{ xtype: 'panel', border: false, height: 184, margin: '5 0 0 0', width: '100%', title: '', layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'container', width: '45%', items: [{ xtype: 'gridpanel', id: 'userAllProductsGrid', multiSelect: true, height: 176, padding: 5, autoScroll: true, title: label_AVAILABLE_PRODUCTS, hideHeaders: true, scroll: 'vertical', columns: [{ xtype: 'gridcolumn', width: '100%', dataIndex: 'name', text: '' }], viewConfig: { autoScroll: false } }] }, { xtype: 'container', width: '10%', layout: { type: 'vbox', align: 'center', pack: 'center' }, items: [{ xtype: 'button', margin: '0 0 20 0', text: label_ADD, listeners: { click: function () { var productIds = []; for (var i = 0; i < Ext.getCmp('userAllProductsGrid').store.getCount(); i++) { if (Ext.getCmp('userAllProductsGrid').getSelectionModel().isSelected(i)) { productIds.push(Ext.getCmp('userAllProductsGrid').store.getAt(i).data.id); } } Ext.Ajax.request({ url: dataUrl + '/core/user/addUserProduct', method: 'PUT', params: { userId: userGrid.getSelectionModel().getLastSelected().data.userId, productIds: productIds }, reader: { type: 'json', root: 'data' }, success: function () { if (Ext.getCmp('userAllProductsGrid').getSelectionModel().hasSelection()) { var records = Ext.getCmp('userAllProductsGrid').getSelectionModel().getSelection(); Ext.getCmp('userAllProductsGrid').getStore().remove(records); Ext.getCmp('userProductsGrid').getStore().add(records); } Ext.getCmp('userAllProductsGrid').getView().refresh(); Ext.getCmp('userProductsGrid').getView().refresh(); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width: 300, buttons: Ext.MessageBox.YES }); } }); Ext.getCmp('userProductsGrid').getView().refresh(); } } }, { xtype: 'button', text: label_DELETE, listeners: { click: function () { if (Ext.getCmp('userProductsGrid').getSelectionModel().hasSelection()) { var productIds = []; for (var i = 0; i < Ext.getCmp('userProductsGrid').store.getCount(); i++) { if (Ext.getCmp('userProductsGrid').getSelectionModel().isSelected(i)) { productIds.push(Ext.getCmp('userProductsGrid').store.getAt(i).data.id); } } Ext.Ajax.request({ url: dataUrl + '/core/user/delUserProduct', method: 'POST', params: { userId: userGrid.getSelectionModel().getLastSelected().data.userId, productIds: productIds }, reader: { type: 'json', root: 'data' }, success: function () { if (Ext.getCmp('userProductsGrid').getSelectionModel().hasSelection()) { var records = Ext.getCmp('userProductsGrid').getSelectionModel().getSelection(); Ext.getCmp('userProductsGrid').getStore().remove(records); Ext.getCmp('userAllProductsGrid').getStore().add(records); } Ext.getCmp('userAllProductsGrid').getView().refresh(); Ext.getCmp('userProductsGrid').getView().refresh(); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width: 300, buttons: Ext.MessageBox.YES }); } }) }; Ext.getCmp('userProductsGrid').getView().refresh(); } } }] }, { xtype: 'container', width: '45%', items: [{ xtype: 'gridpanel', id: 'userProductsGrid', store: userProductsStore, multiSelect: true, height: 176, padding: 5, autoScroll: true, title: label_APPOINTED_PRODUCTS, hideHeaders: true, scroll: 'vertical', columns: [{ xtype: 'gridcolumn', width: '100%', dataIndex: 'name', text: '' }], viewConfig: { autoScroll: false } }] }] }] }] }] }, { xtype: 'panel', title: label_SETUP_PERIODICITY, height: 600, layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'panel', title: label_SUBJECTS, width: 200, split: true, autoScroll: true, flex: 1, items: [ subjectTypeGrid ] }, { xtype: 'panel', title: label_PERIODICITY, autoScroll: true, width: 800, height: 600, layout: { type: 'vbox', align: 'center' }, items: [{ xtype: 'combobox', id: 'subjectProducts', store: subjectProductsStore, margin: '20 0 0 0', width: 450, editable: false, valueField: 'id', displayField: 'name', labelWidth: 130, fieldLabel: label_SELECTED_PROD, labelAlign: 'left', labelStyle: 'font-weight: bold; text-align:center;', listeners: { change: function () { if (subjectTypeGrid.getSelectionModel().hasSelection()) { Ext.Ajax.request({ url: dataUrl + '/core/subject/getSubjectTypeProductPeriod', method: 'GET', params: { subjectTypeId: subjectTypeGrid.getSelectionModel().getLastSelected().data.id, productId: Ext.getCmp('subjectProducts').getValue() }, reader: { type: 'json', root: 'data' }, success: function (response) { periodName = response.responseText; Ext.getCmp('periodTypeCombo').setValue(periodName); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width: 300, buttons: Ext.MessageBox.YES }); Ext.getCmp('periodTypeCombo').setValue("Регулярный"); periodName = ""; } }); } else { Ext.Msg.alert('', label_CHOOSE_SUBJECT); } } } }, { xtype: 'combobox', id: 'periodTypeCombo', store: periodTypeStore, margin: '20 0 0 0', width: 450, editable: false, valueField: 'id', displayField: 'nameRu', labelWidth: 200, fieldLabel: label_PERIOD, labelAlign: 'left', labelStyle: 'font-weight: bold; text-align:center;', listeners: { change: function () { var record = periodTypeStore.findRecord('id', Ext.getCmp('periodTypeCombo').getValue()); if (record !== null && record.get('nameRu') !== periodName) { Ext.getCmp('btnSavePeriod').setDisabled(false); } else { Ext.getCmp('btnSavePeriod').setDisabled(true); } } } }, { xtype: 'button', id: 'btnSavePeriod', margin: '20 0 20 0', text: label_SAVE, enabled: false, listeners: { click: function () { if (subjectTypeGrid.getSelectionModel().hasSelection()) { Ext.Ajax.request({ url: dataUrl + '/core/subject/updateSubjectType', method: 'POST', params: { subjectTypeId: subjectTypeGrid.getSelectionModel().getLastSelected().data.id, productId: Ext.getCmp('subjectProducts').getValue(), periodId: Ext.getCmp('periodTypeCombo').getValue() }, reader: { type: 'json', root: 'data' }, success: function () { Ext.Msg.alert('', label_SUCCESS_UPDATE); Ext.getCmp('btnSavePeriod').setDisabled(true); var record = periodTypeStore.findRecord('id', Ext.getCmp('periodTypeCombo').getValue()); periodName = record.get('nameRu'); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width: 300, buttons: Ext.MessageBox.YES }); } }); Ext.getCmp('userPositionsGrid').getView().refresh(); } else { Ext.Msg.alert('', label_CHOOSE_SUBJECT); } } } }] }] }, { xtype: 'panel', title: label_SETUP_EDS, items: [{ xtype: 'panel', border: false, height: 513, margin: '5 0 0 0', title: '', layout: { type: 'vbox', align: 'center' }, items: [{ xtype: 'label', margin: '10 0 0 0', style: 'font-weight: bold;', text: label_REQUIRED_EDS }, { xtype: 'panel', border: false, height: 184, margin: '5 0 0 0', width: '100%', title: '', layout: { type: 'hbox', align: 'stretch' }, items: [{ xtype: 'container', width: '48%', items: [{ xtype: 'gridpanel', id: 'leftRespondentsGrid', store: leftRespondentsStore, multiSelect: true, height: 176, padding: 5, autoScroll: true, title: '', hideHeaders: true, scroll: 'vertical', columns: [{ xtype: 'gridcolumn', width: '100%', dataIndex: 'name', text: '' }], viewConfig: { autoScroll: false } }] }, { xtype: 'container', width: '4%', layout: { type: 'vbox', align: 'center', pack: 'center' }, items: [{ xtype: 'button', margin: '0 0 20 0', text: '>>', listeners: { click: function () { if (Ext.getCmp('leftRespondentsGrid').getSelectionModel().hasSelection()) { var records = Ext.getCmp('leftRespondentsGrid').getSelectionModel().getSelection(); leftRespondentsStore.remove(records); rightRespondentsStore.add(records) } } } }, { xtype: 'button', text: '<<', listeners: { click: function () { if (Ext.getCmp('rightRespondentsGrid').getSelectionModel().hasSelection()) { var records = Ext.getCmp('rightRespondentsGrid').getSelectionModel().getSelection(); rightRespondentsStore.remove(records); leftRespondentsStore.add(records) } } } }] }, { xtype: 'container', width: '48%', items: [{ xtype: 'gridpanel', id: 'rightRespondentsGrid', store: rightRespondentsStore, multiSelect: true, height: 176, padding: 5, autoScroll: true, title: '', hideHeaders: true, scroll: 'vertical', columns: [{ xtype: 'gridcolumn', width: '100%', dataIndex: 'name', text: '' }], viewConfig: { autoScroll: false } }] }] }, { xtype: 'button', text: label_SAVE, listeners: { click: function () { digiGrid = Ext.getCmp("rightRespondentsGrid"); var credIds = []; for (var i = 0; i < digiGrid.store.getCount(); i++) credIds.push(digiGrid.store.getAt(i).data.id); Ext.Ajax.request({ url: dataUrl + '/utils/config/updateDigitalSigningOrgIds', method: 'POST', params: { digitalSigningOrgIds: credIds }, reader: { type: 'json', root: 'data' }, success: function () { Ext.Msg.alert(label_UPDATED); }, failure: function (response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width: 300, buttons: Ext.MessageBox.YES }); } }); } } }] }] }] }); }); <file_sep>package kz.bsbnb.usci.receiver.processor; import kz.bsbnb.usci.receiver.model.Batch; import kz.bsbnb.usci.receiver.model.BatchFile; public interface BatchReceiver { boolean processBatch(long batchId); void declineMaintenanceBatch(long batchId); void cancelBatch(long batchId); void receiveBatch(BatchFile batchFile); boolean processBatch(Batch batch); } <file_sep>package kz.bsbnb.usci.mail.model; import kz.bsbnb.usci.model.adm.User; import kz.bsbnb.usci.model.persistence.Persistable; import java.time.LocalDateTime; import java.util.Map; /** * @author <NAME> */ public class MailMessage extends Persistable { private static final long serialVersionUID = 1L; private MailMessageStatus status; private User receiver; private MailTemplate mailTemplate; private LocalDateTime creationDate; private LocalDateTime sendingDate; private Map<String, String> params; public MailMessage() { super(); this.creationDate = LocalDateTime.now(); } public User getReceiver() { return receiver; } public void setReceiver(User receiver) { this.receiver = receiver; } public MailMessageStatus getStatus() { return status; } public void setStatus(MailMessageStatus status) { this.status = status; } public MailTemplate getMailTemplate() { return mailTemplate; } public void setMailTemplate(MailTemplate mailTemplate) { this.mailTemplate = mailTemplate; } public LocalDateTime getCreationDate() { return creationDate; } public void setCreationDate(LocalDateTime creationDate) { this.creationDate = creationDate; } public LocalDateTime getSendingDate() { return sendingDate; } public void setSendingDate(LocalDateTime sendingDate) { this.sendingDate = sendingDate; } public Map<String, String> getParams() { return params; } public void setParams(Map<String, String> params) { this.params = params; } @Override public String toString() { return "MailMessage{" + "status=" + status + ", receiver=" + receiver + ", mailTemplate=" + mailTemplate + ", creationDate=" + creationDate + ", sendingDate=" + sendingDate + ", params=" + params + '}'; } } <file_sep>package kz.bsbnb.usci.eav.model.base; import kz.bsbnb.usci.eav.model.meta.MetaType; import kz.bsbnb.usci.eav.model.meta.MetaValue; import java.io.Serializable; import java.util.*; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ public class BaseSet implements BaseContainer, Cloneable, Serializable { private MetaType metaType; // использование HashMap вместе HashSet сделано преднамеренно // необходимо допускать дублирование записей в коллекцию во время парсинга, // и затем выявлять дубликаты через бизнес правила // иначе бы HashSet перетирал дубликаты и в коллекций оставались бы только уникальные записи // в качестве ключей HashMap служат UUID которые генерируют уникальные значения // обычные массивы тоже можно было использовать, но ключи HashMap можно зайдествовать в коде private Map<String, BaseValue> values = new HashMap<>(); public BaseSet() { /*Пустой конструктор*/ } public BaseSet(MetaType metaType) { this.metaType = metaType; } @Override public MetaType getMetaType() { return metaType; } public void put(BaseValue baseValue) { if (baseValue == null) throw new IllegalArgumentException("Добавлять в сет пустое значение не допустимо"); UUID uuid = UUID.randomUUID(); put(uuid.toString(), baseValue); } private void put(String name, BaseValue baseValue) { if (baseValue == null || baseValue.getValue() == null) throw new IllegalArgumentException("Добавлять в множество пустое значение не допустимо"); if (name == null) { UUID uuid = UUID.randomUUID(); put(uuid.toString(), baseValue); } if (baseValue.getValue() instanceof BaseSet) throw new UnsupportedOperationException("Множество не может быть значением в множестве"); values.put(name, baseValue); } @Override public Collection<BaseValue> getValues() { return values.values(); } @Override public String toString() { StringBuilder sb = new StringBuilder("["); boolean first = true; for (BaseValue value : values.values()) { if (first) { sb.append(value.getValue().toString()); first = false; } else { sb.append(", ").append(value.getValue().toString()); } } sb.append("]"); return sb.toString(); } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || getClass() != obj.getClass()) return false; BaseSet that = (BaseSet) obj; MetaType thisMetaType = this.getMetaType(); MetaType thatMetaType = that.getMetaType(); if (!thisMetaType.equals(thatMetaType)) return false; if (this.getValueCount() != that.getValueCount()) return false; Set<UUID> uuids = new HashSet<>(); for (BaseValue thisBaseValue : this.getValues()) { boolean found = false; for (BaseValue thatBaseValue : that.getValues()) { if (uuids.contains(thatBaseValue.getUuid())) continue; Object thisObject = thisBaseValue.getValue(); if (thisObject == null) throw new RuntimeException("Элемент множества не может быть равен null"); Object thatObject = thatBaseValue.getValue(); if (thatObject == null) throw new RuntimeException("Элемент множества не может быть равен null"); if (thisObject.equals(thatObject)) { uuids.add(thatBaseValue.getUuid()); found = true; } } if (!found) return false; } return true; } @Override public int hashCode() { int result = super.hashCode(); for (BaseValue baseValue : values.values()) result += 31 * result + baseValue.getValue().hashCode(); return result; } @Override public BaseSet clone() { BaseSet baseSetCloned; try { baseSetCloned = (BaseSet) super.clone(); HashMap<String, BaseValue> valuesCloned = new HashMap<>(); for (String attribute : values.keySet()) { BaseValue baseValue = values.get(attribute); BaseValue baseValueCloned = baseValue.clone(); valuesCloned.put(attribute, baseValueCloned); } baseSetCloned.values = valuesCloned; } catch (CloneNotSupportedException ex) { throw new RuntimeException("BaseSet класс не реализует интерфейс Cloneable"); } return baseSetCloned; } @Override public boolean isSet() { return true; } @Override public boolean isComplex() { return metaType.isComplex(); } public Object getElSimple(String filter) { if (metaType.isComplex() || metaType.isSet()) { throw new IllegalArgumentException("Простой метод был вызван для комплексного атрибута или массива"); } for (BaseValue value : values.values()) { Object innerValue = value.getValue(); if (innerValue == null) continue; if (value.equalsToString(filter, ((MetaValue) metaType).getMetaDataType())) return innerValue; } return null; } public Object getElComplex(String filter) { if (!metaType.isComplex() || metaType.isSet()) throw new IllegalArgumentException("Комплексный метод был вызван для простого атрибута или массива"); StringTokenizer tokenizer = new StringTokenizer(filter, ","); HashMap<String, String> params = new HashMap<>(); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); StringTokenizer innerTokenizer = new StringTokenizer(token, "="); String fieldName = innerTokenizer.nextToken().trim(); if (!innerTokenizer.hasMoreTokens()) throw new IllegalStateException("Ожидалось значение поля"); String fieldValue = innerTokenizer.nextToken().trim(); params.put(fieldName, fieldValue); } for (BaseValue value : values.values()) { Object innerValue = value.getValue(); if (innerValue == null) continue; if (((BaseEntity) innerValue).equalsToString(params)) return innerValue; } return null; } public Object getEl(String filter) { if (metaType.isComplex()) return getElComplex(filter); return getElSimple(filter); } @Override public int getValueCount() { return values.size(); } } <file_sep>package kz.bsbnb.usci.mail; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @SpringBootApplication @Configuration @ComponentScan(basePackages = {"kz.bsbnb.usci"}) @EnableConfigurationProperties @EnableFeignClients(basePackages = {"kz.bsbnb.usci.core.client"}) @EnableEurekaClient public class MailApplication { public static void main(String[] args) { SpringApplication.run(MailApplication.class, args); } } <file_sep>/** * @author <NAME> */ function fillSearchTree(metaClassId) { var tree = Ext.getCmp('searchTreeView'); var rootNode = tree.getRootNode(); rootNode.removeAll(); var loadMask = new Ext.LoadMask(Ext.getCmp('mainPanel'), {msg:label_LOADING}); loadMask.show(); Ext.Ajax.request({ url: dataUrl + '/core/meta/getMetaClassAttributesList', params : { metaClassId: metaClassId }, method: 'GET', failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.errorMessage, width : 300, buttons: Ext.MessageBox.YES }); }, success: function(response) { // получаем мета атрибуты у мета класса // затем атрибуты boolean, комплексные сущности создаем чтобы юзер // тыкал и добавлял параметры поиска var attributes = JSON.parse(response.responseText); for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; if (!attribute.key) continue; if (attribute.simple && attribute.metaType === 'BOOLEAN') { attribute.iconCls = 'file'; attribute.leaf = 'true'; attribute.value = false; rootNode.appendChild(attribute); } else if (!attribute.simple && !attribute.dictionary) { attribute.expanded = true; rootNode.appendChild(attribute); } } loadMask.hide(); Ext.getCmp('searchTreeView').getView().refresh(); } }); } // добавление атрибута или элемента сета function showAddSearchParamWindow(node) { var metaClassId = null; var windowTitle = null; if (node.data.depth == 0) { metaClassId = Ext.getCmp('edMetaClass').value; windowTitle = Ext.getCmp('edMetaClass').getRawValue(); } else { metaClassId = node.data.refClassId; windowTitle = node.data.title; } if (node.data.array) { if (node.data.simple) { //нет данных для тестирования throw label_SIMPLE_MASS; } else { showArrayNewElWindow(metaClassId, node, windowTitle, true, function() { Ext.getCmp('searchTreeView').getView().refresh(); }); } } else { showAddAttrWindow(node, metaClassId, windowTitle, true, function(form) { Ext.getCmp('searchTreeView').getView().refresh(); }); } } function getSearchDataFromTree(currentNode) { var entityData = {name: currentNode.data.name, value: currentNode.data.value, children: []}; var children = currentNode.childNodes; for (var i = 0; i < children.length; i++) { if (children[i].data.simple) { // обрабатываем простые сеты if (currentNode.data.array) { } else { // по справочникам включаем только ключевые атрибуты // все остальные атрибуты пропускаем if (currentNode.data.dictionary && !children[i].data.key) continue; var attrData = {name: children[i].data.name, value: children[i].data.value, children: []}; entityData.children.push(attrData); } } else { // комплексная сущность var childEntityData = getSearchDataFromTree(children[i]); entityData.children.push(childEntityData); } } return entityData; }<file_sep>var label_ERROR = 'Ошибка'; var label_DOWNLOAD = 'Загрузить профили'; var label_SPISOK = 'Список профилей'; var label_PROTECTED = 'Профиль защищен паролем'; var label_PASSWORD = '<PASSWORD>: '; var label_GET_SERT = 'Получить сертификаты из профиля'; var label_CANT_GET = 'Не удалось получить список сертификатов'; var label_SERTIFICATE = 'Сертификат'; var label_FILE_NAME = 'Имя файла'; var label_REC_DATE = 'Дата получения'; var label_SIGNED = 'Подписан'; var label_SING_SAVE = 'Подписать и сохранить выбранные файлы'; var label_CHOOSE_P = 'Выберите профиль'; var label_CHOOSE_S = 'Выберите сертификат'; var label_WAIT = 'Подождите...'; var label_BATCHES_SAVED = 'Подписанные батчи сохранены'; var label_CANCEL_SELECTED = 'Отменить загрузку выбранных файлов'; var label_BATCHES_CANCELED = 'Выбранные батчи отменены'; <file_sep>package kz.bsbnb.usci.util.client; import kz.bsbnb.usci.model.util.Application; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @FeignClient(name = "utils") public interface ApplicationClient { @GetMapping(value = "/config/getApplicationList") List<Application> getApplicationList(); } <file_sep>Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.selection.CellModel', 'Ext.grid.*', 'Ext.data.*', 'Ext.button.*', 'Ext.toolbar.*', 'Ext.container.*' ]); Ext.onReady(function () { function isEmpty(value) { return value === undefined || value === null || value.length === 0; } function getProfiles() { var profilesString = document.app.getProfileNames('|'); return profilesString.split('|'); } function getCertificates(profile, password) { var certificatesInfo = document.app.getCertificatesInfo(profile, password, 0, '', true, false, '|'); return certificatesInfo.split('|'); } function signHash(value, certificate, profile, password) { return document.app.createPKCS7(value, 0, null, certificate, true, profile, password, '1.3.6.1.4.1.6801.1.5.8', true); } function getFileName(value) { var startIndex = (value.indexOf('\\') >= 0 ? value.lastIndexOf('\\') : value.lastIndexOf('/')); var filename = value.substring(startIndex); if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) { filename = filename.substring(1); } return filename; } var profilesStore = Ext.create('Ext.data.Store', { id: 'profilesStore', fields: ['name'], data : [ {"name":"Нажмите на кнопку \"Загрузить профили\" ..."} ], autoload: false }); var certificatesStore = Ext.create('Ext.data.Store', { id: 'certificatesStore', fields: ['name'], data : [ {"name":"Нажмите на кнопку \"Получить сертификаты из профиля\" ..."} ], autoload: false }); var userRespondentStore = Ext.create('Ext.data.Store', { id: 'userRespondentStore', fields: ['id', 'name', 'shortName', 'code', 'shutdownDate', 'changeDate', 'bin', 'rnn', 'bik', 'mainOffice', 'branches', 'subjectType'], autoLoad: true, proxy: { type: 'ajax', url: dataUrl + '/core/respondent/getUserRespondentList', extraParams: {userId: userId}, actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, listeners: { load: function () { var creditorId = userRespondentStore.getAt(0).data.id; Ext.getCmp('batchSignGrid').store.load({ params: { respondentId: creditorId, userId: userId }, scope: this }); Ext.getCmp('batchSignGrid').getView().refresh(); } }, sorters: [{ property: 'name', direction: 'asc' }] }); var batchSignStore = Ext.create('Ext.data.Store', { id: 'batchSignStore', fields: ['id', 'receiverDate', 'fileName', 'hash', 'totalEntityCount', 'signSymbol', 'signature', 'check'], autoLoad: false, proxy: { type: 'ajax', url: dataUrl+'/receiver/batch/getBatchListToSign', method: 'GET', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } }, }); var panel = Ext.create('Ext.panel.Panel', { height: 800, margin: 0, width: 1200, autoScroll: true, title: ' ', titleCollapse: false, renderTo: 'signing-content', id: 'MainPanel', listeners: { afterrender: function () { Ext.getCmp('profilesCombo').setValue(profilesStore.getAt(0).data.name); Ext.getCmp('certsCombo').setValue(certificatesStore.getAt(0).data.name); } }, items: [{ xtype: 'button', margin: '10 0 0 10', text: label_DOWNLOAD, listeners: { click: function () { var profiles = getProfiles(); var selectedValue = ''; var store = Ext.getCmp('profilesCombo').getStore(); store.removeAll(); Ext.getCmp('profilesCombo').setValue(null); store.commitChanges(); for (var i = 0; i < profiles.length; i++) { store.add({name: profiles[i]}); if (profiles[i] === 'profile://FSystem') { selectedValue = profiles[i]; } } if (!isEmpty(selectedValue)) { Ext.getCmp('profilesCombo').setValue(selectedValue); } } } }, { xtype: 'combobox', id: 'profilesCombo', store: profilesStore, margin: '10 0 0 10', width: 400, editable : false, valueField: 'name', displayField: 'name', fieldLabel: label_SPISOK, labelWidth: 130, labelAlign: 'left', labelStyle: 'font-weight: bold;' }, { xtype: 'checkboxfield', margin: '10 0 0 10', cls: 'checkBox', fieldLabel: '', boxLabel: label_PROTECTED, listeners: { change: function (field, newValue, oldValue, options) { passfield = Ext.getCmp("profilePasword"); if (newValue == '1') { passfield.show(); } else if (newValue == '0') { passfield.hide(); } } } }, { xtype: 'textfield', id: 'profilePasword', hidden: true, margin: '10 0 0 10', fieldLabel: label_PASSWORD, labelWidth: 130, inputType: 'password' }, { xtype: 'button', margin: '10 0 0 10', text: label_GET_SERT, listeners: { click: function () { var profile = Ext.getCmp('profilesCombo').getValue(); var password = Ext.getCmp('profilePasword').getValue(); var certificates = getCertificates(profile, password); if (!certificates || (certificates.length === 0)) { Ext.Msg.alert(label_CANT_GET); return; } var store = Ext.getCmp('certsCombo').getStore(); store.removeAll(); Ext.getCmp('certsCombo').setValue(null); store.commitChanges(); for (var i = 0; i < certificates.length; i++) { store.add({name: certificates[i]}); } Ext.getCmp('certsCombo').setValue(store.getAt(0)); } } }, { xtype: 'combobox', id: 'certsCombo', store: certificatesStore, margin: '10 0 0 10', width: 1000, editable : false, valueField: 'name', displayField: 'name', fieldLabel: label_SERTIFICATE, labelAlign: 'left', labelStyle: 'font-weight: bold;' }, { xtype: 'gridpanel', id: 'batchSignGrid', store: batchSignStore, height: 400, width: 1190, margin: '10 0 15 5', autoScroll: true, title: '', columns: [{ xtype: 'checkcolumn', dataIndex : 'check', width: 60, text: '' }, { xtype: 'gridcolumn', width: 300, dataIndex: 'fileName', text: label_FILE_NAME }, { xtype: 'datecolumn', width: 130, dataIndex: 'receiverDate', text: label_REC_DATE, format: 'd.m.Y H:i:s' }, { xtype: 'gridcolumn', dataIndex : 'signSymbol', width: 136, text: label_SIGNED }], dockedItems: [{ xtype: 'toolbar', dock: 'bottom', items: [{ text: 'Выделить все', handler: function() { var batchSignGridStore = Ext.getCmp('batchSignGrid').getStore(); batchSignGridStore.suspendEvents(); batchSignGridStore.each(function(rec){ rec.set('check', true) }) batchSignGridStore.resumeEvents(); Ext.getCmp('batchSignGrid').getView().refresh(); } }, { xtype: 'tbseparator', }, { text: 'Снять выделение', handler: function() { var batchSignGridStore = Ext.getCmp('batchSignGrid').getStore(); batchSignGridStore.suspendEvents(); batchSignGridStore.each(function(rec){ rec.set('check', false) }) batchSignGridStore.resumeEvents(); Ext.getCmp('batchSignGrid').getView().refresh(); } }, { xtype: 'tbseparator', }, { xtype: 'button', text: label_SING_SAVE, listeners: { click: function () { var profile = Ext.getCmp('profilesCombo').getValue(); if (isEmpty(profile)) { Ext.Msg.alert(label_CHOOSE_P); return; } var certificate = Ext.getCmp('certsCombo').getValue(); if (isEmpty(certificate)) { Ext.Msg.alert(label_CHOOSE_S); return; } var password = Ext.getCmp('profilePasword').getValue(); var loadMask = new Ext.LoadMask(Ext.getBody(), { msg: label_WAIT }); loadMask.show(); gridBatch = Ext.getCmp("batchSignGrid"); for (var i = 0; i < gridBatch.store.getCount(); i++) { if (gridBatch.store.getAt(i).data.check === true) { var pkcs7 = signHash(gridBatch.store.getAt(i).data.hash, certificate, profile, password); gridBatch.store.getAt(i).data.signature = pkcs7; gridBatch.store.getAt(i).data.signSymbol = '<img src="'+ contextPathUrl + '/pics/accept.png"/>'; gridBatch.store.getAt(i).commit(); } } gridBatch.getView().refresh(); var creditorBin = userRespondentStore.getAt(0).data.bin; var batchSignJsonList = { batchList: []}; for (var i = 0; i < gridBatch.store.getCount(); i++) { if (gridBatch.store.getAt(i).data.check === true) { batchSignJsonList.batchList.push(gridBatch.store.getAt(i).data); } } Ext.Ajax.request({ url: dataUrl + '/receiver/batch/saveSignedBatchList', method: 'POST', params: { respondentBin: creditorBin }, jsonData: batchSignJsonList, reader: { type: 'json', root: 'data' }, success: function() { loadMask.hide(); Ext.Msg.alert(label_BATCHES_SAVED); gridBatch.store.remove(records); }, failure: function(response) { loadMask.hide(); var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); gridBatch.getView().refresh(); } } }, { xtype: 'tbseparator' }, { xtype: 'button', text: label_CANCEL_SELECTED, listeners: { click: function () { gridBatch = Ext.getCmp("batchSignGrid"); var batchIds = []; var records = []; for (var i = 0; i < gridBatch.store.getCount(); i++) { if (gridBatch.store.getAt(i).data.check === true) { batchIds.push(gridBatch.store.getAt(i).data.id); records.push(gridBatch.store.getAt(i)); } } Ext.Ajax.request({ url: dataUrl+'/receiver/batch/cancelBatch', method: 'POST', params: { batchIds: batchIds }, reader: { type: 'json', root: 'data' }, success: function() { Ext.Msg.alert(label_BATCHES_CANCELED); gridBatch.store.remove(records); }, failure: function(response) { var error = JSON.parse(response.responseText); Ext.Msg.show({ title: label_ERROR, msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); gridBatch.getView().refresh(); } } }] }], viewConfig:{ markDirty:false } }] }); }); <file_sep>group = 'kz.bsbnb.usci.brms' version = '0.1.0' dependencies { compile project(':model') compile project(':eav:eav-api') compile project(':util:util-api') } jar { baseName = 'usci-brms-api' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>package kz.bsbnb.usci.receiver.dao; import kz.bsbnb.usci.receiver.model.BatchEntry; import java.util.List; /** * @author <NAME> * @author <NAME> */ public interface BatchEntryDao { BatchEntry load(Long id); void remove(Long id); List<BatchEntry> getBatchEntriesByUserId(Long userId); Long save(BatchEntry batchEntry); void setProcessed(List<Long> batchEntryIds); } <file_sep>package kz.bsbnb.usci.eav.service; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.meta.MetaClass; import java.time.LocalDate; import java.util.List; /** * @author <NAME> */ public interface BaseEntityLoadService { BaseEntity loadByMaxReportDate(BaseEntity baseEntity, LocalDate savingReportDate); BaseEntity loadBaseEntity(BaseEntity baseEntity, LocalDate savingReportDate); BaseEntity loadBaseEntity(BaseEntity baseEntity); List<BaseEntity> loadBaseEntityEntries(BaseEntity baseEntity, LocalDate reportDate); List<BaseEntity> loadBaseEntitiesByMetaClass(MetaClass metaClass); } <file_sep>/** * @author <NAME> */ function createDateTimePicker(fieldLabel, labelWidth, fieldId, width, value, allowBlank, readOnly) { var dateTime = value? moment(value, 'DD.MM.YYYY HH:mm:ss'): null; var dateField = Ext.create("Ext.form.field.Date", { id: fieldId, width: '60%', format: 'd.m.Y', value: dateTime? dateTime.toDate(): null, readOnly: readOnly, allowBlank: allowBlank, blankText: label_REQUIRED_FIELD, getDateTimeValue: function() { var rawDateTime = this.getValue(); if (!rawDateTime) return null; var hours = Number(hourField.value); var minutes = Number(minField.value); var seconds = Number(secField.value); rawDateTime.setHours(hours); rawDateTime.setMinutes(minutes); rawDateTime.setSeconds(seconds); return rawDateTime; }, getValueAsString: function() { var rawDateTime = this.getDateTimeValue(); var asString = moment(rawDateTime).format('DD.MM.YYYY HH:mm:ss'); return asString; } }); var hourField = Ext.create("Ext.form.field.Number", { id: fieldId + '_hour', fieldLabel: '', labelWidth: '0%', width: 45, value: dateTime? dateTime.hours(): 0, allowDecimals: false, allowNegative: false, minValue: 0, maxValue: 23 }); var minField = Ext.create("Ext.form.field.Number", { id: fieldId + '_min', fieldLabel: '', labelWidth: '0%', width: 45, value: dateTime? dateTime.minutes(): 0, allowDecimals: false, allowNegative: false, minValue: 0, maxValue: 59 }); var secField = Ext.create("Ext.form.field.Number", { id: fieldId + '_sec', fieldLabel: '', labelWidth: '0%', width: 45, value: dateTime? dateTime.seconds(): 0, allowDecimals: false, allowNegative: false, minValue: 0, maxValue: 59 }); var panelDict = Ext.create('Ext.form.FieldContainer', { fieldLabel: fieldLabel, labelWidth: labelWidth, width: width, preventHeader: true, border: 0, layout: { type: 'hbox', align: 'stretch' }, items: [dateField, hourField, minField, secField] }); return panelDict; }<file_sep>plugins { id 'java' id 'war' } group = 'kz.bsbnb.usci.portlet' version = '0.1.0' description = "USCI Portlet: Queue Portlet" sourceCompatibility = 1.7 targetCompatibility = 1.7 repositories { mavenCentral() } war { baseName = 'queue_portlet' version = '2.1.0' enabled = true } bootWar { enabled = false } dependencies { compile group: 'org.json', name: 'json', version:'20090211' compile group: 'com.google.code.gson', name: 'gson', version:'2.8.2' compile group: 'jstl', name: 'jstl', version:'1.2' compile group: 'com.liferay.portal', name: 'portal-service', version:'6.1.1' compile group: 'com.liferay.portal', name: 'util-bridges', version:'6.1.1' compile group: 'com.liferay.portal', name: 'util-taglib', version:'6.1.1' compile group: 'com.liferay.portal', name: 'util-java', version:'6.1.1' compile group: 'javax.portlet', name: 'portlet-api', version:'2.0' compile group: 'javax.servlet', name: 'servlet-api', version:'2.4' compile group: 'javax.servlet.jsp', name: 'jsp-api', version:'2.0' } <file_sep>group 'kz.bsbnb.usci' version '1.0.1' dependencies { compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-server') } bootJar { baseName = 'usci-eureka' } springBoot { mainClassName = 'kz.bsbnb.usci.eureka.EurekaApplication' } <file_sep>package kz.bsbnb.usci.eav.dao; import kz.bsbnb.usci.eav.model.core.EavHub; import java.util.List; import java.util.Optional; /** * @author <NAME> */ public interface BaseEntityHubDao { void insert(List<EavHub> hubs); Optional<Long> find(EavHub eavHub, List<String> keys); void delete(EavHub eavHub); void update(EavHub eavHub); } <file_sep>package kz.bsbnb.usci.wsclient.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ws.WebServiceMessage; import org.springframework.xml.transform.TransformerObjectSupport; import java.io.ByteArrayOutputStream; public class HttpLoggingUtils extends TransformerObjectSupport { private static final Logger LOGGER = LoggerFactory.getLogger(HttpLoggingUtils.class); private HttpLoggingUtils() {} public static String getMessage(WebServiceMessage webServiceMessage) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); webServiceMessage.writeTo(byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (Exception e) { LOGGER.error("Unable to get HTTP message.", e); return null; } } }<file_sep>var label_ERROR = 'Қате'; var label_RETURN = 'Есептер тізіліміне қайта оралу'; var label_FILTER = 'Филтрді қосу'; var label_CHOSEN = 'Есеп таңдалынды'; var label_PARAMETRS = 'Енгізу парамерлерін толтырыңыз'; var label_REPORT = 'XLS есепті жүктеу'; var label_TABLE = 'Есеп кестесін жүктеу '; var label_REPORTING = 'Есепті құрастыру орындалуда... '; var label_REP_NAME = 'Есептің атауы'; var LABEL_USER = 'Пайдаланушы'; var label_BEG_TIME = 'Басталу уақыты '; var label_END_TIME = 'Аяқталу уақыты '; var label_COMMENT = 'Пікірлер'; var label_REFRESH = 'Жаңарту'; var label_OUTPUT = 'Шығыс формалары'; var label_SPISOK = 'Есептер тізімі'; var label_FINISHED = 'Жасалған есептер'; var label_FILES = 'Файлдар'; var label_FILE_NAME = 'Файлдың атауы'; var label_DOWNLOAD = 'Жүктеу'; <file_sep>package kz.bsbnb.usci.receiver.reader; import kz.bsbnb.usci.eav.model.meta.MetaDataType; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.receiver.model.deprecated.InfoData; import javax.xml.namespace.QName; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.time.format.DateTimeParseException; /** * @author <NAME> */ @Deprecated public class InfoParser extends MainReader { private final InfoData infoData = new InfoData(); @Override public void startElement(XMLEvent event, StartElement startElement, String localName) { switch (localName) { case "code": break; case "doc": infoData.setDocType(event.asStartElement().getAttributeByName(new QName("doc_type")).getValue()); break; case "no": break; case "account_date": break; case "report_date": break; case "actual_credit_count": break; case "maintenance": String val = ((XMLEvent) this.xmlReader.next()).asCharacters().getData(); infoData.setMaintenance("1".equals(val) || "true".equals(val)); break; } } @Override public boolean endElement(String localName) { switch (localName) { case "info": return true; case "code": infoData.setCode(data.toString()); data.setLength(0); break; case "doc": break; case "no": infoData.setDocValue(data.toString()); data.setLength(0); break; case "account_date": try { infoData.setAccountDate(MetaDataType.parseSplashDate(data.toString())); } catch (DateTimeParseException e) { throw new UsciException(e.getMessage()); } data.setLength(0); break; case "report_date": try { infoData.setReportDate(MetaDataType.parseSplashDate(data.toString())); } catch (DateTimeParseException e) { throw new UsciException(e.getMessage()); } data.setLength(0); break; case "actual_credit_count": try { infoData.setActualCreditCount(Long.parseLong(data.toString())); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } data.setLength(0); break; case "name": data.setLength(0); break; } return false; } public InfoData getInfoData() { return infoData; } } <file_sep>package kz.bsbnb.usci.eav.dao; import kz.bsbnb.usci.eav.model.base.OperType; import kz.bsbnb.usci.eav.model.core.BaseEntityStatus; import kz.bsbnb.usci.eav.model.core.EntityStatusType; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author <NAME> * @author <NAME> */ @Repository public class BaseEntityStatusDaoImpl implements BaseEntityStatusDao { private SimpleJdbcInsert baseEntityStatusInsert; private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; private static final Logger logger = LoggerFactory.getLogger(BaseEntityStatusDaoImpl.class); public BaseEntityStatusDaoImpl(JdbcTemplate baseEntityStatusInsert, JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) { this.baseEntityStatusInsert = new SimpleJdbcInsert(baseEntityStatusInsert) .withTableName("EAV_ENTITY_STATUS") .withSchemaName("EAV_DATA") .usingColumns("BATCH_ID", "META_CLASS_ID", "EXCEPTION_TRACE", "ENTITY_INDEX", "ENTITY_ID", "SYSTEM_DATE", "ENTITY_TEXT", "STATUS_ID", "OPERATION_ID", "ERROR_CODE", "ERROR_MESSAGE") .usingGeneratedKeyColumns("ID"); this.jdbcTemplate = jdbcTemplate; this.npJdbcTemplate = npJdbcTemplate; } @Override public BaseEntityStatus insert(BaseEntityStatus baseEntityStatus) { String exceptionTrace = baseEntityStatus.getExceptionTrace(); if (exceptionTrace != null && exceptionTrace.length() > 4000) exceptionTrace = exceptionTrace.substring(0, 3000); Number id = baseEntityStatusInsert .executeAndReturnKey(new MapSqlParameterSource("BATCH_ID", baseEntityStatus.getBatchId()) .addValue("ENTITY_ID", baseEntityStatus.getEntityId()) .addValue("META_CLASS_ID", baseEntityStatus.getMetaClassId()) .addValue("SYSTEM_DATE", baseEntityStatus.getSystemDate()) .addValue("ENTITY_INDEX", baseEntityStatus.getIndex()) .addValue("STATUS_ID", baseEntityStatus.getStatus().getId()) .addValue("OPERATION_ID", baseEntityStatus.getOperation() != null ? baseEntityStatus.getOperation().getId() : null) .addValue("ENTITY_TEXT", baseEntityStatus.getEntityText()) .addValue("ERROR_CODE", baseEntityStatus.getErrorCode()) .addValue("ERROR_MESSAGE", baseEntityStatus.getErrorMessage()) .addValue("EXCEPTION_TRACE", exceptionTrace)); baseEntityStatus.setId(id.longValue()); return baseEntityStatus; } //TODO /* Данный метод реалтзован для времнного решение проблем с очередью. Проблема заключается в том, что когда нагрузка большая executeAndReturnKey застревает */ @Override public BaseEntityStatus insertBatchMethod(BaseEntityStatus baseEntityStatus) { String exceptionTrace = baseEntityStatus.getExceptionTrace(); String errorMessage = baseEntityStatus.getErrorMessage(); if (exceptionTrace != null && exceptionTrace.length() > 4000) exceptionTrace = exceptionTrace.substring(0, 3000); if (errorMessage != null && errorMessage.length() > 4000) errorMessage = errorMessage.substring(0, 3000); baseEntityStatusInsert .executeBatch(new MapSqlParameterSource("BATCH_ID", baseEntityStatus.getBatchId()) .addValue("ENTITY_ID", baseEntityStatus.getEntityId()) .addValue("META_CLASS_ID", baseEntityStatus.getMetaClassId()) .addValue("SYSTEM_DATE", baseEntityStatus.getSystemDate()) .addValue("ENTITY_INDEX", baseEntityStatus.getIndex()) .addValue("STATUS_ID", baseEntityStatus.getStatus().getId()) .addValue("OPERATION_ID", baseEntityStatus.getOperation() != null ? baseEntityStatus.getOperation().getId() : null) .addValue("ENTITY_TEXT", baseEntityStatus.getEntityText()) .addValue("ERROR_CODE", baseEntityStatus.getErrorCode()) .addValue("ERROR_MESSAGE", errorMessage) .addValue("EXCEPTION_TRACE", exceptionTrace)); return baseEntityStatus; } @Override public void update(BaseEntityStatus baseEntityStatus) { int count = npJdbcTemplate.update("update EAV_DATA.EAV_ENTITY_STATUS\n" + " set ENTITY_ID = :ENTITY_ID, STATUS_ID = :STATUS_ID, OPERATION_ID = :OPERATION_ID, SYSTEM_DATE = :SYSTEM_DATE, ERROR_MESSAGE = :ERROR_MESSAGE \n" + " where BATCH_ID = :BATCH_ID and ENTITY_ID = :APPROVED_ENTITY_ID and STATUS_ID = 9", new MapSqlParameterSource("BATCH_ID", baseEntityStatus.getBatchId()) .addValue("ENTITY_ID", baseEntityStatus.getEntityId()) .addValue("APPROVED_ENTITY_ID", baseEntityStatus.getApprovedEntityId()) .addValue("STATUS_ID", baseEntityStatus.getStatus().getId()) .addValue("OPERATION_ID", baseEntityStatus.getOperation() != null ? baseEntityStatus.getOperation().getId() : null) .addValue("SYSTEM_DATE", baseEntityStatus.getSystemDate()) .addValue("ERROR_MESSAGE",baseEntityStatus.getErrorMessage())); if (count != 1) throw new UsciException("Ошибка update записи в таблице EAV_DATA.EAV_ENTITY_STATUS"); } @Override public Object[] getStatusList(Long batchId, List<EntityStatusType> statuses) { String selectClause = "select *\n" + " from EAV_DATA.EAV_ENTITY_STATUS t\n"; String whereClause = "where BATCH_ID = :batchId\n" + " and STATUS_ID in (:statusIds)\n"; String fetchQuery = selectClause + whereClause + "order by SYSTEM_DATE desc\n"; String countQuery = "select count(1) from EAV_DATA.EAV_ENTITY_STATUS\n" + whereClause; MapSqlParameterSource params = new MapSqlParameterSource("batchId", batchId) .addValue("statusIds", statuses.stream() .map(EntityStatusType::getId) .collect(Collectors.toList())); int count = npJdbcTemplate.queryForObject(countQuery, params, Integer.class); List<Map<String, Object>> rows = npJdbcTemplate.queryForList(fetchQuery, params); List<BaseEntityStatus> list = new ArrayList<>(); for (Map<String, Object> row : rows) list.add(getBaseEntityStatusFromJdbcMap(row)); return new Object[] {list, count}; } @Override public int getErrorEntityCount(long batchId) { return jdbcTemplate.queryForObject("select count(1) from EAV_DATA.EAV_ENTITY_STATUS where BATCH_ID = ? and STATUS_ID = ?", new Object[] {batchId, EntityStatusType.ERROR.getId()}, Integer.class); } @Override public int getSuccessEntityCount(long batchId) { return jdbcTemplate.queryForObject("select count(1) from EAV_DATA.EAV_ENTITY_STATUS where BATCH_ID = ? and STATUS_ID = ?", new Object[] {batchId, EntityStatusType.COMPLETED.getId()}, Integer.class); } private BaseEntityStatus getBaseEntityStatusFromJdbcMap(Map<String, Object> row) { BaseEntityStatus entityStatus = new BaseEntityStatus(); entityStatus.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); entityStatus.setEntityId(SqlJdbcConverter.convertToLong(row.get("ENTITY_ID"))); entityStatus.setMetaClassId(SqlJdbcConverter.convertToLong(row.get("META_CLASS_ID"))); entityStatus.setBatchId(SqlJdbcConverter.convertToLong(row.get("BATCH_ID"))); entityStatus.setIndex(SqlJdbcConverter.convertToLong(row.get("INDEX"))); entityStatus.setOperation(row.get("OPERATION_ID") != null? OperType.getOperType(SqlJdbcConverter.convertToShort(row.get("OPERATION_ID"))): null); entityStatus.setErrorCode(SqlJdbcConverter.convertObjectToString(row.get("ERROR_CODE"))); entityStatus.setErrorMessage(SqlJdbcConverter.convertObjectToString(row.get("ERROR_MESSAGE"))); entityStatus.setStatus(EntityStatusType.getEntityStatus(SqlJdbcConverter.convertToInt(row.get("STATUS_ID")))); entityStatus.setEntityText(SqlJdbcConverter.convertObjectToString(row.get("ENTITY_TEXT"))); return entityStatus; } } <file_sep>package kz.bsbnb.usci.wsclient.model.ctrkgd; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public enum RequestStatus { SUCCESS(100), ERROR(101); private long id; RequestStatus(int id) { this.id = id; } public long getId() { return id; } public void setId(int id) { this.id = id; } public String type() { return "REQUEST_STATUS"; } public String code() { return name(); } private static final Map<Long, RequestStatus> map = new ConcurrentHashMap<>(); static { for (RequestStatus requestStatus : RequestStatus.values()) { map.put(requestStatus.getId(), requestStatus); } } public static RequestStatus getRequestStatus(long id) { return map.get(id); } } <file_sep>package kz.bsbnb.usci.portlet.static_portlet; import com.liferay.util.bridges.mvc.MVCPortlet; public class StaticPortlet extends MVCPortlet { } <file_sep>package kz.bsbnb.usci.portlet.meta; import com.liferay.util.bridges.mvc.MVCPortlet; public class MetaPortlet extends MVCPortlet { } <file_sep>package kz.bsbnb.usci.receiver.validator; import kz.bsbnb.usci.model.respondent.Respondent; import kz.bsbnb.usci.receiver.model.Batch; import java.util.List; public interface BatchValidator { void validateUserRespondent(Batch batch, List<Respondent> userRespondents); } <file_sep>package kz.bsbnb.usci.wsclient.service; import kz.bsbnb.usci.util.SqlJdbcConverter; import kz.bsbnb.usci.wsclient.client.KGDSOAPClient; import kz.bsbnb.usci.wsclient.dao.KGDDao; import kz.bsbnb.usci.wsclient.jaxb.ctr.*; import kz.bsbnb.usci.wsclient.jaxb.kgd.ResponseMessage; import kz.bsbnb.usci.wsclient.model.ctrkgd.Request; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.xml.bind.JAXBElement; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service public class KGDServiceImpl implements KGDService { private static final Logger logger = LoggerFactory.getLogger(KGDServiceImpl.class); private final KGDDao kgdDao; private final KGDSOAPClient kgdsoapClient; public KGDServiceImpl(KGDDao kgdDao, KGDSOAPClient kgdsoapClient) { this.kgdDao = kgdDao; this.kgdsoapClient = kgdsoapClient; } @Override public void testRequestKgd() { try { ResponseMessage response = kgdsoapClient.testResponseMessage(); } catch (Exception e) { e.printStackTrace(); } } @Override @Transactional public void ctrRequest(LocalDate reportDate, Long id, boolean isUpdate) { List<Map<String, Object>> entities = kgdDao.entityRows(reportDate); if (!isUpdate) { if (entities.size() > 0) { logger.info("Started request"); Request ctrRequest = kgdsoapClient.ctrRequest(getCtrList(entities)); logger.info("end of Started request"); ctrRequest.setEntitiesCount(Long.valueOf(entities.size())); ctrRequest.setReportDate(reportDate); kgdDao.insertRequest(ctrRequest); logger.info("inserted request"); } } else { Request ctrRequest = kgdsoapClient.ctrRequest(getCtrList(entities)); ctrRequest.setEntitiesCount(Long.valueOf(entities.size())); ctrRequest.setId(id); ctrRequest.setReportDate(reportDate); kgdDao.updateRequest(ctrRequest); } } @Override public List<Request> getCtrRequestList(LocalDate reportDate) { return kgdDao.getCtrRequestList(reportDate); } private static Entities getCtrList(List<Map<String, Object>> rows) { ObjectFactory objectFactory = new ObjectFactory(); Entities entities = new Entities(); List<CtrTransaction> ctrTransactionList = new ArrayList<>(); for (Map<String, Object> row : rows) { CtrTransaction ctrTransaction = new CtrTransaction(); ctrTransaction.setCurrTransDate(objectFactory.createCtrTransactionCurrTransDate(SqlJdbcConverter.convertToString(SqlJdbcConverter.convertToLocalDate(row.get("CURR_TRANS_DATE"))))); ctrTransaction.setReference(SqlJdbcConverter.convertObjectToString(row.get("REFERENCE"))); ctrTransaction.setContSum(objectFactory.createCtrTransactionContSum(SqlJdbcConverter.convertToDouble(row.get("CONT_SUM")))); ctrTransaction.setContNum(objectFactory.createCtrTransactionContNum(SqlJdbcConverter.convertObjectToString(row.get("CONT_NUM")))); ctrTransaction.setContDate(objectFactory.createCtrTransactionContDate(SqlJdbcConverter.convertToString(SqlJdbcConverter.convertToLocalDate(row.get("CONT_DATE"))))); ctrTransaction.setContRegNum(objectFactory.createCtrTransactionContRegNum(SqlJdbcConverter.convertObjectToString(row.get("CONT_REG_NUM")))); CtrSubject beneficiary = new CtrSubject(); RefCountry refCountry = new RefCountry(); refCountry.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2(SqlJdbcConverter.convertObjectToString(row.get("BENEFICIARY_COUNTRY_CODE")))); RefResidency refResidency = new RefResidency(); if (SqlJdbcConverter.convertObjectToString(row.get("BENEFICIARY_RESIDENCY_CODE")) != null) { refResidency.setCode(SqlJdbcConverter.convertObjectToString(row.get("BENEFICIARY_RESIDENCY_CODE"))); beneficiary.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidency)); } RefEconSector refEconSector = new RefEconSector(); if (SqlJdbcConverter.convertObjectToString(row.get("BENEFICIARY_ECON_SECTOR_CODE")) != null) { refEconSector.setCode(SqlJdbcConverter.convertObjectToString(row.get("BENEFICIARY_ECON_SECTOR_CODE"))); beneficiary.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSector)); } beneficiary.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountry)); beneficiary.setName(SqlJdbcConverter.convertObjectToString(row.get("BENEFICIARY_NAME"))); beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin(SqlJdbcConverter.convertObjectToString(row.get("BENEFICIARY_BINIIN")))); //beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("BENEFICIARY_BINIIN")))); ctrTransaction.setBeneficiary(objectFactory.createCtrTransactionBeneficiary(beneficiary)); CtrSubject sender = new CtrSubject(); RefCountry refCountryS = new RefCountry(); refCountryS.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2(SqlJdbcConverter.convertObjectToString(row.get("SENDER_COUNTRY_CODE")))); RefResidency refResidencyS = new RefResidency(); refResidencyS.setCode(SqlJdbcConverter.convertObjectToString(row.get("SENDER_RESIDENCY_CODE"))); RefEconSector refEconSectorS = new RefEconSector(); refEconSectorS.setCode(SqlJdbcConverter.convertObjectToString(row.get("SENDER_ECON_SECTOR_CODE"))); sender.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountryS)); sender.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidencyS)); sender.setName(SqlJdbcConverter.convertObjectToString(row.get("SENDER_NAME"))); sender.setBinIin(objectFactory.createCtrSubjectBinIin(SqlJdbcConverter.convertObjectToString(row.get("SENDER_BINIIN")))); //sender.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("SENDER_BINIIN")))); sender.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSectorS)); ctrTransaction.setSender(objectFactory.createCtrTransactionSender(sender)); RefCurrTransPpc refCurrTransPpc = new RefCurrTransPpc(); refCurrTransPpc.setCode(SqlJdbcConverter.convertObjectToString(row.get("CURR_TRANS_PPC_CODE"))); ctrTransaction.setRefCurrTransPpc(objectFactory.createCtrTransactionRefCurrTransPpc(refCurrTransPpc)); RefCurrency refCurrency = new RefCurrency(); refCurrency.setCode(objectFactory.createRefCurrencyCode(SqlJdbcConverter.convertObjectToString(row.get("CURRENCY_CODE")))); refCurrency.setShortName(objectFactory.createRefCurrencyShortName(SqlJdbcConverter.convertObjectToString(row.get("CURRENCY_NAME")))); ctrTransaction.setRefCurrency(objectFactory.createCtrTransactionRefCurrency(refCurrency)); ctrTransactionList.add(ctrTransaction); } entities.getCtrTransaction().addAll(ctrTransactionList); return entities; } } <file_sep>package kz.bsbnb.usci.eav.model.meta.json; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; /** * Класс для вывода ENTITY в json формате * @author <NAME> */ public class EntityExtJsTreeJson { private String text; private String title; private String name; private Object value; private Object newValue = null; private boolean key; private boolean leaf = false; private boolean simple = false; private boolean array = false; private boolean root = false; private boolean dictionary = false; private boolean cumulative = false; private Long classId = 0L; private String metaType; private String iconCls; private Long refClassId; private String refType; private String typeCode; private Integer totalCount; private LocalDate openDate; private LocalDate closeDate; private boolean required = false; private List<EntityExtJsTreeJson> children = new ArrayList<>(); public EntityExtJsTreeJson() { super(); } public String getText() { return text; } public EntityExtJsTreeJson setText(String text) { this.text = text; return this; } public String getTitle() { return title; } public EntityExtJsTreeJson setTitle(String title) { this.title = title; return this; } public String getName() { return name; } public EntityExtJsTreeJson setName(String name) { this.name = name; return this; } public Object getValue() { return value; } public EntityExtJsTreeJson setValue(Object value) { this.value = value; return this; } public Object getNewValue() { return newValue; } public EntityExtJsTreeJson setNewValue(Object newValue) { this.newValue = newValue; return this; } public boolean isKey() { return key; } public EntityExtJsTreeJson setKey(boolean key) { this.key = key; return this; } public boolean isLeaf() { return leaf; } public EntityExtJsTreeJson setLeaf(boolean leaf) { this.leaf = leaf; return this; } public boolean isSimple() { return simple; } public EntityExtJsTreeJson setSimple(boolean simple) { this.simple = simple; return this; } public boolean isArray() { return array; } public EntityExtJsTreeJson setArray(boolean array) { this.array = array; return this; } public boolean isDictionary() { return dictionary; } public EntityExtJsTreeJson setDictionary(boolean dictionary) { this.dictionary = dictionary; return this; } public boolean isCumulative() { return cumulative; } public EntityExtJsTreeJson setCumulative(boolean cumulative) { this.cumulative = cumulative; return this; } public boolean isRoot() { return root; } public EntityExtJsTreeJson setRoot(boolean root) { this.root = root; return this; } public String getMetaType() { return metaType; } public EntityExtJsTreeJson setMetaType(String metaType) { this.metaType = metaType; return this; } public Long getClassId() { return classId; } public EntityExtJsTreeJson setClassId(Long classId) { this.classId = classId; return this; } public String getIconCls() { return iconCls; } public EntityExtJsTreeJson setIconCls(String iconCls) { this.iconCls = iconCls; return this; } public Long getRefClassId() { return refClassId; } public EntityExtJsTreeJson setRefClassId(Long refClassId) { this.refClassId = refClassId; return this; } public String getRefType() { return refType; } public EntityExtJsTreeJson setRefType(String refType) { this.refType = refType; return this; } public String getTypeCode() { return typeCode; } public EntityExtJsTreeJson setTypeCode(String typeCode) { this.typeCode = typeCode; return this; } public List<EntityExtJsTreeJson> getChildren() { return children; } public EntityExtJsTreeJson setChildren(List<EntityExtJsTreeJson> children) { this.children = children; return this; } public EntityExtJsTreeJson addChild(EntityExtJsTreeJson child) { children.add(child); return this; } public Integer getTotalCount() { return totalCount; } public EntityExtJsTreeJson setTotalCount(Integer totalCount) { this.totalCount = totalCount; return this; } public LocalDate getOpenDate() { return openDate; } public EntityExtJsTreeJson setOpenDate(LocalDate openDate) { this.openDate = openDate; return this; } public LocalDate getCloseDate() { return closeDate; } public EntityExtJsTreeJson setCloseDate(LocalDate closeDate) { this.closeDate = closeDate; return this; } public boolean isRequired() { return required; } public EntityExtJsTreeJson setRequired(boolean required) { this.required = required; return this; } } <file_sep>package kz.bsbnb.usci.util.client; import kz.bsbnb.usci.model.util.Text; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @FeignClient(name = "utils") public interface TextClient { @GetMapping(value = "/text/getTextListByType") List<Text> getTextListByType(@RequestParam(name = "types") List<String> types); @GetMapping(value = "/text/getTextById") Text getTextById(@RequestParam(name = "id") Long id); } <file_sep>package kz.bsbnb.usci.portlet.entity.editor; import com.liferay.portal.util.PortalUtil; import com.liferay.util.bridges.mvc.MVCPortlet; import javax.portlet.PortletException; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class EntityEditorPortlet extends MVCPortlet { @Override public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest( PortalUtil.getHttpServletRequest(renderRequest)); String reqEntityId = httpReq.getParameter("entityId"); if (reqEntityId != null && reqEntityId.length() > 0) { Long queryEntityId = Long.parseLong(reqEntityId); String queryRepDate = httpReq.getParameter("repDate"); Long queryRespondentId = Long.parseLong(httpReq.getParameter("respondentId")); Long queryMetaClassId = Long.parseLong(httpReq.getParameter("metaClassId")); renderRequest.setAttribute("queryEntityId", queryEntityId); renderRequest.setAttribute("queryRepDate", queryRepDate); renderRequest.setAttribute("queryRespondentId", queryRespondentId); renderRequest.setAttribute("queryMetaClassId", queryMetaClassId); } super.doView(renderRequest, renderResponse); } } <file_sep>var label_ERROR = 'Қате'; var label_APPROVAL = 'Өзгерістерді мақұлдау'; var label_ORGS = 'Ұйым'; var label_SELECT_ALL = 'Барлығын көрсету'; var label_REP_DATE = 'Есепті күн'; var label_DOWN_Q = 'Тізімді жүктеу'; var label_ORG_NAME = 'Ұйымның атауы'; var label_FILE_NAME = 'Файлдың атауы'; var label_REC_DATE = 'Алу күні'; var label_BEG_DATE = 'Өңдеуді бастау күні'; var label_END_DATE = 'Аяқталу күні'; var label_STATUS = 'Статус'; var label_DATE_REP = 'Есеп беру күні'; var label_SEND = 'Жөнелту'; var label_CONFIRMED = 'Мақұлданды'; var label_CANCAL = 'Қабылдамау'; var label_CANCELED = 'Қабылданбады'; <file_sep>package kz.bsbnb.usci.portlet.maintenance_approval; import com.liferay.util.bridges.mvc.MVCPortlet; public class MaintenanceApprovalPortlet extends MVCPortlet { } <file_sep>package kz.bsbnb.usci.report.model.json; import java.io.Serializable; import java.util.List; public class ParameterWrapper implements Serializable { private List<InputParametersJson> parameters; public List<InputParametersJson> getParameters() { return parameters; } public void setParameters(List<InputParametersJson> parameters) { this.parameters = parameters; } } <file_sep>package kz.bsbnb.usci.util; import java.util.HashSet; import java.util.Set; /** * @author <NAME> */ public class SetUtils { public static <T> Set<T> difference(Set<T> setA, Set<T> setB) { Set<T> tmp = new HashSet<T>(); for (T key : setA) { if (!setB.contains(key)) { tmp.add(key); } } return tmp; } public static <T> Set<T> intersection(Set<T> setA, Set<T> setB) { Set<T> tmp = new HashSet<T>(); for (T x : setA) if (setB.contains(x)) tmp.add(x); return tmp; } } <file_sep>package kz.bsbnb.usci.model.adm; import kz.bsbnb.usci.model.persistence.Persistable; /** * @author <NAME> * Справочник должностей */ public class Position extends Persistable { private String nameRu; private String nameKz; private String shortNameRu; private String shortNameKz; private Long level; @Override public Position setId(Long id) { this.id = id; return this; } public String getNameRu() { return nameRu; } public Position setNameRu(String nameRu) { this.nameRu = nameRu; return this; } public String getNameKz() { return nameKz; } public Position setNameKz(String nameKz) { this.nameKz = nameKz; return this; } public Long getLevel() { return level; } public Position setLevel(Long level) { this.level = level; return this; } public String getShortNameRu() { return shortNameRu; } public Position setShortNameRu(String shortNameRu) { this.shortNameRu = shortNameRu; return this; } public String getShortNameKz() { return shortNameKz; } public Position setShortNameKz(String shortNameKz) { this.shortNameKz = shortNameKz; return this; } } <file_sep>/** * @author <NAME> * @author <NAME> */ Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.button.*' ]); function showMcWindow(metaClassId) { var metaClass = null; if (metaClassId) { var loadMask = new Ext.LoadMask(Ext.getBody(), { msg: LABEL_LOADING }); loadMask.show(); Ext.Ajax.request({ url: dataUrl + '/core/meta/getMetaClassData', method: 'GET', params: { metaClassId: metaClassId }, success: function(response) { loadMask.hide(); metaClass = JSON.parse(response.responseText); if (metaClass.uiConfig !== null ) { metaClass.uiConfig = metaClass.uiConfig.displayField; } createMcWindow(metaClass).show(); } }); } else { metaClass = { id: null, name: "", title: "", uiConfig: "", hashSize: 0, dictionary: false, operational: false, deleted: false }; createMcWindow(metaClass).show(); } } function createMcWindow(metaClass) { Ext.define('constantModel', { extend: 'Ext.data.Model', fields: ['id', 'nameRu', 'nameKz'] }); var buttonSave = Ext.create('Ext.button.Button', { id: "buttonSave", text: LABEL_SAVE, handler : function() { var form = Ext.getCmp('formMetaClass').getForm(); if (form.isValid()) { var formValues = form.getValues(); var uiConfig = { displayField: formValues.uiConfig } // формирую обьект мета класс для отправки в бэк var metaClassData = { id: metaClass.id, name: formValues.name, title: formValues.title, uiConfig: uiConfig, hashSize: formValues.hashSize, periodTypeId: formValues.periodTypeId, dictionary: formValues.dictionary, operational: formValues.operational, deleted: formValues.deleted }; var loadMask = new Ext.LoadMask(Ext.getBody(), { msg: label_SAVING }); loadMask.show(); Ext.Ajax.request({ url: dataUrl + '/core/meta/saveMetaClass', method: 'POST', waitMsg: label_SAVING, jsonData: metaClassData, reader: { type: 'json', root: 'data' }, success: function(response, opts) { loadMask.hide(); Ext.getCmp('windowMetaClass').destroy(); var metaClassGrid = Ext.getCmp('metaClassGrid'); // перегружаем весь грид чтобы отобразить изменения metaClassGrid.getStore().load(); metaClassGrid.getView().refresh(); }, failure: function(response, opts) { loadMask.hide(); Ext.Msg.alert(label_ERROR, JSON.parse(response.responseText).errorMessage); } }); } else { Ext.Msg.alert(LABEL_ATTENTION, LABEL_ALL_FIELDS); } } }); var buttonClose = Ext.create('Ext.button.Button', { id: 'buttonClose', text: LABEL_CANCEL, handler : function() { Ext.getCmp('windowMetaClass').destroy(); } }); var hashSizeList = [ [0, label_2min], [4, label_10min], [32, label_50min], [128, label_50minmore] ]; var formMetaClass = Ext.create('Ext.form.Panel', { id: 'formMetaClass', region: 'center', width: 615, fieldDefaults: { msgTarget: 'side' }, defaults: { anchor: '100%' }, defaultType: 'textfield', bodyPadding: '5 5 0', items: [ { fieldLabel: LABEL_CODE + '*', name: 'name', value: metaClass.name, allowBlank: false, maskRe: /[_a-z]/, validator: function(v) { if (/^([_a-z])+$/.test(v)) { return true; } else { return 'Допускается ввод только строчных латинских букв и символа "_" !'; } }, readOnly: metaClass.id != null, blankText: LABEL_REQUIRED_FIELD, }, { fieldLabel: LABEL_TITLE + '*', name: 'title', value: '', required: true }, { fieldLabel: LABEL_UI_CONFIG + '*', name: 'uiConfig', value: '', required: true }, { fieldLabel: label_PERIODICY, id: 'comPeriodType', name: 'periodTypeId', xtype: 'combobox', allowBlank: false, editable : false, readOnly: metaClass.id != null, store: Ext.create('Ext.data.Store', { model: 'constantModel', pageSize: 100, proxy: { type: 'ajax', url: dataUrl + '/utils/text/getTextListByType', extraParams: { types: ['PERIOD_TYPE'] }, actionMethods: { read: 'GET' }, reader: { type: 'json', root: '' } }, listeners: { load: function(me, records, options) { // по умолчанию укажем на первую запись if (!metaClass.id && records.length > 0) Ext.getCmp('comPeriodType').setValue(records[0].get('id')); } }, autoLoad: true, remoteSort: true }), valueField: 'id', displayField: 'nameRu', queryMode: 'local' }, { fieldLabel: label_SIZE_TABLE, id: 'comHashSize', name: 'hashSize', xtype: 'combobox', editable: false, readOnly: metaClass.id != null, store: new Ext.data.SimpleStore({ id: 0, fields:['id', 'text'], data: hashSizeList }), valueField: 'id', displayField: 'text', queryMode: 'local' }, { xtype: 'checkboxfield', cls: 'checkBox', boxLabel: label_NOT_ACTIVE, name: 'deleted', inputValue: true }, { xtype: 'checkboxfield', cls: 'checkBox', boxLabel: LABEL_REFERENCE, name: 'dictionary', readOnly: metaClass.id != null, inputValue: true }, { xtype: 'checkboxfield', cls: 'checkBox', boxLabel: label_OPER, name: 'operational', readOnly: metaClass.id != null, inputValue: true }], buttons: [buttonSave, buttonClose] }); var form = Ext.getCmp('formMetaClass').getForm(); form.setValues(metaClass); var windowMetaClass = new Ext.Window({ id: "windowMetaClass", layout: 'fit', title: LABEL_META, modal: true, maximizable: true, items: [formMetaClass] }); return windowMetaClass; } <file_sep>package kz.bsbnb.usci.wsclient.test; import kz.bsbnb.usci.util.SqlJdbcConverter; import kz.bsbnb.usci.wsclient.client.KGDSOAPClient; import kz.bsbnb.usci.wsclient.jaxb.ctr.*; import kz.bsbnb.usci.wsclient.model.ctrkgd.Request; import kz.bsbnb.usci.wsclient.service.KGDService; import kz.bsbnb.usci.wsclient.service.NSIService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.junit4.SpringRunner; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class WsClientTest { @Autowired JdbcTemplate jdbcTemplate; @Autowired NSIService nsiService; @Autowired KGDService kgdService; @Autowired KGDSOAPClient kgdsoapClient; @Test public void test0() { LocalDate begDate = LocalDate.of(2019,8,2); LocalDate endDate = LocalDate.of(2019,8,10); nsiService.saveCurrencyRates(begDate,endDate); } @Test public void test2() { try { kgdService.testRequestKgd(); } catch (Exception e) { e.printStackTrace(); } } @Test public void test3() { LocalDate localDate = LocalDate.of(2019,5,2); kgdService.ctrRequest(localDate, 22L, false); } @Test public void test4() { LocalDate begDate = LocalDate.of(2019,1,1); LocalDate endDate = LocalDate.of(2020,12,31); nsiService.saveHolidayDates(begDate,endDate); } @Test public void test5() { LocalDate now = LocalDate.now(); System.out.println("ldtnow " + now.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()); //System.out.println("ldtnow Localdate "+ Instant.ofEpochMilli().atZone(ZoneId.systemDefault()).toLocalDate()); System.out.println("ldt " + LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); System.out.println("ldt Localdatetime" + LocalDateTime.ofInstant(Instant.ofEpochMilli(now.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()),ZoneId.systemDefault())); System.out.println("ctm " + System.currentTimeMillis()); } @Test public void testOneCtr() { ObjectFactory objectFactory = new ObjectFactory(); Entities entities = new Entities(); List<CtrTransaction> ctrTransactionList = new ArrayList<>(); CtrTransaction ctrTransaction = new CtrTransaction(); ctrTransaction.setCurrTransDate(objectFactory.createCtrTransactionCurrTransDate("20.08.2019")); ctrTransaction.setReference("9074590152201092019"); ctrTransaction.setContSum(objectFactory.createCtrTransactionContSum(SqlJdbcConverter.convertToDouble(new BigDecimal(83)))); ctrTransaction.setContNum(objectFactory.createCtrTransactionContNum("100")); ctrTransaction.setContDate(objectFactory.createCtrTransactionContDate("27.06.2019")); ctrTransaction.setContRegNum(objectFactory.createCtrTransactionContRegNum("1/459/2010/8760")); CtrSubject beneficiary = new CtrSubject(); RefCountry refCountry = new RefCountry(); refCountry.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("DE")); RefResidency refResidency = new RefResidency(); refResidency.setCode("2"); beneficiary.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidency)); RefEconSector refEconSector = new RefEconSector(); refEconSector.setCode("7"); beneficiary.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSector)); beneficiary.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountry)); beneficiary.setName("DFH"); beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin("")); //beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("BENEFICIARY_BINIIN")))); ctrTransaction.setBeneficiary(objectFactory.createCtrTransactionBeneficiary(beneficiary)); CtrSubject sender = new CtrSubject(); RefCountry refCountryS = new RefCountry(); refCountryS.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("KZ")); RefResidency refResidencyS = new RefResidency(); refResidencyS.setCode("1"); RefEconSector refEconSectorS = new RefEconSector(); refEconSectorS.setCode("7"); sender.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountryS)); sender.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidencyS)); sender.setName("ABC"); sender.setBinIin(objectFactory.createCtrSubjectBinIin("970740001482")); //sender.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("SENDER_BINIIN")))); sender.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSectorS)); ctrTransaction.setSender(objectFactory.createCtrTransactionSender(sender)); RefCurrTransPpc refCurrTransPpc = new RefCurrTransPpc(); refCurrTransPpc.setCode("710"); ctrTransaction.setRefCurrTransPpc(objectFactory.createCtrTransactionRefCurrTransPpc(refCurrTransPpc)); RefCurrency refCurrency = new RefCurrency(); refCurrency.setCode(objectFactory.createRefCurrencyCode("EUR")); refCurrency.setShortName(objectFactory.createRefCurrencyShortName("EUR")); ctrTransaction.setRefCurrency(objectFactory.createCtrTransactionRefCurrency(refCurrency)); ctrTransactionList.add(ctrTransaction); entities.getCtrTransaction().addAll(ctrTransactionList); try { Request response = kgdsoapClient.ctrRequest(entities); } catch (Exception e) { e.printStackTrace(); } } @Test public void testLess50000() { ObjectFactory objectFactory = new ObjectFactory(); Entities entities = new Entities(); List<CtrTransaction> ctrTransactionList = new ArrayList<>(); CtrTransaction ctrTransaction = new CtrTransaction(); ctrTransaction.setCurrTransDate(objectFactory.createCtrTransactionCurrTransDate("20.07.2019")); ctrTransaction.setReference("9074590152201082019"); ctrTransaction.setContSum(objectFactory.createCtrTransactionContSum(SqlJdbcConverter.convertToDouble(new BigDecimal(5)))); ctrTransaction.setContNum(objectFactory.createCtrTransactionContNum("100")); ctrTransaction.setContDate(objectFactory.createCtrTransactionContDate("27.06.2019")); ctrTransaction.setContRegNum(objectFactory.createCtrTransactionContRegNum("1/459/2010/8760")); CtrSubject beneficiary = new CtrSubject(); RefCountry refCountry = new RefCountry(); refCountry.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("DE")); RefResidency refResidency = new RefResidency(); refResidency.setCode("2"); beneficiary.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidency)); RefEconSector refEconSector = new RefEconSector(); refEconSector.setCode("7"); beneficiary.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSector)); beneficiary.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountry)); beneficiary.setName("DFH"); beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin("")); //beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("BENEFICIARY_BINIIN")))); ctrTransaction.setBeneficiary(objectFactory.createCtrTransactionBeneficiary(beneficiary)); CtrSubject sender = new CtrSubject(); RefCountry refCountryS = new RefCountry(); refCountryS.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("KZ")); RefResidency refResidencyS = new RefResidency(); refResidencyS.setCode("1"); RefEconSector refEconSectorS = new RefEconSector(); refEconSectorS.setCode("7"); sender.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountryS)); sender.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidencyS)); sender.setName("ABC"); sender.setBinIin(objectFactory.createCtrSubjectBinIin("970740001482")); //sender.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("SENDER_BINIIN")))); sender.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSectorS)); ctrTransaction.setSender(objectFactory.createCtrTransactionSender(sender)); RefCurrTransPpc refCurrTransPpc = new RefCurrTransPpc(); refCurrTransPpc.setCode("710"); ctrTransaction.setRefCurrTransPpc(objectFactory.createCtrTransactionRefCurrTransPpc(refCurrTransPpc)); RefCurrency refCurrency = new RefCurrency(); refCurrency.setCode(objectFactory.createRefCurrencyCode("EUR")); refCurrency.setShortName(objectFactory.createRefCurrencyShortName("EUR")); ctrTransaction.setRefCurrency(objectFactory.createCtrTransactionRefCurrency(refCurrency)); ctrTransactionList.add(ctrTransaction); entities.getCtrTransaction().addAll(ctrTransactionList); try { Request response = kgdsoapClient.ctrRequest(entities); } catch (Exception e) { e.printStackTrace(); } } @Test public void testInvalidXSD() { ObjectFactory objectFactory = new ObjectFactory(); Entities entities = new Entities(); List<CtrTransaction> ctrTransactionList = new ArrayList<>(); CtrTransaction ctrTransaction = new CtrTransaction(); ctrTransaction.setCurrTransDate(objectFactory.createCtrTransactionCurrTransDate("20.07.2019")); ctrTransaction.setContSum(objectFactory.createCtrTransactionContSum(SqlJdbcConverter.convertToDouble(new BigDecimal(73)))); ctrTransaction.setContNum(objectFactory.createCtrTransactionContNum("100")); ctrTransaction.setContDate(objectFactory.createCtrTransactionContDate("27.06.2019")); ctrTransaction.setContRegNum(objectFactory.createCtrTransactionContRegNum("1/459/2010/8760")); CtrSubject beneficiary = new CtrSubject(); RefCountry refCountry = new RefCountry(); refCountry.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("DE")); RefResidency refResidency = new RefResidency(); refResidency.setCode("2"); beneficiary.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidency)); RefEconSector refEconSector = new RefEconSector(); refEconSector.setCode("7"); beneficiary.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSector)); beneficiary.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountry)); beneficiary.setName("DFH"); beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin("")); //beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("BENEFICIARY_BINIIN")))); ctrTransaction.setBeneficiary(objectFactory.createCtrTransactionBeneficiary(beneficiary)); CtrSubject sender = new CtrSubject(); RefCountry refCountryS = new RefCountry(); refCountryS.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("KZ")); RefResidency refResidencyS = new RefResidency(); refResidencyS.setCode("1"); RefEconSector refEconSectorS = new RefEconSector(); refEconSectorS.setCode("7"); sender.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountryS)); sender.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidencyS)); sender.setName("ABC"); sender.setBinIin(objectFactory.createCtrSubjectBinIin("970740001482")); //sender.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("SENDER_BINIIN")))); sender.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSectorS)); ctrTransaction.setSender(objectFactory.createCtrTransactionSender(sender)); RefCurrTransPpc refCurrTransPpc = new RefCurrTransPpc(); refCurrTransPpc.setCode("710"); ctrTransaction.setRefCurrTransPpc(objectFactory.createCtrTransactionRefCurrTransPpc(refCurrTransPpc)); RefCurrency refCurrency = new RefCurrency(); refCurrency.setCode(objectFactory.createRefCurrencyCode("EUR")); refCurrency.setShortName(objectFactory.createRefCurrencyShortName("EUR")); ctrTransaction.setRefCurrency(objectFactory.createCtrTransactionRefCurrency(refCurrency)); ctrTransactionList.add(ctrTransaction); entities.getCtrTransaction().addAll(ctrTransactionList); try { Request response = kgdsoapClient.ctrRequest(entities); } catch (Exception e) { e.printStackTrace(); } } @Test public void testManyCtrRequests() { ObjectFactory objectFactory = new ObjectFactory(); for (int i=1;i<100000;i++) { Entities entities = new Entities(); List<CtrTransaction> ctrTransactionList = new ArrayList<>(); CtrTransaction ctrTransaction = new CtrTransaction(); ctrTransaction.setCurrTransDate(objectFactory.createCtrTransactionCurrTransDate("20.07.2019")); ctrTransaction.setReference("9074590152201082019"); ctrTransaction.setContSum(objectFactory.createCtrTransactionContSum(SqlJdbcConverter.convertToDouble(new BigDecimal(73)))); ctrTransaction.setContNum(objectFactory.createCtrTransactionContNum("100")); ctrTransaction.setContDate(objectFactory.createCtrTransactionContDate("27.06.2019")); ctrTransaction.setContRegNum(objectFactory.createCtrTransactionContRegNum("1/459/2010/8760")); CtrSubject beneficiary = new CtrSubject(); RefCountry refCountry = new RefCountry(); refCountry.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("DE")); RefResidency refResidency = new RefResidency(); refResidency.setCode("2"); beneficiary.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidency)); RefEconSector refEconSector = new RefEconSector(); refEconSector.setCode("7"); beneficiary.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSector)); beneficiary.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountry)); beneficiary.setName("DFH"); beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin("")); //beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("BENEFICIARY_BINIIN")))); ctrTransaction.setBeneficiary(objectFactory.createCtrTransactionBeneficiary(beneficiary)); CtrSubject sender = new CtrSubject(); RefCountry refCountryS = new RefCountry(); refCountryS.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("KZ")); RefResidency refResidencyS = new RefResidency(); refResidencyS.setCode("1"); RefEconSector refEconSectorS = new RefEconSector(); refEconSectorS.setCode("7"); sender.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountryS)); sender.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidencyS)); sender.setName("ABC"); sender.setBinIin(objectFactory.createCtrSubjectBinIin("970740001482")); //sender.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("SENDER_BINIIN")))); sender.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSectorS)); ctrTransaction.setSender(objectFactory.createCtrTransactionSender(sender)); RefCurrTransPpc refCurrTransPpc = new RefCurrTransPpc(); refCurrTransPpc.setCode("710"); ctrTransaction.setRefCurrTransPpc(objectFactory.createCtrTransactionRefCurrTransPpc(refCurrTransPpc)); RefCurrency refCurrency = new RefCurrency(); refCurrency.setCode(objectFactory.createRefCurrencyCode("EUR")); refCurrency.setShortName(objectFactory.createRefCurrencyShortName("EUR")); ctrTransaction.setRefCurrency(objectFactory.createCtrTransactionRefCurrency(refCurrency)); ctrTransactionList.add(ctrTransaction); entities.getCtrTransaction().addAll(ctrTransactionList); try { Request response = kgdsoapClient.ctrRequest(entities); } catch (Exception e) { e.printStackTrace(); } } } @Test public void testRequestManyCtr() { ObjectFactory objectFactory = new ObjectFactory(); Entities entities = new Entities(); List<CtrTransaction> ctrTransactionList = new ArrayList<>(); for (int i=1;i<100000;i++) { CtrTransaction ctrTransaction = new CtrTransaction(); ctrTransaction.setCurrTransDate(objectFactory.createCtrTransactionCurrTransDate("20.07.2019")); ctrTransaction.setReference("9074590152201082019"); ctrTransaction.setContSum(objectFactory.createCtrTransactionContSum(SqlJdbcConverter.convertToDouble(new BigDecimal(73)))); ctrTransaction.setContNum(objectFactory.createCtrTransactionContNum("100")); ctrTransaction.setContDate(objectFactory.createCtrTransactionContDate("27.06.2019")); ctrTransaction.setContRegNum(objectFactory.createCtrTransactionContRegNum("1/459/2010/8760")); CtrSubject beneficiary = new CtrSubject(); RefCountry refCountry = new RefCountry(); refCountry.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("DE")); RefResidency refResidency = new RefResidency(); refResidency.setCode("2"); beneficiary.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidency)); RefEconSector refEconSector = new RefEconSector(); refEconSector.setCode("7"); beneficiary.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSector)); beneficiary.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountry)); beneficiary.setName("DFH"); beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin("")); //beneficiary.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("BENEFICIARY_BINIIN")))); ctrTransaction.setBeneficiary(objectFactory.createCtrTransactionBeneficiary(beneficiary)); CtrSubject sender = new CtrSubject(); RefCountry refCountryS = new RefCountry(); refCountryS.setCodeAlpha2(objectFactory.createRefCountryCodeAlpha2("KZ")); RefResidency refResidencyS = new RefResidency(); refResidencyS.setCode("1"); RefEconSector refEconSectorS = new RefEconSector(); refEconSectorS.setCode("7"); sender.setRefCountry(objectFactory.createCtrSubjectRefCountry(refCountryS)); sender.setRefResidency(objectFactory.createCtrSubjectRefResidency(refResidencyS)); sender.setName("ABC"); sender.setBinIin(objectFactory.createCtrSubjectBinIin("970740001482")); //sender.setBinIin(objectFactory.createCtrSubjectBinIin(String.valueOf(row.get("SENDER_BINIIN")))); sender.setRefEconSector(objectFactory.createCtrSubjectRefEconSector(refEconSectorS)); ctrTransaction.setSender(objectFactory.createCtrTransactionSender(sender)); RefCurrTransPpc refCurrTransPpc = new RefCurrTransPpc(); refCurrTransPpc.setCode("710"); ctrTransaction.setRefCurrTransPpc(objectFactory.createCtrTransactionRefCurrTransPpc(refCurrTransPpc)); RefCurrency refCurrency = new RefCurrency(); refCurrency.setCode(objectFactory.createRefCurrencyCode("EUR")); refCurrency.setShortName(objectFactory.createRefCurrencyShortName("EUR")); ctrTransaction.setRefCurrency(objectFactory.createCtrTransactionRefCurrency(refCurrency)); ctrTransactionList.add(ctrTransaction); } entities.getCtrTransaction().addAll(ctrTransactionList); try { Request response = kgdsoapClient.ctrRequest(entities); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/** * @author <NAME> * @author <NAME> * @author <NAME> */ var fetchSize = 50; var timeout = 300000; // данная переменная нужна чтобы зафиксировать изменения // запрещаем отправку XML если нет никаких изменений var editorAction = { lastAction: 'none', hasUnsavedAction: function() { return this.lastAction != 'none'; }, commitEdit: function() { this.lastAction = 'edit'; var lblOperation = Ext.getCmp('lblOperation'); if (lblOperation) lblOperation.setText(label_NON_SAVED); } } var isMaintenance = false;<file_sep>package kz.bsbnb.usci.receiver.model; import kz.bsbnb.usci.model.util.TextJson; /** * @author <NAME> */ public class BatchStatusJson { private Long batchId; private Long entityId; private Long metaClassId; private Long statusId; private TextJson status; private String textCode; private TextJson operation; private String textRu; private String textKz; private String comments; private String entityText; public BatchStatusJson() { super(); } public BatchStatusJson(Long batchId) { this.batchId = batchId; } public Long getBatchId() { return batchId; } public BatchStatusJson setBatchId(Long batchId) { this.batchId = batchId; return this; } public Long getEntityId() { return entityId; } public BatchStatusJson setEntityId(Long entityId) { this.entityId = entityId; return this; } public Long getMetaClassId() { return metaClassId; } public BatchStatusJson setMetaClassId(Long metaClassId) { this.metaClassId = metaClassId; return this; } public String getTextCode() { return textCode; } public BatchStatusJson setTextCode(String textCode) { this.textCode = textCode; return this; } public String getTextRu() { return textRu; } public BatchStatusJson setTextRu(String textRu) { this.textRu = textRu; return this; } public TextJson getOperation() { return operation; } public void setOperation(TextJson operation) { this.operation = operation; } public String getTextKz() { return textKz; } public BatchStatusJson setTextKz(String textKz) { this.textKz = textKz; return this; } public String getComments() { return comments; } public BatchStatusJson setComments(String comments) { this.comments = comments; return this; } public TextJson getStatus() { return status; } public BatchStatusJson setStatus(TextJson status) { this.status = status; return this; } public String getEntityText() { return entityText; } public BatchStatusJson setEntityText(String entityText) { this.entityText = entityText; return this; } public Long getStatusId() { return statusId; } public BatchStatusJson setStatusId(Long statusId) { this.statusId = statusId; return this; } } <file_sep>package kz.bsbnb.usci.wsclient.model.currency; import java.time.LocalDate; public class CurrencyEntityCustom { private Long CurrId; private String CurrCode; private LocalDate CourseDate; private Long CourseKind; private Double Course; private Long Corellation; private Long WdKind; public Long getCurrId() { return CurrId; } public void setCurrId(Long currId) { CurrId = currId; } public String getCurrCode() { return CurrCode; } public void setCurrCode(String currCode) { CurrCode = currCode; } public LocalDate getCourseDate() { return CourseDate; } public void setCourseDate(LocalDate courseDate) { CourseDate = courseDate; } public Long getCourseKind() { return CourseKind; } public void setCourseKind(Long courseKind) { CourseKind = courseKind; } public Double getCourse() { return Course; } public void setCourse(Double course) { Course = course; } public Long getCorellation() { return Corellation; } public void setCorellation(Long corellation) { Corellation = corellation; } public Long getWdKind() { return WdKind; } public void setWdKind(Long wdKind) { WdKind = wdKind; } } <file_sep>package kz.bsbnb.usci.util.repository.impl; import kz.bsbnb.usci.model.util.Text; import kz.bsbnb.usci.util.dao.TextDao; import kz.bsbnb.usci.util.repository.TextRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Repository; import java.util.HashMap; import java.util.List; @Repository public class TextRepositoryImpl implements TextRepository, InitializingBean { private final static Logger logger = LoggerFactory.getLogger(TextRepositoryImpl.class); private HashMap<String, Text> cache = new HashMap<>(); private final TextDao textDao; public TextRepositoryImpl(TextDao textDao) { this.textDao = textDao; } @Override public void afterPropertiesSet() { List<Text> textList = textDao.getAll(); for (Text text : textList) cache.put(text.getType() + ":" + text.getCode(), text); } @Override public Text getConfig(String type, String code) { String key = type + ":" + code; Text text = cache.get(key); if (text == null) { text = textDao.get(type, code); cache.put(key, text); } return text; } @Override public Text getConfig(Long id) { return textDao.get(id); } } <file_sep>apply plugin: 'java' apply plugin: 'war' group = 'kz.bsbnb.usci.portlet' version = '0.2.0' description = "USCI Portlet: Administration" sourceCompatibility = 1.7 targetCompatibility = 1.7 repositories { mavenCentral() } war { baseName = 'admin' version = '2.3.0' enabled = true } bootWar { enabled = false } dependencies { compile project(':model') compile project(':util:util-api') compile group: 'com.liferay.portal', name: 'portal-service', version:'6.1.1' compile group: 'com.liferay.portal', name: 'util-bridges', version:'6.1.1' compile group: 'com.liferay.portal', name: 'util-taglib', version:'6.1.1' compile group: 'com.liferay.portal', name: 'util-java', version:'6.1.1' compile group: 'javax.portlet', name: 'portlet-api', version:'2.0' compile group: 'javax.servlet', name: 'servlet-api', version:'2.4' compile group: 'javax.servlet.jsp', name: 'jsp-api', version:'2.0' }<file_sep>package kz.bsbnb.usci.core.dao; import kz.bsbnb.usci.core.service.RespondentServiceImpl; import kz.bsbnb.usci.eav.meta.dao.ProductDaoImpl; import kz.bsbnb.usci.eav.model.base.BaseEntity; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.eav.repository.MetaClassRepository; import kz.bsbnb.usci.eav.service.BaseEntityLoadService; import kz.bsbnb.usci.model.Constants; import kz.bsbnb.usci.model.adm.User; import kz.bsbnb.usci.model.batch.Product; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.model.respondent.Respondent; import kz.bsbnb.usci.util.SetUtils; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.math.BigInteger; import java.sql.Timestamp; import java.util.*; /** * @author <NAME> * @author <NAME> * @author <NAME> */ @Repository public class UserDaoImpl implements UserDao { private static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class); private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate npJdbcTemplate; private final MetaClassRepository metaClassRepository; private final BaseEntityLoadService baseEntityLoadService; private final SimpleJdbcInsert respondentUserInsert; private final SimpleJdbcInsert userProductInsert; @Autowired public UserDaoImpl(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate, MetaClassRepository metaClassRepository, BaseEntityLoadService baseEntityLoadService) { this.jdbcTemplate = jdbcTemplate; this.npJdbcTemplate = npJdbcTemplate; this.metaClassRepository = metaClassRepository; this.baseEntityLoadService = baseEntityLoadService; this.respondentUserInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_ADM") .withTableName("CREDITOR_USER") .usingColumns("USER_ID", "CREDITOR_ID") .usingGeneratedKeyColumns("ID"); this.userProductInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_ADM") .withTableName("USER_PRODUCT") .usingColumns("USER_ID", "PRODUCT_ID") .usingGeneratedKeyColumns("ID"); } @Override public List<User> getUserList() { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from USCI_ADM.USERS"); List<User> users = new ArrayList<>(); for (Map<String, Object> row : rows) users.add(getUserFromJdbcMap(row, false)); return users; } @Override public List<User> getRespondentUserList(long respondentId) { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select u.*\n" + "from USCI_ADM.CREDITOR_USER cu,\n" + " USCI_ADM.USERS u\n" + "where cu.CREDITOR_ID = ?\n" + " and cu.USER_ID = u.USER_ID", respondentId); List<User> users = new ArrayList<>(); for (Map<String, Object> row : rows) users.add(getUserFromJdbcMap(row, false)); return users; } @Override public List<Respondent> getUserRespondentList(long userId) { MetaClass metaClass = metaClassRepository.getMetaClass("ref_respondent"); String query = "select CREDITOR_ID from USCI_ADM.CREDITOR_USER where USER_ID = :userId"; MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("userId", userId); List<Respondent> respondents = new ArrayList<>(); List<Long> rows = npJdbcTemplate.queryForList(query, params, Long.class); if (rows.size() < 1) return Collections.emptyList(); for (Long respondentId : rows) { BaseEntity beRespondent = baseEntityLoadService.loadBaseEntity(new BaseEntity(respondentId, metaClass, Constants.NBK_AS_RESPONDENT_ID)); Respondent respondent = RespondentServiceImpl.getRespondentFromEntity(beRespondent); respondents.add(respondent); } return respondents; } @Override public void addUserRespondent(Long userId, List<Long> respondentIds) { List<MapSqlParameterSource> params = new ArrayList<>(); for (Long respondentId : respondentIds) { params.add(new MapSqlParameterSource("USER_ID", userId) .addValue("CREDITOR_ID", respondentId)); } if (respondentIds.size() > 1) { int counts[] = respondentUserInsert.executeBatch(params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException("Ошибка insert записей в таблицу USCI_ADM.CREDITOR_USER"); } else { int count = respondentUserInsert.execute(params.get(0)); if (count != 1) throw new UsciException("Ошибка insert записей в таблицу USCI_ADM.CREDITOR_USER"); } } @Override public void deleteUserRespondent(Long userId, List<Long> respondentIds) { List<MapSqlParameterSource> params = new ArrayList<>(); for (Long respondentId : respondentIds) { params.add(new MapSqlParameterSource("USER_ID", userId) .addValue("RESPONDENT_ID", respondentId)); } String delete = "delete from USCI_ADM.CREDITOR_USER\n" + " where USER_ID = :USER_ID\n" + " and CREDITOR_ID = :RESPONDENT_ID"; if (respondentIds.size() > 1) { int counts[] = npJdbcTemplate.batchUpdate(delete, params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException("Ошибка delete записей из таблицы USCI_ADM.CREDITOR_USER"); } else { int count = npJdbcTemplate.update(delete, params.get(0)); if (count != 1) throw new UsciException("Ошибка delete записей из таблицы USCI_ADM.CREDITOR_USER"); } } @Override public void addUserProduct(Long userId, List<Long> productIds) { List<MapSqlParameterSource> params = new ArrayList<>(); for (Long productId : productIds) { params.add(new MapSqlParameterSource("USER_ID", userId) .addValue("PRODUCT_ID", productId)); } if (productIds.size() > 1) { int counts[] = userProductInsert.executeBatch(params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException("Ошибка insert записей в таблицу USCI_ADM.USER_PRODUCT"); } else { int count = userProductInsert.execute(params.get(0)); if (count != 1) throw new UsciException("Ошибка insert записей в таблицу USCI_ADM.USER_PRODUCT"); } } @Override public void deleteUserProduct(Long userId, List<Long> productIds) { List<MapSqlParameterSource> params = new ArrayList<>(); for (Long productId : productIds) { params.add(new MapSqlParameterSource("USER_ID", userId) .addValue("PRODUCT_ID", productId)); } String delete = "delete from USCI_ADM.USER_PRODUCT\n" + " where USER_ID = :USER_ID\n" + " and PRODUCT_ID = :PRODUCT_ID"; if (productIds.size() > 1) { int counts[] = npJdbcTemplate.batchUpdate(delete, params.toArray(new SqlParameterSource[0])); if (Arrays.stream(counts).anyMatch(value -> value != 1)) throw new UsciException("Ошибка delete записей из таблицы USCI_ADM.USER_PRODUCT"); } else { int count = npJdbcTemplate.update(delete, params.get(0)); if (count != 1) throw new UsciException("Ошибка delete записей из таблицы USCI_ADM.USER_PRODUCT"); } } @Override public List<Product> getUserProductList(long userId) { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select p.*\n" + " from USCI_ADM.USER_PRODUCT up, \n" + " EAV_CORE.EAV_M_PRODUCT p\n" + " where up.USER_ID = ?\n" + " and up.PRODUCT_ID = p.ID", userId); return ProductDaoImpl.getProductFromJdbcMap(rows); } //TODO: отрефакторить @Override public void synchronize(List<User> users) { HashMap<Long, User> usersFromDB = new HashMap<>(); HashMap<Long, User> usersFromPortal = new HashMap<>(); String querySelect = "select ID, USER_ID, FIRST_NAME, LAST_NAME, MIDDLE_NAME, SCREEN_NAME, EMAIL, MODIFIED_DATE, IS_ACTIVE from USCI_ADM.USERS"; List<Map<String, Object>> rows = jdbcTemplate.queryForList(querySelect); for (Map<String, Object> row : rows) { User user = getUserFromJdbcMap(row, false); usersFromDB.put(user.getUserId(), user); } for (User user : users) { usersFromPortal.put(user.getUserId(), user); } //TODO:временно убрал //Set<Long> toDelete = SetUtils.difference(usersFromDB.keySet(), usersFromPortal.keySet()); Set<Long> toAdd = SetUtils.difference(usersFromPortal.keySet(), usersFromDB.keySet()); Set<Long> toUpdate = SetUtils.intersection(usersFromPortal.keySet(), usersFromDB.keySet()); //TODO:временно убрал /*for (Long id : toDelete) { MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("userId", id); String queryDelete = "delete from USCI_ADM.CREDITOR_USER\n" + " where USER_ID = :userId"; int count = npJdbcTemplate.update(queryDelete, params); if (count > 1 ) throw new UsciException("Ошибка delete записей из таблицы USCI_ADM.CREDITOR_USER"); queryDelete = "delete from USCI_ADM.USERS\n" + " where USER_ID = :userId"; count = npJdbcTemplate.update(queryDelete, params); if (count != 1) throw new UsciException("Ошибка delete записей из таблицы USCI_ADM.USERS"); }*/ for (Long id : toAdd) { User user = usersFromPortal.get(id); SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_ADM") .withTableName("USERS") .usingGeneratedKeyColumns("ID") .usingColumns("USER_ID","FIRST_NAME","LAST_NAME","MIDDLE_NAME","SCREEN_NAME","EMAIL","MODIFIED_DATE");; int count = simpleJdbcInsert.execute(new MapSqlParameterSource() .addValue("USER_ID", user.getUserId()) .addValue("FIRST_NAME", user.getFirstName()) .addValue("LAST_NAME", user.getLastName()) .addValue("MIDDLE_NAME", user.getMiddleName()) .addValue("SCREEN_NAME", user.getScreenName()) .addValue("EMAIL", user.getEmailAddress()) .addValue("MODIFIED_DATE", SqlJdbcConverter.convertToSqlDate(user.getModifiedDate()))); if (count != 1) throw new UsciException("Ошибка insert записей в таблицу USCI_ADM.USERS"); } for (Long id : toUpdate) { User user = usersFromPortal.get(id); User dbUser = usersFromDB.get(id); if (!user.getFirstName().equals(dbUser.getFirstName()) || !user.getLastName().equals(dbUser.getLastName()) || !user.getMiddleName().equals(dbUser.getMiddleName()) || !user.getScreenName().equals(dbUser.getScreenName()) || !user.getEmailAddress().equals(dbUser.getEmailAddress()) || !user.isActive().equals(dbUser.isActive()) ) { int count = npJdbcTemplate.update("UPDATE USCI_ADM.USERS\n" + " SET USER_ID = :userId ,\n" + " FIRST_NAME = :firstName ,\n" + " LAST_NAME = :lastName ,\n" + " MIDDLE_NAME = :middleName ,\n" + " SCREEN_NAME = :screenName ,\n" + " EMAIL = :emailAddress ,\n" + " MODIFIED_DATE = :modifiedDate ,\n" + " IS_ACTIVE = :isActive\n" + " WHERE USER_ID = :id ", new MapSqlParameterSource("id", id) .addValue("userId", user.getUserId()) .addValue("firstName", user.getFirstName()) .addValue("lastName", user.getLastName()) .addValue("middleName", user.getMiddleName()) .addValue("screenName", user.getScreenName()) .addValue("emailAddress", user.getEmailAddress()) .addValue("modifiedDate", SqlJdbcConverter.convertToSqlDate(user.getModifiedDate())) .addValue("isActive", SqlJdbcConverter.convertToByte(user.isActive()))); if (count != 1) throw new RuntimeException("Ошибка update записи в таблице USCI_ADM.USERS"); } } } //TODO: отрефакторить @Override public void addMailTemplatesToNewUser(List<User> users) { String select = "select USER_ID from USCI_ADM.USERS"; List<Long> rows = jdbcTemplate.queryForList(select, Long.class); Set<Long> dbUsers = new HashSet<>(); Set<Long> liferayUsers = new HashSet<>(); for (Long userId : rows) { dbUsers.add(userId); } for (User user : users) { liferayUsers.add(user.getUserId()); } Set<Long> toAdd = SetUtils.difference(liferayUsers, dbUsers); if(toAdd.size() < 1) return; Set<Long> userConfigurableTemplates = new HashSet<>(); String templateSelect = "select ID from USCI_MAIL.MAIL_TEMPLATE where CONFIG_TYPE_ID = 137"; List<Long> templateRows = jdbcTemplate.queryForList(templateSelect, Long.class); for (Long templateId : templateRows) { userConfigurableTemplates.add(templateId); } for (Long userId : toAdd) { for (Long templateId : userConfigurableTemplates) { SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_MAIL") .withTableName("MAIL_USER_MAIL_TEMPLATE") .usingGeneratedKeyColumns("ID"); int count = simpleJdbcInsert.execute(new MapSqlParameterSource() .addValue("PORTAL_USER_ID", userId) .addValue("MAIL_TEMPLATE_ID", templateId) .addValue("ENABLED", 0L)); if (count != 1) throw new UsciException("Ошибка insert записей в таблицу USCI_MAIL.MAIL_USER_MAIL_TEMPLATE"); } } } @Override public User getUser(long userId) { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from USCI_ADM.USERS where USER_ID = ?", userId); if (rows == null || rows.isEmpty()) return null; Map<String, Object> row = rows.get(0); return getUserFromJdbcMap(row, true); } @Override public List<User> getNationalBankUsers(long respondentId) { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select *\n" + " from USCI_ADM.USERS u\n" + " where EMAIL like '%nationalbank.kz'\n" + " and exists (select cu.USER_ID\n" + " from USCI_ADM.CREDITOR_USER cu\n" + " where cu.USER_ID = u.USER_ID\n" + " and cu.CREDITOR_ID = ?)", new Object[]{respondentId}); List<User> users = new ArrayList<>(); for (Map<String, Object> row : rows) users.add(getUserFromJdbcMap(row, false)); return users; } public Optional<Set<Long>> getUserProductPositionIds(Long userId, Long productId) { try { return Optional.of(new HashSet<>(jdbcTemplate.queryForList("select POS_ID\n" + " from USCI_ADM.USER_PROD_POS\n" + "where USER_ID = ?\n" + " and PRODUCT_ID = ?", new Object[]{userId, productId}, Long.class))); } catch (EmptyResultDataAccessException e) { return Optional.empty(); } } private User getUserFromJdbcMap(Map<String, Object> row, boolean fillRespondents) { User user = new User(); user.setId(BigInteger.valueOf(SqlJdbcConverter.convertToLong(row.get("ID")))); user.setUserId(SqlJdbcConverter.convertToLong(row.get("USER_ID"))); user.setScreenName(SqlJdbcConverter.convertObjectToString(row.get("SCREEN_NAME"))); user.setEmailAddress(SqlJdbcConverter.convertObjectToString(row.get("EMAIL"))); user.setFirstName(SqlJdbcConverter.convertObjectToString(row.get("FIRST_NAME"))); user.setLastName(SqlJdbcConverter.convertObjectToString(row.get("LAST_NAME"))); user.setMiddleName(SqlJdbcConverter.convertObjectToString(row.get("MIDDLE_NAME"))); user.setModifiedDate(SqlJdbcConverter.convertToLocalDate((Timestamp) row.get("MODIFIED_DATE"))); user.setActive(SqlJdbcConverter.convertToBoolean(row.get("IS_ACTIVE"))); if (fillRespondents) user.setRespondents(getUserRespondentList(user.getUserId())); return user; } } <file_sep>var label_ERROR = 'Қате'; var label_REP_DATE = 'Есепті күн'; var label_DOWN_PRO = 'Профилді жүктеу'; var label_SPISOK = 'Профилдер тізімі'; var label_PROTECTED = 'Профил паролмен қорғалған'; var label_PASSWORD = '<PASSWORD>'; var label_GET_SERT = 'Сертификаттарды профилден алу '; var label_GET_ERROR = 'Сертификаттардың тізімін алу мүмкін болмады'; var label_SERTIFICATE = 'Сертификат'; var label_SIGN = 'Қол қою'; var label_PRESS = 'Басыңыз'; var label_CHOOSE_P = 'Профилді таңдаңыз'; var label_CHOOSE_S = 'Сертификатты таңдаңыз'; var label_WAIT = 'Күте тұрыңыз'; var label_INFO = 'Ақпарат'; var label_REP_CONFIRMED = 'Есеп расталды'; var label_CONFIRM = 'Растау'; var label_SHOW = 'Келісімді көрсету'; var label_UNKNOWN = 'Белгісіз'; var label_NO_DATA = 'Бейнелеуге арналған деректер жоқ'; var label_MESSAGES = 'Хабарлама'; var label_SENDLER = 'Жөнелтуші'; var label_TEXT = 'Хабарлама мәтіні'; var label_NO_MESSAGE = 'Хабарламасыз'; var label_DATE_TIME = 'Жөнелту күні/уақыты'; var label_ATTACH_FILES = 'Қоса берілген файлдар'; var label_NO_ATTACH = 'Қоса берілген файлдар жоқ'; var label_FILE_NAME = 'Файлдың атауы '; var label_DOWNLOAD = 'Жүктеу '; var label_HISTORY = 'Растау тарихы '; var label_USER = 'Пайдаланушы '; var label_POSITION = ''; var label_STATUS = 'Статус'; var label_D_T = 'Күн/уақыт'; var label_DOWNLOAD_CON = 'Келісімді жүктеу'; var label_RESP = 'Респонденттер'; var label_RESP_NAME = 'Респондент атауы'; var label_PRODUCT = 'Өнім'; var label_FIRST_DATE = 'Ақпаратты бірінші қабылдау күні'; var label_LAST_DATE = 'Ақпаратты соңғы қабылдау күні'; var label_VIEW = 'Көрсету'; var label_CONF = 'Бекіту'; var label_BACK = 'Тізімге қайта оралу'; var label_ADD_MESS = 'Хабарламаны салу'; var label_FILL = 'Хабарламаның мәтінін толтырыңыз'; var label_SENDED_MESS = 'Хабарлама жөнелтілді'; var label_NEW_MESS = 'Жаңа хабарлама'; var label_ATTACHES = 'Қоса берілген файлдар'; var label_NO_FILES = 'Файлдар жоқ'; var label_ATTACHING = 'Файлды қоса беру'; var label_DETAILS = 'Деректемелер'; var label_RESPONDENT = 'Респондент:'; var label_CROSSCHECK = 'Аралық бақылаудың нәтижесі'; var label_R = 'Даму банкі'; var label_VU = 'Екінші деңгейдегі банк'; var label_PU = 'Бірінші деңгейдегі банк'; var label_IO = 'Ипотекалық ұйым'; var label_OTHER = 'Банктік операциялардың жеке түрлерін жүзеге асырушы басқада ұйымдар '; var label_SELECT_ALL = 'Барлығын таңдау'; var label_OFF_SELECTED = 'Бөліп көрсетілгенді алып тастау'; var label_ALL = 'Барлығын бөліп көрсету'; var label_CONFIRMATION = 'Растау'; <file_sep>package kz.bsbnb.usci.receiver.model; import kz.bsbnb.usci.model.persistence.Persistable; import java.time.LocalDate; import java.time.LocalDateTime; /** * @author <NAME> */ public class BatchEntry extends Persistable { /** * XML файл */ private String value; /** * Отчетная дата; заполняется пользователем на фронте */ private LocalDate repDate; /** * Дата создания сущности */ private LocalDateTime updateDate; /** * Идентификатор пользователя который создал запись */ private Long userId; /** * Идентфикатор сущности; инициализируется на фронте скриптом */ private Long entityId; /** * Идентфикатор мета класса; инициализируется на фронте скриптом */ private Long metaClassId; /** * Признак батча когда меняется ключевое поле */ private boolean isMaintenance = false; /** * Признак обработки батча */ private Boolean isProcessed = false; /** * Признак удаления батча */ private boolean isDeleted = false; public BatchEntry() { super(); } public BatchEntry(Long id) { super(id); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public LocalDate getRepDate() { return repDate; } public void setRepDate(LocalDate repDate) { this.repDate = repDate; } public LocalDateTime getUpdateDate() { return updateDate; } public void setUpdateDate(LocalDateTime updateDate) { this.updateDate = updateDate; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getEntityId() { return entityId; } public void setEntityId(Long entityId) { this.entityId = entityId; } public Boolean getProcessed() { return isProcessed; } public void setProcessed(Boolean processed) { isProcessed = processed; } public boolean isMaintenance() { return isMaintenance; } public void setMaintenance(boolean maintenance) { this.isMaintenance = maintenance; } public Long getMetaClassId() { return metaClassId; } public void setMetaClassId(Long metaClassId) { this.metaClassId = metaClassId; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean deleted) { isDeleted = deleted; } } <file_sep>group = 'kz.bsbnb.usci.util' version = '0.1.0' dependencies { compile project(':model') compile project(':util:util-core') compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.boot:spring-boot-starter-jdbc') compile('org.springframework.boot:spring-boot-starter-web') compile("org.springframework.boot:spring-boot-starter-actuator") } bootJar { baseName = 'usci-utils-boot' version = '0.1.0' } springBoot { mainClassName = 'kz.bsbnb.usci.util.UtilApplication' }<file_sep>Ext.require([ 'Ext.tab.*', 'Ext.tree.*', 'Ext.data.*', 'Ext.tip.*' ]); Ext.Ajax.timeout= 3000000; Ext.override(Ext.data.proxy.Ajax, { timeout: Ext.Ajax.timeout }); Ext.override(Ext.data.proxy.Server, { timeout: Ext.Ajax.timeout }); Ext.override(Ext.data.Connection, { timeout: Ext.Ajax.timeout }); Ext.onReady(function(){ Ext.define('creditorListModel',{ extend: 'Ext.data.Model', fields: ['id', 'name', 'shortName', 'code', 'shutdownDate', 'changeDate', 'bin', 'rnn', 'bik', 'mainOffice', 'branches', 'subjectType'] }); Ext.define('crossCheckStoreModel',{ extend: 'Ext.data.Model', fields: ['id', 'dateBegin', 'dateEnd', 'creditorId', 'reportDate', 'status', 'statusName', 'username', 'creditorName'] }); Ext.define('crossCheckMessageModel',{ extend: 'Ext.data.Model', fields: ['description', 'help', 'difference', 'outerValue', 'innerValue', 'isError', 'nonCritical' ] }); var productStore = Ext.create('Ext.data.Store', { fields: ['id', 'code', 'name'], proxy: { type: 'ajax', extraParams: { userId: userId }, url: dataUrl + '/core/user/getUserProductJsonList', reader: { type: 'json', root: 'data', totalProperty: 'total' } }, autoLoad: true, listeners: { load: function(me, records, options) { var productId = records[0].get('id'); Ext.getCmp('edProduct').setValue(productId); } } }); var bvuFilter = new Ext.util.Filter({ filterFn: function(item) { var obj = item.get('subjectType'); return obj.id != '1' ? true : false; } }); var bpuFilter = new Ext.util.Filter({ filterFn: function(item) { var obj = item.get('subjectType'); return obj.id != null ? true : false; } }); var elseorgFilter = new Ext.util.Filter({ filterFn: function(item) { var obj = item.get('subjectType'); return obj.id != '3' ? true : false; } }); var ipotechFilter = new Ext.util.Filter({ filterFn: function(item) { var obj = item.get('subjectType'); return obj.id != '2' ? true : false; } }); Ext.Date.patterns={ CustomFormat: "d.m.Y" }; var creditorStore = Ext.create('Ext.data.Store', { id: 'creditorStore', model: 'creditorListModel', autoLoad: false, proxy: { type: 'ajax', url: dataUrl+'/core/respondent/getUserRespondentList', actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }, sorters: [{ property: 'name', direction: 'asc' }] }); var creditorListGrid = Ext.create('Ext.grid.Panel', { store: creditorStore, id: 'creditorListGrid', multiSelect: true, autoScroll: true, scroll: 'vertical', columns: [{ text: label_CRED, dataIndex: 'name', width: 200, heigt: 200, flex: 1 }], viewConfig: { emptyText: 'Нет данных для отображения' } }); function executeCrossCheck(){ var buttonExecute = Ext.create('Ext.button.Button', { text: 'Запустить', handler: function() { var productId = Ext.getCmp('edProduct').getValue(); var checkedItem = Ext.getCmp('radioClauses').getValue(); var creditorIds= []; if (isNb) { for (var i = 0; i < creditorListGrid.store.getCount(); i++) { if (creditorListGrid.getSelectionModel().isSelected(i)) { creditorIds.push(creditorListGrid.store.getAt(i).data.id); } } } else { creditorIds.push(creditorListGrid.store.getAt(0).data.id); } var loadMask = new Ext.LoadMask(Ext.getBody(), { msg: label_PROCCESING }); loadMask.show(); Ext.Ajax.request({ url: dataUrl + '/report/crosscheck/executeCrossCheckAll', timeout: 3000000, params : { userId: userId, creditorIds: creditorIds, productId: productId, executeClause: checkedItem.radiog, reportDate: Ext.Date.format(Ext.getCmp('reportDate').value, Ext.Date.patterns.CustomFormat) }, method: 'POST', success: function(response) { loadMask.hide(); Ext.getCmp('windowExecute').destroy(); viewCrossCheckPanel(); crossCheckListGrid = Ext.getCmp('crossCheckListGrid'); if (crossCheckListGrid.store.data.length > 0) { crossCheckListGrid.getSelectionModel().select(0); loadCrossCheckMessage(); } }, failure: function(response) { loadMask.hide(); var error = JSON.parse(response.responseText); Ext.Msg.show({ title: 'Ошибка', msg: error.message, width : 300, buttons: Ext.MessageBox.YES }); } }); } }); var buttonClose = Ext.create('Ext.button.Button', { text: 'Отмена', handler : function() { Ext.getCmp('windowExecute').destroy(); } }); var formExecute = Ext.create('Ext.form.Panel', { id: 'formExecute', width: 400, height: 100, fieldDefaults: { msgTarget: 'side' }, defaults: { anchor: '100%' }, bodyPadding: '5 5 0', items: [ { xtype: 'radiogroup', fieldLabel: 'Условия запуска', id: 'radioClauses', columns: 2, vertical: true, items: [{ xtype: 'radio', boxLabel: 'Полная проверка', cls: 'radioButton', name: 'radiog' , checked: true , inputValue: 'FULL' } , { xtype: 'radio', boxLabel: 'Частичная проверка', cls: 'radioButton', name: 'radiog', inputValue:'SIMPLE' }] }], buttons: [buttonExecute, buttonClose] }); var windowProduct = new Ext.Window({ id: 'windowExecute', layout: 'fit', title: 'Запуск', modal: true, maximizable: true, items: [formExecute] }); windowProduct.show(); } function viewCrossCheckPanel() { var creditorIds= []; if (isNb) { for (var i = 0; i < creditorListGrid.store.getCount(); i++) { if (creditorListGrid.getSelectionModel().isSelected(i)) { creditorIds.push(creditorListGrid.store.getAt(i).data.id); } } } else { creditorIds.push(creditorListGrid.store.getAt(0).data.id); } var crossCheckStore = Ext.create('Ext.data.Store', { id: 'crossCheckStore', model: 'crossCheckStoreModel', autoLoad: true, proxy: { type: 'ajax', url : dataUrl + '/report/crosscheck/getCrossCheck', jsonData: true, extraParams: { creditorIds: creditorIds, reportDate: Ext.Date.format(Ext.getCmp('reportDate').value, Ext.Date.patterns.CustomFormat), productId: Ext.getCmp('edProduct').getValue() }, actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } } }); var crossCheckListGrid = Ext.create('Ext.grid.Panel', { store: crossCheckStore, id:'crossCheckListGrid', dockedItems: [ { xtype: 'toolbar', dock: 'top', items: [ { xtype: 'button', region: 'west', text: label_EXCEL, handler: function() { var crossCheckListGrid = Ext.getCmp('crossCheckListGrid'); var crossCheckId = crossCheckListGrid.getSelectionModel().getLastSelected().data.id; var xhr = new XMLHttpRequest(); xhr.open("POST", dataUrl + "/report/crosscheck/exportToExcel?crossCheckId= "+ crossCheckId); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.responseType = "arraybuffer"; xhr.onload = function (oEvent) { var responseArray = new Uint8Array(this.response); // извлекаю наименование файла из заголовков var fileName = label_CROSSCHECK; // var disposition = xhr.getResponseHeader('Content-Disposition'); // if (disposition && disposition.indexOf('attachment') !== -1) { // var fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; // var matches = fileNameRegex.exec(disposition); // if (matches != null && matches[1]) { // fileName = matches[1].replace(/['"]/g, ''); // } // } var blob = new Blob([responseArray], {type: "application/vnd.ms-excel"}); saveAs(blob, fileName + ".xls"); }; xhr.send(); } } ] } ], columns:[ { text: label_ORG_NAME, dataIndex: 'creditorName', width: 100, heigt: 200, flex: 1 }, { xtype: 'datecolumn', text: label_BEG_DATE, dataIndex: 'dateBegin', width: 100, heigt: 200, flex: 1, format: 'd.m.Y H:i:s' }, { xtype: 'datecolumn', text: label_END_DATE, dataIndex: 'dateEnd', width: 100, heigt: 200, flex: 1, format: 'd.m.Y H:i:s' }, { text: label_STATUS, dataIndex: 'statusName', width: 100, heigt: 200, flex: 1 }, { text: label_USER, dataIndex: 'username', width: 100, heigt: 200, flex: 1 } ], listeners: { selectionchange: function () { loadCrossCheckMessage() } } }); crossCheckPanel = Ext.getCmp('crossCheckPanel'); crossCheckPanel.add(crossCheckListGrid); Ext.getCmp('crossCheckPanel').show(); } function loadCrossCheckMessage() { var crossCheckListGrid = Ext.getCmp('crossCheckListGrid'); var crossCheckId = crossCheckListGrid.getSelectionModel().getLastSelected().data.id; console.log(crossCheckId); var crossCheckMessageStore = Ext.create('Ext.data.Store', { id: 'crossCheckMessageStore', model: 'crossCheckMessageModel', autoLoad: true, proxy: { type: 'ajax', url : dataUrl + '/report/crosscheck/getCrossCheckMessages', extraParams: { crossCheckId: crossCheckId }, actionMethods: { read: 'GET' }, reader: { type: 'json', root: 'data', totalProperty: 'total' } }}); crossCheckMessageListGrid = Ext.create('Ext.grid.Panel', { store: crossCheckMessageStore, columns:[ { text: label_PARAMETR, dataIndex: 'description', flex: 1 }, { text: label_VALUE_KR, dataIndex: 'innerValue', flex: 1 }, { text: label_OUT_VALUE, dataIndex: 'outerValue', flex: 1 }, { text: label_DIFF, dataIndex: 'difference', flex: 1 }] }); crossCheckMessagePanel = Ext.getCmp('crossCheckMessagePanel'); crossCheckMessagePanel.removeAll(); crossCheckMessagePanel.add(crossCheckMessageListGrid); Ext.getCmp('crossCheckMessagePanel').show(); } Ext.create('Ext.panel.Panel', { renderTo: 'crosscheck-content', width: 1200, height: 900, scroll: 'both', layout: { type: 'vbox', align: 'stretch' }, items: [{ xtype: 'panel', title: label_ORGS, id: 'orgsPanel', hidden: true, height:50, layout: { type: 'hbox' }, items:[ { xtype: 'checkbox', boxLabel: label_VU, id:'cbBankSecondLev', checked: true, cls: 'checkBox', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp("creditorListGrid"); if (newValue == '1') { grid.store.removeFilter(bvuFilter); } else if (newValue == '0') { grid.store.addFilter(bvuFilter); } } } }, { xtype: 'checkbox', boxLabel: label_PU, id:'cbBankFirstLev', checked:'true', cls: 'checkBox', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp("creditorListGrid"); if (newValue == '1') { grid.store.removeFilter(bpuFilter); } else if (newValue == '0') { grid.store.addFilter(bpuFilter); } } } }, { xtype: 'checkbox', boxLabel: label_IO, id:'cbIpotekaOrg', cls: 'checkBox', checked:'true', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp("creditorListGrid"); if (newValue == '1') { grid.store.removeFilter(elseorgFilter); } else if (newValue == '0') { grid.store.addFilter(elseorgFilter); } } } }, { xtype: 'checkbox', boxLabel: label_OTHER, id:'cbOtherOrg', checked:'true', cls: 'checkBox', listeners: { change: function (field, newValue, oldValue, options) { grid = Ext.getCmp("creditorListGrid"); if (newValue == '1') { grid.store.removeFilter(ipotechFilter); } else if (newValue == '0') { grid.store.addFilter(ipotechFilter); } } } }, { xtype: 'button', text: label_SELECT_ALL, id:'btnChooseAll', heigt: 30, handler: function() { Ext.getCmp('cbBankSecondLev').setValue(true); Ext.getCmp('cbBankFirstLev').setValue(true); Ext.getCmp('cbIpotekaOrg').setValue(true); Ext.getCmp('cbOtherOrg').setValue(true); } }, { xtype: 'button', text: label_OFF_SELECTED, id:'btnDeSelectAll', heigt: 30, handler: function() { Ext.getCmp('cbBankSecondLev').setValue(false); Ext.getCmp('cbBankFirstLev').setValue(false); Ext.getCmp('cbIpotekaOrg').setValue(false); Ext.getCmp('cbOtherOrg').setValue(false); } } ] }, { xtype: 'textfield', hidden: true, id: 'searchText', listeners: { change: function(field, newValue, oldValue, options) { grid = Ext.getCmp("creditorListGrid"); if(newValue==''){ grid.store.clearFilter(); if (Ext.getCmp('cbBankSecondLev').checked == false) { grid.store.addFilter(bvuFilter) }; if (Ext.getCmp('cbBankFirstLev').checked == false) { grid.store.addFilter(bpuFilter) }; if (Ext.getCmp('cbOtherOrg').checked == false) { grid.store.addFilter(elseorgFilter) }; if (Ext.getCmp('cbIpotekaOrg').checked == false) { grid.store.addFilter(ipotechFilter) }; grid.getView().refresh(); } else { grid.store.filter([ {property: "name", value: newValue, anyMatch: true, caseSensitive: false} ]); } } } }, // панель кредиторов { xtype: 'panel', id: 'respondentsPanel', hidden: true, title: '', height:200, layout: 'fit', items: [creditorListGrid] }, // панель управления { xtype: 'panel', title: '', height:75, items:[ { xtype: 'button', hidden: true, text: label_ALL, id:'btnChooseAllCreditor', heigt: 30, width : 200, handler: function(){ creditorListGrid.getSelectionModel().selectAll(); } },{ fieldLabel: 'Выберите продукт', id: 'edProduct', xtype: 'combobox', store: productStore, displayField: 'name', width : 300, labelWidth: 120, valueField: 'id', editable: false }, { xtype: 'datefield', id:'reportDate', anchor: '100%', width : 200, format: 'd.m.Y', name: 'from_date', maxValue: new Date() // limited to the current date or prior } ] }, { xtype: 'panel', title: '', height:25, layout: { type: 'hbox' }, items:[ { xtype: 'button', text: label_SHOW, id:'btnView', heigt: 30, handler: function() { viewCrossCheckPanel(); crossCheckListGrid = Ext.getCmp('crossCheckListGrid'); if (crossCheckListGrid.store.data.length > 0) { crossCheckListGrid.getSelectionModel().select(0); loadCrossCheckMessage(); } } }, { xtype: 'button', text: label_CROSSCHECK, id:'btnCrossCheck', heigt: 30, handler: function() { executeCrossCheck(); } } ] }, { xtype: 'panel', height: 200, id: 'crossCheckPanel', hidden: true, layout: 'fit', title: label_START }, { xtype: 'panel', height: 200, id: 'crossCheckMessagePanel', hidden: true, layout: 'fit', title: label_DATA } ], listeners: { afterrender: function () { creditorStore.load({ params: { userId: userId }, scope: this }); if (isNb) { Ext.getCmp("orgsPanel").show(); Ext.getCmp("searchText").show(); Ext.getCmp("respondentsPanel").show(); Ext.getCmp("btnChooseAllCreditor").show(); } } } }); });<file_sep>group = 'kz.bsbnb.usci.wsclient' version = '0.1.0' dependencies { compile project(':model') compile project(':wsclient:wsclient-api') compile project(':util:util-api') compile ("org.springframework.boot:spring-boot-starter-web") compile ("org.springframework.boot:spring-boot-starter-web-services") compile ("org.springframework.boot:spring-boot-starter-jdbc") compile("org.apache.httpcomponents:httpclient:4.5.3") compile("org.apache.cxf:cxf-spring-boot-starter-jaxws:3.2.1") compile("com.oracle:${ojdbcVersion}") } jar { baseName = 'usci-wsclient-core' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>package kz.bsbnb.usci.brms; import kz.bsbnb.usci.eav.repository.MetaClassRepository; import kz.bsbnb.usci.eav.service.BaseEntityLoadService; import kz.bsbnb.usci.eav.service.BaseEntityProcessor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component public class StaticContextInitializer { @Autowired private BaseEntityProcessor rulesProcessor; @Autowired private BaseEntityLoadService rulesLoad; @Autowired private MetaClassRepository rulesMeta; @PostConstruct public void init() { BRMSHelper.setRulesProcessor(rulesProcessor); BRMSHelper.setRulesLoad(rulesLoad); BRMSHelper.setRulesMeta(rulesMeta); } } <file_sep>var label_ERROR = 'Ошибка'; var label_APPROVAL = 'Одобрение изменений'; var label_ORGS = 'Организации'; var label_SELECT_ALL = 'Выделить все'; var label_REP_DATE = 'Отчетная дата'; var label_DOWN_Q = 'Загрузить очередь'; var label_ORG_NAME = 'Наименование организации'; var label_FILE_NAME = 'Имя файла'; var label_REC_DATE = 'Дата получения'; var label_BEG_DATE = 'Дата начала обработки'; var label_END_DATE = 'Дата завершения'; var label_STATUS = 'Статус'; var label_DATE_REP = 'Дата отчета'; var label_SEND = 'Отправить'; var label_CONFIRMED = 'Одобрено'; var label_CANCAL = 'Отклонить'; var label_CANCELED = 'Отклонено'; <file_sep>// get fields function buildsFiels(json){ var uniques=[]; for (i = 0; i < json.length; i++) { for(x in json[i]) { if (!uniques.includes(x)) { uniques.push(x) } } } return uniques; } // create column info function buildColumnsInfo(json) { var uniques=buildsFiels(json); var colsInfo=[]; if (uniques.length>0){ for(i=0; i<uniques.length; i++){ colsInfo.push({ text: uniques[i], dataIndex: uniques[i], flex: 0, editor: { allowBlank: false } }); } } return colsInfo; } // create model function createModel( listOfField){ var x = Ext.define('sqlModel', { extend: 'Ext.data.Model', fields: listOfField }); return x; } // create store function createStore(model, data) { var x = Ext.create('Ext.data.Store', { model: model }); x.add(data); return x; } // create grid function createGrid(model, lst_columns){ var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 }); var x = Ext.create('Ext.grid.Panel', { id: "sqlGrid", header: false, title: 'GRID', store: model, autoSizeColumn: true, columns: lst_columns, resizable: true, height: 400, columnLines: true, /*overflowY: 'auto', overflowX: 'auto',*/ scroll: 'both', selType: 'rowmodel', tbar: [ { xtype: 'button', cls: 'button-excel', title: 'dsfdsfadsfadsf', scale: 'large', height: 20, margin: '0 1 0 1', listeners: { click: function () { exportToEXL(); } } }] }); return x; } <file_sep>group = 'kz.bsbnb.usci.report' version = '0.1.0' dependencies { compile project(':model') compile('net.sf.jasperreports:jasperreports670'){ exclude group: 'com.itextpdf', module: 'itextpdf' } compile('org.springframework.cloud:spring-cloud-starter-openfeign') } jar { baseName = 'usci-report-api' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>package kz.bsbnb.usci.receiver.queue; import kz.bsbnb.usci.receiver.model.Batch; import java.util.List; public interface BatchQueueOrder { Batch getNextBatch(List<Batch> files); int compare(Batch batch1, Batch batch2); } <file_sep>buildscript { ext { droolsVersion = '7.6.0.Final' } } group = 'kz.bsbnb.usci.brms' version = '0.1.0' dependencies { compile project(':model') compile project(':util:util-api') compile project(':eav:eav-api') compile project(':brms:brms-api') compile ("org.drools:drools-core:${droolsVersion}") compile ("org.kie:kie-spring:${droolsVersion}") compile ("org.drools:drools-compiler:${droolsVersion}") runtime("com.oracle:${ojdbcVersion}") } jar { baseName = 'usci-brms-core' version = '0.1.0' enabled = true } bootJar { enabled = false }<file_sep>Ext.define('creditorListModel',{ extend: 'Ext.data.Model', fields: ['id', 'name', 'shortName', 'code', 'shutdownDate', 'changeDate', 'bin', 'rnn', 'bik', 'mainOffice', 'branches', 'subjectType'] }); Ext.define('loadModel',{ extend: 'Ext.data.Model', fields: ['id', 'report', 'portalUserId', 'startTime', 'finishTime', 'note', 'files'] }); Ext.define('reportListModel',{ extend: 'Ext.data.Model', fields: ['id', 'nameRu', 'nameKz', 'name', 'procedureName', 'type', 'orderNumber', 'inputParameters', 'exportTypesList'] }); Ext.define('reportModel',{ extend: 'Ext.data.Model', fields: ['id', 'user', 'respondent', 'product', 'tableName', 'reportDate', 'beginDate', 'endDate', 'status'] }); Ext.define('valueModel',{ extend: 'Ext.data.Model', fields: ['displayName', 'value'] }) <file_sep>package kz.bsbnb.usci.brms.dao; import kz.bsbnb.usci.brms.model.RulePackage; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.util.SqlJdbcConverter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author <NAME> */ @Component public class PackageDaoImpl implements PackageDao { private final JdbcTemplate jdbcTemplate; public PackageDaoImpl(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public RulePackage loadBatch(long id) { if (id < 1) throw new UsciException("Не имеет id. Не возможно загружать."); String query = "select * from USCI_RULE.PACKAGE_ WHERE ID = ?"; RulePackage batch = jdbcTemplate.queryForObject(query, new Object[]{id}, new BatchMapper()); return batch; } private class BatchMapper implements RowMapper<RulePackage> { @Override public RulePackage mapRow(ResultSet resultSet, int i) throws SQLException { RulePackage batch = new RulePackage(); batch.setId(resultSet.getLong("id")); batch.setName(resultSet.getString("name")); batch.setDescription(resultSet.getString("description")); return batch; } } @Override @Transactional public long savePackage(String rulePackageName) { SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate) .withSchemaName("USCI_RULE") .withTableName("PACKAGE_") .usingGeneratedKeyColumns("ID"); Number id = simpleJdbcInsert.executeAndReturnKey(new MapSqlParameterSource() .addValue("NAME", rulePackageName)); return id.longValue(); } @Override public List<RulePackage> getAllPackages() { String query = "select * from USCI_RULE.PACKAGE_"; List<Map<String, Object>> rows = jdbcTemplate.queryForList(query); List<RulePackage> rulePackageList = new ArrayList<>(); for (Map<String, Object> row : rows) { RulePackage rulePkg = new RulePackage(); rulePkg.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); rulePkg.setName((String) row.get("NAME")); rulePackageList.add(rulePkg); } return rulePackageList; } } <file_sep>package kz.bsbnb.usci.receiver.model; import kz.bsbnb.usci.model.persistence.Persistable; import java.time.LocalDateTime; /** * @author <NAME> */ public class BatchStatus extends Persistable { private static final long serialVersionUID = 1L; private Long batchId; private String text; private LocalDateTime receiptDate; private BatchStatusType status; private String exceptionTrace; public BatchStatus() { super(); } public BatchStatus(Long batchId, BatchStatusType status) { this.batchId = batchId; this.receiptDate = LocalDateTime.now(); this.status = status; } public Long getBatchId() { return batchId; } public BatchStatus setBatchId(Long batchId) { this.batchId = batchId; return this; } public String getText() { return text; } public BatchStatus setText(String text) { if (text != null) { if (text.getBytes(java.nio.charset.StandardCharsets.UTF_8).length < 512) { this.text = text; } else { this.text = text.substring(0, 256); } } else { this.text = null; } return this; } public String getExceptionTrace() { return exceptionTrace; } public BatchStatus setExceptionTrace(String exceptionTrace) { this.exceptionTrace = exceptionTrace; return this; } public LocalDateTime getReceiptDate() { return receiptDate; } public BatchStatus setReceiptDate(LocalDateTime receiptDate) { this.receiptDate = receiptDate; return this; } public BatchStatusType getStatus() { return status; } public BatchStatus setStatus(BatchStatusType status) { this.status = status; return this; } } <file_sep>package kz.bsbnb.usci.model.util; import kz.bsbnb.usci.model.persistence.Persistable; /** * @author <NAME> * */ public class Application extends Persistable { private String module; private String host; private Integer port; private String product; private Integer rmiPort; public Application() { super(); } public String getModule() { return module; } public void setModule(String module) { this.module = module; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public Integer getRmiPort() { return rmiPort; } public void setRmiPort(Integer rmiPort) { this.rmiPort = rmiPort; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } @Override public String toString() { return "Application{" + "module='" + module + '\'' + ", host='" + host + '\'' + ", port=" + port + ", product='" + product + '\'' + ", rmiPort=" + rmiPort + '}'; } } <file_sep>package kz.bsbnb.usci.eav.controller; import kz.bsbnb.usci.eav.model.meta.MetaClass; import kz.bsbnb.usci.eav.service.EntityExtJsService; import kz.bsbnb.usci.eav.service.MetaClassService; import kz.bsbnb.usci.util.json.ext.ExtJsJson; import org.springframework.core.io.InputStreamResource; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.ContentDisposition; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.ByteArrayInputStream; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; /** * @author <NAME> */ @RestController @RequestMapping(value = "/dict") public class DictionaryController { private final MetaClassService metaClassService; private final EntityExtJsService dictionaryService; public DictionaryController(MetaClassService metaClassService, EntityExtJsService dictionaryService) { this.metaClassService = metaClassService; this.dictionaryService = dictionaryService; } @GetMapping(value = "getDictEntities") public ExtJsJson getDictEntities(@RequestParam(name = "metaId") Long metaClassId, @RequestParam(name = "userId") Long userId, @RequestParam(name = "isNb") boolean isNb, @RequestParam(name = "reportDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate reportDate) { List<Map<String, Object>> list = dictionaryService.loadEntityEntries(metaClassService.getMetaClass(metaClassId), reportDate, userId, isNb); return new ExtJsJson(list); } @GetMapping(value = "exportDictionaryToMsExcel") public ResponseEntity<InputStreamResource> exportDictionaryToMsExcel(@RequestParam(name = "metaClassId") Long metaClassId, @RequestParam(name = "userId") Long userId, @RequestParam(name = "isNb") boolean isNb, @RequestParam(name = "date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) { MetaClass metaClass = metaClassService.getMetaClass(metaClassId); String fileName = metaClass.getClassName() + "_" + LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")) + ".xls"; InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(dictionaryService.exportDictionaryToMsExcel(metaClass, date, userId, isNb))); HttpHeaders header = createHeader(); header.setContentDisposition(ContentDisposition.builder("attachment").filename(fileName).build()); return ResponseEntity .ok() .headers(header) .contentType(MediaType.parseMediaType("application/vnd.ms-excel")) .body(resource); } private static HttpHeaders createHeader() { // Чтоб не кэшировалось HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); //без этих значений выходило: Refused to get unsafe header "Accept-Ranges" headers.add("Access-Control-Allow-Headers", "Range"); headers.add("Access-Control-Expose-Headers", "Accept-Ranges, Content-Encoding, Content-Length, Content-Range, Content-Disposition"); return headers; } } <file_sep>group 'kz.bsbnb.usci' version '0.1.0' bootJar { enabled = false }<file_sep>package kz.bsbnb.usci.util.json.ext; import java.util.List; public class ExtJsList { private int totalCount; private List<Object> data; private boolean success; public ExtJsList(List data) { this.data = data; this.totalCount = data.size(); this.success = true; } public ExtJsList(List data, int totalCount) { this.data = data; this.totalCount = totalCount; this.success = true; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public List<Object> getData() { return data; } public void setData(List<Object> data) { this.data = data; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } } <file_sep>package kz.bsbnb.usci.eav.model.meta; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public enum PeriodType { CONSTANT(200L), DAY(201L), WEEK(202L), MONTH(203L), QUARTER(206L), YEAR(204L); private long id; private static final Map<Long, PeriodType> map = new ConcurrentHashMap<>(); static { for (PeriodType periodType : PeriodType.values()) { map.put(periodType.getId(), periodType); } } PeriodType(long id) { this.id = id; } public long getId() { return id; } public static PeriodType getPeriodType(long value) { return map.get(value); } } <file_sep>var LABEL_SEND = 'Жіберу'; var LABEL_EDIT = 'Өңдеу'; var LABEL_DATE = 'Күні'; var LABEL_CODE = 'Коды'; var LABEL_TITLE = 'Атауы'; var LABEL_REFERENCE = 'Анықтамалық'; var LABEL_ITEMS = 'Элементтер'; var LABEL_ERROR = 'Қате'; var LABEL_ERROR_NO_DATA = 'Деректерді алу мүмкін емес'; var LABEL_VIEW = 'Шолу'; var LABEL_ERROR_NO_DATA_FOR = 'Деректерді алу мүмкін емес: {0}'; var LABEL_SAVE = 'Сақтау'; var LABEL_CANCEL = 'Болдырмау'; var LABEL_VALUE = 'Мағынасы'; var LABEL_ARRAY = 'Массив'; var LABEL_TYPE = 'Типі'; var LABEL_INPUT_FORM = "Форма ввода"; var LABEL_REF = 'Анықтамалық'; var LABEL_ENTITY_ID = 'Ұйым идентификаторы'; var LABEL_DEL = 'Жою'; var LABEL_ADD = 'Қосу'; var LABEL_ADDING = 'Алып тасталуда ...'; var LABEL_ERROR_ACC = "Қате пайда болды: {0}"; var LABEL_ERROR_ACC = "Қате пайда болды: {0}"; var LABEL_CHOOSE = 'Көру үшін класс таңдаңыз'; var LABEL_CLASSES = "Кластар"; var LABEL_DATA_PANEL = 'Метадеректер тақтасы'; var LABEL_CLASS_ST = 'Класс құрылымы'; var LABEL_UNFOLD = 'Барлығын кеңейтіңіз'; var LABEL_FOLD = 'Барлығын тасалау'; var LABEL_DOWNLOAD_XSD = 'Схеманы жүктеу'; var LABEL_ACTIVE = 'Белсенді'; var LABEL_NOT_ACTIVE = 'Белсенді емес'; var LABEL_SENDING = 'Жіберу ...'; var LABEL_ATTENTION = 'Назар'; var LABEL_ERROR_EXIST = 'Қате орын алды'; var LABEL_YES = 'Ия'; var LABEL_NO = 'Жоқ'; var LABEL_SIMPLE = 'Қарапайым'; var LABEL_COMPLEX = 'Композиттік'; var LABEL_SIMPLE_SET = 'Қарапайым жиым'; var LABEL_COMPLEX_SET = 'Композиттік массив'; var LABEL_NUMBER = 'Нөмір'; var LABEL_STRING = 'Жол'; var LABEL_BOOLEAN = 'Логикалық'; var LABEL_FLOAT = 'Қатысты нүкте нөмірі'; var LABEL_CLASS_CODE = 'Сынып коды'; var LABEL_PARENT_CODE = 'Ата-ана идентификаторы'; var LABEL_ATTRIBUTE_PUTH = 'Төлсипат жолы'; var LABEL_ATTRIBUTE_CODE = 'Атрибут коды'; var LABEL_ARRTIBUTE_NAME = 'Атрибут атауы'; var LABEL_ATTRIBUTE_TYPE = 'Атрибут түрі'; var LABEL_ATTRIBUTE_CLASS = 'Атрибут класы'; var LABEL_KEY_ATTRIBUTE = 'Негізгі төлсипат'; var LABEL_MUST_ATTRIBUTE = 'Міндетті төлсипат'; var LABEL_NULL_GET = 'Босату'; var LABEL_FINAL_RECORD = 'Соңғы жазба'; var LABEL_NOT_CHANGED_RECORD = 'Өзгеріссіз енгізу'; var LABEL_ACTIVITY = 'Белсенділік белгісі'; var LABEL_LOADING = 'Орындалуда ...'; var LABEL_ERROR = 'Қате'; var LABEL_ATTRIBUTE = 'Атрибут'; var LABEL_NOT_REF = 'Анықтама кітабы емес'; var LABEL_ALL_FIELDS = 'БАРЛЫҒЫ өрістерін толтырыңыз'; var LABEL_CLASS_TYPE = 'Класс түрі'; var LABEL_META = 'Метакласс'; var LABEL_REQUIRED_FIELD = "Обязательное поле"; var LABEL_UI_CONFIG = "UI CONFIG"; var label_OPER = 'Жедел'; var label_SYNCING = 'ДҚ обьектілерін мета деректермен синхрондау орындалуда'; var label_INFO = 'Ақпарат'; var label_SUC_SYNC = 'Синхрондау сәтті аяқталды'; var label_ALL = 'Барлығы'; var label_OFF = 'Жеке'; var label_DATE_AND_TIME = 'Күн және уақыт'; var label_SAVING = 'Сақталу орындалуда'; var label_MUST = 'Міндетті'; var label_NOT_ACTIVE = 'Белсенді емес '; var label_LINK = 'Сілтеме'; var label_NULLABLE = 'Нөлге айналдырылған'; var label_DOCH = 'Еншілес'; var label_MASS = 'Массивтер'; var label_SOBIR = 'Жинақтама'; var label_TYPE_KEY = 'Кілттің түрі'; var label_KEYS = 'Кілттер'; var label_KEYABLE = 'Негізгі'; var label_EMPTY = 'Бос'; var label_GROUP_KEYS = 'Кілттер тобы'; var label_2min = '2 минутқа дейін'; var label_10min = '10 минутқа дейін'; var label_50min = '50 минутқа дейін'; var label_50minmore = '50 минуттан жоғары'; var label_PERIODICY = 'Кезең'; var label_SIZE_TABLE = 'Кесте мөлшері*'; <file_sep> package kz.bsbnb.usci.wsclient.jaxb.kgd; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebService(name = "EiccToKgdUniversalPortType", targetNamespace = "http://nationalbank.kz/ws/EiccToKgdUniversal/") @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) @XmlSeeAlso({ ObjectFactory.class }) public interface EiccToKgdUniversalPortType { /** * * @param parameters * @return * returns ResponseMessage * @throws SendMessageException */ @WebMethod(operationName = "SendMessage", action = "http://10.8.255.50:1274/EiccToKgdUniversal/SendMessage") @WebResult(name = "sendMessageResponse", targetNamespace = "http://nationalbank.kz/ws/EiccToKgdUniversal/", partName = "parameters") public ResponseMessage sendMessage( @WebParam(name = "sendMessageRequest", targetNamespace = "http://nationalbank.kz/ws/EiccToKgdUniversal/", partName = "parameters") RequestMessage parameters) throws SendMessageException ; } <file_sep>group = 'kz.bsbnb.usci' version '0.1.0' dependencies { compile project(':wsclient:wsclient-core') compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('org.springframework.boot:spring-boot-starter-jdbc') compile('org.springframework.boot:spring-boot-starter-web') compile("org.springframework.boot:spring-boot-starter-actuator") } bootJar { baseName = 'usci-wsclient-boot' version = '0.1.0' } springBoot { mainClassName = 'kz.bsbnb.usci.wsclient.WsclientApplication' }<file_sep>package kz.bsbnb.usci.util.service.impl; import kz.bsbnb.usci.model.util.Application; import kz.bsbnb.usci.util.dao.ApplicationDao; import kz.bsbnb.usci.util.service.ApplicationService; import org.springframework.stereotype.Service; import java.util.List; @Service public class ApplicationServiceImpl implements ApplicationService { private final ApplicationDao applicationDao; public ApplicationServiceImpl(ApplicationDao applicationDao) { this.applicationDao = applicationDao; } @Override public List<Application> getAppList() { return applicationDao.getAppList(); } } <file_sep>package kz.bsbnb.usci.wsclient.controller; import kz.bsbnb.usci.wsclient.model.ctrkgd.Request; import kz.bsbnb.usci.wsclient.service.KGDService; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.util.List; @RestController @RequestMapping(value = "/kgd") public class KGDController { private final KGDService kgdService; public KGDController(KGDService kgdService) { this.kgdService = kgdService; } @GetMapping(value = "getCtrRequestList") public List<Request> getCtrRequestList(@RequestParam @DateTimeFormat(pattern = "dd.MM.yyyy") LocalDate reportDate){ return kgdService.getCtrRequestList(reportDate); } @PostMapping(value = "resendCtrRequest") public void resendCtrRequest (@RequestParam(name = "requestId") Long requestId, @RequestParam(name = "isUpdate") boolean isUpdate, @RequestParam @DateTimeFormat(pattern = "dd.MM.yyyy") LocalDate reportDate){ kgdService.ctrRequest(reportDate, requestId, isUpdate); } } <file_sep>group = 'kz.bsbnb.usci' version = '0.1.0' bootJar { enabled = false }<file_sep>Ext.require([ 'Ext.Msg', 'Ext.panel.*', 'Ext.form.*', 'Ext.selection.CellModel', 'Ext.grid.*', 'Ext.data.*' ]); Ext.onReady(function(){ var uploadStore = Ext.create('Ext.data.Store', { fields: ['name', 'size', 'file', 'status'] }); var postDocument = function(url, store, i) { var xhr = new XMLHttpRequest(); var fd = new FormData(); xhr.open("POST", url, true); fd.append('file', store.getAt(i).data.file); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { store.getAt(i).data.status = label_UPLOADED; store.getAt(i).commit(); } else if (xhr.readyState == 4 && xhr.status != 200) { store.getAt(i).data.status = label_ERROR+xhr.responseText; store.getAt(i).commit(); } }; xhr.send(fd); }; var panel = Ext.create('Ext.panel.Panel', { height: 600, width: '100%', hidden: isDataManager, renderTo: 'upload-content', id: 'NoAccessPanel', title: label_TITLE, html: '<p>Нет прав для загрузки</p>' }); var panel = Ext.create('Ext.tab.Panel', { height: 600, width: '100%', hidden: !isDataManager, renderTo: 'upload-content', id: 'MainTabPanel', items: [{ xtype: 'panel', title: label_TITLE, items: [{ multiSelect: true, xtype: 'grid', id: 'UploadGrid', height: 400, columns: [{ header: label_FILE_NAME, dataIndex: 'name', flex: 2 }, { header: label_FILE_SIZE, dataIndex: 'size', flex: 1, renderer: Ext.util.Format.fileSize }, { header: label_STATUS, dataIndex: 'status', flex: 1, renderer: function(value, metaData, record, rowIndex, colIndex, store) { var color = "grey"; if (value === label_READY) { color = "blue"; } else if (value === label_UPLOADING) { color = "orange"; } else if (value === label_UPLOADED) { color = "green"; } else if (value === label_MAIN_ERROR) { color = "red"; } value = "<span style='color:"+color+"' >"+value+"</span>"; return value; } }], viewConfig: { emptyText: label_INFO, deferEmptyText: false }, store: uploadStore, listeners: { drop: { element: 'el', fn: 'drop' }, dragstart: { element: 'el', fn: 'addDropZone' }, dragenter: { element: 'el', fn: 'addDropZone' }, dragover: { element: 'el', fn: 'addDropZone' }, dragleave: { element: 'el', fn: 'removeDropZone' }, dragexit: { element: 'el', fn: 'removeDropZone' }, }, noop: function (e) { e.stopEvent(); }, addDropZone: function (e) { if (!e.browserEvent.dataTransfer || Ext.Array.from(e.browserEvent.dataTransfer.types).indexOf('Files') === -1) { return; } e.stopEvent(); this.addCls('drag-over'); }, removeDropZone: function (e) { var el = e.getTarget(), thisEl = this.getEl(); e.stopEvent(); if (el === thisEl.dom) { this.removeCls('drag-over'); return; } while (el !== thisEl.dom && el && el.parentNode) { el = el.parentNode; } if (el !== thisEl.dom) { this.removeCls('drag-over'); } }, drop: function (e) { e.stopEvent(); Ext.Array.forEach(Ext.Array.from(e.browserEvent.dataTransfer.files), function (file) { uploadStore.add({ file: file, name: file.name, size: file.size, status: label_READY }); }); this.removeCls('drag-over'); }, tbar: [{ xtype: 'filefield', hideLabel: true, buttonOnly: true, buttonText: label_CHOOSE, listeners:{ afterrender:function(cmp){ cmp.fileInputEl.set({ multiple:'multiple' }); }, change:function(cmp){ Ext.Array.forEach(Ext.Array.from(cmp.fileInputEl.dom.files), function (file) { uploadStore.add({ file: file, name: file.name, size: file.size, status: label_READY }); }); cmp.reset(); } } }, { xtype: 'tbseparator', }, { text: label_TO_UPLOAD, handler: function () { for (var i = 0; i < uploadStore.data.items.length; i++) { if (!(uploadStore.getAt(i).data.status === label_UPLOADED)) { uploadStore.getAt(i).data.status = label_UPLOADING; uploadStore.getAt(i).commit(); postDocument(dataUrl+"/receiver/batch/uploadBatch?userId=" + userId + '&isNb=' + isNb, uploadStore, i); } } } }, { xtype: 'tbseparator', },{ text: label_DELETE_ALL, handler: function () { uploadStore.reload(); } }, { xtype: 'tbseparator', }, { text: label_DELETE_UPLOAD, handler: function () { for (var i = 0; i < uploadStore.data.items.length; i++) { var record = uploadStore.getAt(i); if ((record.data.status === label_UPLOADED)) { uploadStore.remove(record); i--; } } } },{ xtype: 'tbseparator', }, { text: label_DELETE_CHOSEN, handler: function () { uploadStore.remove(Ext.getCmp('UploadGrid').getSelectionModel().getSelection()); } }] }], padding: 20 }, { xtype: 'panel', hidden: true, title: label_EDS, items: [ { xtype: 'panel', border: false, title: '', layout: { type: 'hbox', align: 'middle', pack: 'center' }, items: [ { xtype: 'checkboxfield', disabled: true, checked: false, cls: 'checkBox', margin: '10 0 0 0', fieldLabel: '', boxLabel: label_SENDING } ] } ] }, { xtype: 'panel', hidden: true, title: label_DATE_SETTING, items: [ { xtype: 'panel', border: false, padding: 10, title: '', items: [ { xtype: 'datefield', fieldLabel: label_ORGANIZATION, labelAlign: 'top', labelStyle: 'font-weight: bold;', format: 'd.m.Y' } ] } ] }], tabBar: { xtype: 'tabbar', layout: { type: 'hbox', align: 'stretch' } } }); });<file_sep>package kz.bsbnb.usci.util.dao.impl; import kz.bsbnb.usci.model.exception.UsciException; import kz.bsbnb.usci.model.util.Application; import kz.bsbnb.usci.util.SqlJdbcConverter; import kz.bsbnb.usci.util.dao.ApplicationDao; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author <NAME> */ @Repository public class ApplicationDaoImpl implements ApplicationDao { private final JdbcTemplate jdbcTemplate; public ApplicationDaoImpl(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public List<Application> getAppList() { List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from USCI_UTIL.APP"); if (rows.size() == 0) throw new UsciException("Таблица USCI_UTIL.APP не содержит модулей"); List<Application> applications = new ArrayList<>(); for (Map<String, Object> row : rows) { Application application = new Application(); application.setId(SqlJdbcConverter.convertToLong(row.get("ID"))); application.setHost(String.valueOf(row.get("HOST"))); application.setPort(SqlJdbcConverter.convertToInt(row.get("PORT"))); application.setModule(String.valueOf(row.get("MODULE"))); application.setRmiPort(SqlJdbcConverter.convertToInt(row.get("RMI_PORT"))); application.setProduct(row.get("PRODUCT") != null? String.valueOf(row.get("PRODUCT")): null); applications.add(application); } return applications; } } <file_sep>package kz.bsbnb.usci.receiver.test; import kz.bsbnb.usci.receiver.model.BatchFile; import kz.bsbnb.usci.receiver.processor.BatchReceiver; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.StreamUtils; import java.io.FileInputStream; import java.io.IOException; @RunWith(SpringRunner.class) @SpringBootTest public class BatchProcessorTest { @Autowired private BatchReceiver batchReceiver; @Before public void setUp() { } @Test public void test0() throws IOException { String fileName = "C:\\bsb\\usci\\batches\\33333333\\5-cred_reg_file_31.03.2018.xml.zip"; BatchFile batchFile = new BatchFile(10196L, false, fileName); batchFile.setFileName("5-cred_reg_file_31.03.2018.xml.zip"); batchFile.setFileContent(StreamUtils.copyToByteArray(new FileInputStream(fileName))); batchReceiver.receiveBatch(batchFile); } } <file_sep>package kz.bsbnb.usci.wsclient.config; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClients; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.client.support.interceptor.ClientInterceptor; import org.springframework.ws.transport.http.HttpComponentsMessageSender; @Configuration public class SOAPClientConfig { @Value("${wsclient.kgdUrl}") private String kgdUrl; @Bean Jaxb2Marshaller nsiJaxb2Marshaller() { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setContextPath("kz.bsbnb.usci.wsclient.jaxb.nsi"); return jaxb2Marshaller; } @Bean Jaxb2Marshaller kgdJaxb2Marshaller() { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setContextPath("kz.bsbnb.usci.wsclient.jaxb.kgd"); return jaxb2Marshaller; } @Bean public WebServiceTemplate nsiWebServiceTemplate() { WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); webServiceTemplate.setMarshaller(nsiJaxb2Marshaller()); webServiceTemplate.setUnmarshaller(nsiJaxb2Marshaller()); webServiceTemplate.setDefaultUri("https://nbportal.nationalbank.kz:443/WebService/NSI_NBRK"); webServiceTemplate.setMessageSender(httpComponentsMessageSender()); return webServiceTemplate; } @Bean public WebServiceTemplate kgdWebServiceTemplate() { WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); webServiceTemplate.setMarshaller(kgdJaxb2Marshaller()); webServiceTemplate.setUnmarshaller(kgdJaxb2Marshaller()); webServiceTemplate.setDefaultUri("http://"+kgdUrl+"/EiccToKgdUniversal"); webServiceTemplate.setMessageSender(httpComponentsMessageSender()); ClientInterceptor[] interceptors = new ClientInterceptor[] {new LogClientInterceptor()}; webServiceTemplate.setInterceptors(interceptors); return webServiceTemplate; } @Bean public HttpComponentsMessageSender httpComponentsMessageSender() { HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender(); httpComponentsMessageSender.setReadTimeout(3000000); httpComponentsMessageSender.setConnectionTimeout(3000000); return httpComponentsMessageSender; } @Bean public HttpComponentsMessageSender httpProxyComponentsMessageSender() { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope("10.10.32.14",3128), new UsernamePasswordCredentials("bakash.yernur","3791364Ss")); HttpClient client = HttpClients.custom() .addInterceptorFirst(new HttpComponentsMessageSender.RemoveSoapHeadersInterceptor()) .setDefaultCredentialsProvider(credentialsProvider) .setProxy(new HttpHost("10.10.32.14", 3128, "http")) .build(); HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender(client); //httpComponentsMessageSender.setReadTimeout(3000000); // httpComponentsMessageSender.setConnectionTimeout(3000000); return httpComponentsMessageSender; } }
785253804ad17feb9395439931b448188ca66828
[ "JavaScript", "Java", "INI", "Gradle" ]
241
Java
Kaliaskar/usci_2
cf2ed14cffbf94bab679b0a688e34d82d4f7dc74
340660060f1b79145cf2612d79fea8c47729062c
refs/heads/master
<repo_name>BGCX261/zope3tutorial-svn-to-git<file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/browser/navigator.py """ Simple navigator to allow easy navigation of code in the file system. """ import os import os.path from zope.publisher.interfaces import IRequest from five import grok from ploneide.core import PloneIDENavigatorViewletManager from ploneide.core import PloneIDEJSViewletManager from ploneide.core import IPloneIDE from ploneide.core import IPloneIDEModel class FileSystemNavigator(grok.Viewlet): grok.name('navigator-filesystem') grok.require('cmf.ManagePortal') grok.context(IPloneIDE) grok.viewletmanager(PloneIDENavigatorViewletManager) grok.order(100) def render(self): # Navigator must provide code to fit into the jstree structure. return """ <h2 class="current">Files</h2> <div style="display:block" class="pane"> <p style="color:#333">Files in ./src folder:</p> <div id="tree"></div> </div>""" class FileSystemNavigatorResources(grok.Viewlet): """jquery.jstree is in the static folder""" grok.name('navigator-filesystem') grok.require('cmf.ManagePortal') grok.viewletmanager(PloneIDEJSViewletManager) grok.context(IPloneIDE) grok.order(200) def render(self): rv = [ """<script src="%s/++resource++ploneide.core/ploneide-fs-navigator.js" type="text/javascript"></script>""" % self.context.portal_url(), """<script src="%s/++resource++ploneide.core/ploneide-edit-bespin.js" type="text/javascript"></script>""" % self.context.portal_url(), ] return '\n'.join(rv) class FileSystemHandler(grok.MultiAdapter): grok.adapts(IPloneIDE, IRequest) grok.provides(IPloneIDEModel) grok.name('navigator-filesystem') def __init__(self, context, request): self.context = context self.request = request def handle(self, type_name, method_name, form): """The filesystem should be built using ajax to reduce load. This method should be called to build the tree""" try: method = getattr(self, method_name) except: raise NotImplemented return method() ## methods implementing the services def _included(self, filename): """Used to exclude files and folders""" if filename.startswith('.'): return False for suffix in ['.pyc', '.pyo', '.egg-info', '.swp', '~', '.pt.py', '.tmp', '.save', 'PKG-INFO', 'SOURCES.txt', '.#']: if filename.endswith(suffix): return False return True def _is_editable(self, filename): for suffix in ['.png', '.jpg', 'gif', 'swf']: if filename.endswith(suffix): return False return True def _recurse_folder(self, folder, is_project=False): """recurse the path adding items the output""" children = [] dirs = [] for filename in sorted(os.listdir(folder)): if not self._included(filename): continue if os.path.isdir(folder + os.sep + filename): dirs.append(filename) else: children.append({'data': { 'title': filename, 'attr': {} }, 'attr': {'id': 'navigator-filesystem:' + folder + os.sep + filename} }) for dirname in dirs: children.append(self._recurse_folder(folder + os.sep + dirname)) return { 'data': { 'title': os.path.basename(folder), 'attr': { 'isFolder': True, 'lineNumber': 1, }, }, 'attr': {'id': 'navigator-filesystem:' + folder}, 'children': children} def _isProject(self, folder): """If the path represents a project, return True, else False""" if os.path.isdir(folder) and os.path.exists(folder + os.sep + 'setup.py'): return True return False def getNavigation(self): """Return a structure containing the navigation, as used by dynatree """ rv = [] srcdir = os.getcwd() + os.sep + 'src' for folder in os.listdir(srcdir): if self._isProject(srcdir + os.sep + folder): rv.append(self._recurse_folder(srcdir + os.sep + folder, True)) return rv def getFile(self): """retrieve a file - return it with some other information""" filename = self.request.get('filename', None) if filename is None: raise NotImplemented payload = open(filename).read() syntax = None model = None if filename.endswith('.py'): model = syntax = 'py' elif filename.endswith('.pt'): syntax = 'html' model = 'pt' elif filename.endswith('.zcml'): syntax = 'html' model = 'zcml' elif filename.endswith('.txt'): syntax = model = 'txt' elif filename.endswith('.css'): syntax = model = 'css' elif filename.endswith('.js'): model = 'js' syntax = 'javascript' else: syntax = 'auto' model = 'txt' return { 'filename': filename, 'syntax': syntax, 'model': model, 'payload': payload, 'readonly': False } <file_sep>/trunk/generator/z3gen_views.py import z3gen_utilities TAB=' ' class Generator: def __init__(self, DSLModel, Table): self.DSLModel = DSLModel self.Table = Table self.TableName = Table['name'] self.interface_name = 'I%s%s' % (self.TableName[0].upper(), self.TableName[1:]) self.field0name = Table['columns'][0]['colname'] self.z3c_layer='' try: self.z3c_layer='layer="%s"\n\t\t' % self.DSLModel['GENERAL']['z3c_layer'] except: pass # Extract the primary key from the list of fields. Don't allow the user # to change this on the edit screens self.primary_key=Table.get('primary_key', None) if self.primary_key != None: if type(self.primary_key) == type([]): # primary key DSL syntax can be list of fields if len(self.primary_key) > 1: print 'Error - only handle the case of a single primary key' sys.exit(1) self.primary_key = self.primary_key[0] else: # For now assume that it is the first field if the generator needs one. # later this should be an error self.fields_excluding_key = Table['columns'][1:] self.primary_key = self.field0name print 'Assuming that the primary key is the first key field' self.columns_excluding_key = [x for x in Table['columns'] if x['colname'] != self.primary_key] self.key_columns = [x for x in Table['columns'] if x['colname'] == self.primary_key] self.update_omit=".omit('__name__', '__parent__')" self.view_omit=".omit('__name__', '__parent__')" self.create_omit=".omit('__name__', '__parent__')" self.load_templates() def load_templates(self): """Load the template. Search for: templates/views_form_library_stereotype templates/views_form_library templates/views_stereotype templates/views Form library should be one of formlib or z3c (.form) """ stereotype = self.Table['stereotype'] form_library = self.DSLModel['GENERAL']['form_library'] import_paths=[ 'templates/views_%s_%s' % (form_library, stereotype), 'templates/views_%s' % (form_library), 'templates/views_%s' % (stereotype), 'templates/views'] self.templates = z3gen_utilities.ImportTemplate(import_paths) def filename(self): """Return the name of the file""" return '%s_views.py' % self.TableName def render(self): """Return a string containing the generated file""" rv = [] self.classnames=[] self.classnames.append('Add') self.classnames.append('Edit') self.classnames.append('View') file_content = self.templates.GenFile(self.DSLModel, self.Table, self) file_content = file_content.replace('\t', TAB) z3gen_utilities.ReplaceFile(self.DSLModel, self.Table, self.filename(), file_content, format="python") # configure.zcml entries self.genConfiguration() def genConfiguration(self): """The configure.zcml entries required""" file_content = self.templates.GenConfiguration(self.DSLModel, self.Table, self) self.Table['config'].append(file_content) <file_sep>/trunk/kg.locationfield/kg/locationfield/map_enabled.py from zope.interface import implements from Products.Five.browser import BrowserView from Products.Maps.interfaces import IMapView from kg.locationfield.field import MyLocationField class MapWidgetEnabled(BrowserView): implements(IMapView) def __init__(self, context, request): self.context = context self.request = request @property def enabled(self): for field in self.context.fgFields(): if isinstance(field, MyLocationField): return True return False <file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/browser/editor.py """ This view should construct the editor """ from ploneide.core import IPloneIDE from ploneide.core import PloneIDEJSViewletManager from ploneide.core import PloneIDECSSViewletManager from ploneide.core import PloneIDENavigatorViewletManager from five import grok class Editor(grok.View): grok.context(IPloneIDE) grok.require('cmf.ManagePortal') class JQueryTreeResources(grok.Viewlet): """jquery.jstree is in the static folder""" grok.name('jquery.jstree') grok.require('zope2.View') grok.viewletmanager(PloneIDEJSViewletManager) grok.context(IPloneIDE) grok.order(20) def render(self): return """<script src="%s/++resource++ploneide.core/jquery.jstree/jquery.jstree.js" type="text/javascript"></script>\n""" % self.context.portal_url() class JQuerySplitterResources(grok.Viewlet): """jquery.splitter is in the static folder""" grok.name('jquery.splitter') grok.require('zope2.View') grok.viewletmanager(PloneIDEJSViewletManager) grok.context(IPloneIDE) grok.order(20) def render(self): return """<script src="%s/++resource++ploneide.core/jquery.splitter/splitter.js" type="text/javascript"></script>\n""" % self.context.portal_url() class DefaultCSSResources(grok.Viewlet): """ploneide.css is in the static/css folder""" grok.name('ploneide.core.ploneide') grok.require('zope2.View') grok.viewletmanager(PloneIDECSSViewletManager) grok.context(IPloneIDE) grok.order(100) def render(self): return """<link rel="stylesheet" href="%s/++resource++ploneide.core/ploneide.css" type="text/css" />\n""" % self.context.portal_url() class DefaultJSResources(grok.Viewlet): """ploneide.js is in the static/js folder""" grok.name('ploneide.core.ploneide') grok.require('zope2.View') grok.viewletmanager(PloneIDEJSViewletManager) grok.context(IPloneIDE) grok.order(100) def render(self): return """<link id="ploneide_base" href="%s" /> <script src="%s/++resource++ploneide.core/ploneide.js" type="text/javascript"></script>""" % (self.context.absolute_url(), self.context.portal_url()) class JQueryBespinResources(grok.Viewlet): """bespin is in the static folder""" grok.name('bespin') grok.require('zope2.View') grok.viewletmanager(PloneIDEJSViewletManager) grok.context(IPloneIDE) grok.order(20) def render(self): return """<link id="bespin_base" href="%s/++resource++ploneide.core/bespin-0.9a1/" /> <script src="%s/++resource++ploneide.core/bespin-0.9a1/BespinEmbedded.js" type="text/javascript"></script>\n""" % ( self.context.portal_url(), self.context.portal_url()) <file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/tool.py """ This is the portal_ploneide which is created in the root of the plone site. """ from zope.interface import implements from OFS.SimpleItem import SimpleItem from ploneide.core import IPloneIDE class PloneIDE(SimpleItem): """This should be installed as a Tool by plone""" implements(IPloneIDE) <file_sep>/trunk/boston_pagelet_skin/README.txt Boston Pagelet Skin ------------------- This is a very simple skin for testing the generated code. It provides a pagelet version of the boston main template. The configurations are: .skin.ISkin - the skin .layer.IPageletLayer - the layer for registering z3c.pagelet and z3c.form The resulting skin can be viewed as: ++skin++BostonPagelet Add this directory to your src directory as boston_pagelet_skin. For your pagelets based content, register them with layer="boston_pagelet_skin.IPageletLayer" In the dsl file, set the GENERAL Section as follows: GENERAL = { 'namespace': 'test', 'sql_dialect': 'postgresql', 'target_folder': 'tables', 'form_library': 'z3c', 'z3c_layer': 'boston_pagelet_skin.IPageletLayer', } ######## I had to hack the original skin configuration so that the navigation viewlet only appears for the admin members. <file_sep>/trunk/generator/z3gen_content.py import sys import z3gen_utilities TAB=' ' class Generator: def __init__(self, DSLModel, Table): self.DSLModel = DSLModel self.Table = Table self.TableName = Table['name'] self.interface_name = 'I%s%s' % (self.TableName[0].upper(), self.TableName[1:]) self.field0name = Table['columns'][0]['colname'] # Build a list of all of the vocabularies required vocabs=[] for col in Table['columns']: schema = col['schema_fields'] if 'vocabulary' in schema: vocab = schema['vocabulary'] if vocab not in vocabs: vocabs.append(vocab) if 'value_type_fields' in col: schema = col['value_type_fields'] if 'vocabulary' in schema: vocab = schema['vocabulary'] if vocab not in vocabs: vocabs.append(vocab) self.required_vocabularies = vocabs self.load_templates() # Extract the primary key from the list of fields for separate # processing if required self.primary_key=Table.get('primary_key', None) if self.primary_key != None: if type(self.primary_key) == type([]): # primary key DSL syntax can be list of fields if len(self.primary_key) > 1: print 'Error - only handle the case of a single primary key' sys.exit(1) self.primary_key = self.primary_key[0] else: # For now assume that it is the first field if the generator needs one. # later this should be an error self.fields_excluding_key = Table['columns'][1:] self.primary_key = self.field0name print 'Assuming that the primary key is the first key field' self.fields_excluding_key = [x for x in Table['columns'] if x['colname'] != self.primary_key] def load_templates(self): """Load the template. Search for: templates/content_stereotype templates/content """ stereotype = self.Table['stereotype'] import_paths=['templates/content_%s' % stereotype, 'templates/content'] self.templates = z3gen_utilities.ImportTemplate(import_paths) import_paths=['templates/tests_%s' % stereotype, 'templates/tests'] self.test_templates = z3gen_utilities.ImportTemplate(import_paths) def filename(self): """Return the name of the file""" return '%s_content.py' % self.TableName def storage_filename(self): """Return the name of the file""" return '%s_storage.py' % self.TableName def tests_filename(self): """Return the name of the file""" return 'tests.py' def doctests_filename(self): """Return the name of the file""" return '%s.txt' % self.TableName def render(self): """Return a string containing the generated file""" self.classnames=[] self.classnames.append(self.Table['name']) self.classnames.append(self.Table['name']+'Container') self.classnames.append(self.Table['name']+'_dublincore') self.classnames.append(self.Table['name']+'ContainerNameChooser') file_content = self.templates.GenFile(self.DSLModel, self.Table, self) file_content = file_content.replace('\t', TAB) z3gen_utilities.ReplaceFile(self.DSLModel, self.Table, self.filename(), file_content, format="python") file_content = self.templates.GenStorageFile(self.DSLModel, self.Table, self) file_content = file_content.replace('\t', TAB) z3gen_utilities.ReplaceFile(self.DSLModel, self.Table, self.storage_filename(), file_content, format="python") # configure.zcml entries self.genConfiguration() # Tests self.genTests() def genConfiguration(self): """The configure.zcml entries required""" file_content = self.templates.GenConfiguration(self.DSLModel, self.Table, self) self.Table['config'].append(file_content) def genTests(self): """Generate the tests - these files are not replaced if they exist""" if not z3gen_utilities.FileExists(self.DSLModel, self.Table, self.tests_filename()): file_content = self.test_templates.GenTestLoader(self.DSLModel, self.Table, self) file_content = file_content.replace('\t', TAB) z3gen_utilities.ReplaceFile(self.DSLModel, self.Table, self.tests_filename(), file_content, format="python") if not z3gen_utilities.FileExists(self.DSLModel, self.Table, self.doctests_filename()): file_content = self.test_templates.GenDocTests(self.DSLModel, self.Table, self) file_content = file_content.replace('\t', TAB) z3gen_utilities.ReplaceFile(self.DSLModel, self.Table, self.doctests_filename(), file_content, format="doctest") <file_sep>/trunk/kg.locationfield/README.txt Introduction ============ This is a PloneFormGen Field for entering a Products.Maps Location. It is a simple wrapper and does not implement the actual field. <file_sep>/trunk/generator/templates/literal.py from templet import stringfunction @stringfunction def db_file(DSLModel, Table): """ # A base class to allow me to structure my SQLDTML Code together import zope.component from zope.rdb.interfaces import IZopeDatabaseAdapter from zope.rdb import queryForResults from zope.app.sqlscript.dtml import SQLDTML from ${DSLModel['GENERAL']['target_folder']}.${Table['name']} import CONNECTION_NAME ECHO_SQL=False class SQLDTML_BaseBase: def __init__(self, context): \"""I need to store the context. Since I use a local utility, the context is required to find it. Otherwise would find only global utilities\""" self.context = context def execute(self, ex_command_name, ex_dtml_str, **params): \"""execute the instruction. ex_command_name is the name of the function - intended for use in error messages dtml_str is the dmtl command as a string params are the parameters to be encoded \""" sqldtml = SQLDTML(ex_dtml_str) query = sqldtml(**params) if ECHO_SQL: print "--------------------------------------------------------------------" print query connection= zope.component.getUtility(IZopeDatabaseAdapter, CONNECTION_NAME, self.context)() return queryForResults(connection, query) # CAN_EDIT_AFTER_THIS_LINE class SQLDTML_Base(SQLDTML_BaseBase): pass """ @stringfunction def config_file(DSLModel, Table): """ <configure xmlns="http://namespaces.zope.org/zope" xmlns:browser="http://namespaces.zope.org/browser" ${{ if (DSLModel['GENERAL']['form_library'] == 'z3c'): out.append('\txmlns:z3c="http://namespaces.zope.org/z3c"\\n') }} i18n_domain="${DSLModel['GENERAL']['namespace']}.${Table['name']}"> ${{ for c in Table['config']: out.append(c) out.append('\\n') }} <!-- CAN_EDIT_AFTER_THIS_LINE --> </configure> """ @stringfunction def init_file(DSLModel, Table): """ from zope.i18nmessageid import MessageFactory MessageFactory = MessageFactory('${DSLModel['GENERAL']['namespace']}.${Table['name']}') CONNECTION_NAME='${DSLModel['GENERAL']['namespace']}' """ @stringfunction def schema_helpers(DSLModel, Table): """ # Functions used to map single content elements to single table # elements. Focus on database type to python type e.g. list from zope.schema.fieldproperty import FieldProperty from base64 import encodestring, decodestring def Bool_toStorage(value): if value: return 't' return 'f' def Bool_fromStorage(value): return value def List_toStorage(value): if value: return ','.join(value) else: return '' def List_fromStorage(value): if value: return value.split(',') else: return [] def BinaryToBase64_fromStorage(value): if value is None or len(value) == 0: return '' return decodestring(value) def BinaryToBase64_toStorage(value): if value is None or len(value) == 0: return '' return encodestring(value) """ <file_sep>/trunk/kg.locationfield/kg/locationfield/field.py from AccessControl import ClassSecurityInfo from Products.CMFCore.permissions import View from Products.CMFCore.Expression import getExprContext from Products.Archetypes.atapi import Schema from Products.Archetypes.Field import StringField from Products.Archetypes.Widget import StringWidget from Products.ATContentTypes.content.base import registerATCT from Products.Maps.field import LocationField, LocationWidget from Products.TALESField import TALESString from Products.PloneFormGen.content.fieldsBase import finalizeFieldSchema, BaseFieldSchema, BaseFormField from kg.locationfield.config import PROJECTNAME from zope.component import getMultiAdapter class MyLocationField(LocationField): # There is a massive problem in the retrieval of data from the object. Need # to track it via the normal mechanism accessor = "dummy_accessor" def dummy_accessor(self): if self.tmp_value == None: return self.default return self.tmp_value def getAccessor(self, context): return self.dummy_accessor class FGLocationField(BaseFormField): """ A string entry field """ security = ClassSecurityInfo() schema = BaseFieldSchema.copy() # hide references & discussion finalizeFieldSchema(schema, folderish=True, moveDiscussion=False) # Standard content type setup portal_type = meta_type = 'FormLocationField' archetype_name = 'Location Field' content_icon = 'location_icon.gif' typeDescription= 'A location field' def __init__(self, oid, **kwargs): """ initialize class """ super(BaseFormField, self).__init__(oid, **kwargs) # set a preconfigured field as an instance attribute self.fgField = MyLocationField('fg_location_field', languageIndependent = 1, default_method="getDefaultLocation", required=True, write_permission = View, validators=('isGeoLocation',), tmp_value = None, widget=LocationWidget( label='Location', ), ) def fgPrimeDefaults(self, request, contextObject=None): """ primes request with default value""" BaseFormField.fgPrimeDefaults(self, request, contextObject) form_val = request.get(self.fgField.__name__, None) if form_val: self.fgField.tmp_value = form_val else: config = getMultiAdapter((self, request), name="maps_configuration") self.fgField.tmp_value = config.default_location request.form.setdefault(self.fgField.__name__, self.fgField.tmp_value) registerATCT(FGLocationField, PROJECTNAME) <file_sep>/trunk/kg.locationfield/kg/locationfield/config.py from Products.CMFCore import permissions PROJECTNAME = 'kg.locationfield' ADD_PERMISSIONS = { 'FormLocationField' : permissions.AddPortalContent, # -*- extra stuff goes here -*- } <file_sep>/trunk/boston_pagelet_skin/newmanager.py from zope.viewlet import manager class LeftViewletManager(manager.ConditionalViewletManager): """Ordered viewlet and Conditional.""" def sort(self, viewlets): """Sort the viewlets on their weight.""" return sorted(viewlets, lambda x, y: cmp(x[1].getWeight(), y[1].getWeight())) <file_sep>/trunk/generator/z3gen_dbclass.py import sys import z3gen_utilities TAB=' ' def DTMLType(n): if n == 'integer': return 'int' if n == 'double precision': return 'float' else: return 'string' class Generator: def __init__(self, DSLModel, Table): self.DSLModel = DSLModel self.Table = Table self.TableName = Table['name'] self.columns=[] for column in Table['columns']: required = column['schema_fields'].get('required', False) self.columns.append((column['colname'], DTMLType(column['dbtype']), required)) # Extract the primary key from the list of fields. Don't allow the user # to change this on the edit screens self.primary_key=Table.get('primary_key', None) if self.primary_key != None: if type(self.primary_key) == type([]): # primary key DSL syntax can be list of fields if len(self.primary_key) > 1: print 'Error - only handle the case of a single primary key' sys.exit(1) self.primary_key = self.primary_key[0] else: # For now assume that it is the first field if the generator needs one. # later this should be an error self.fields_excluding_key = Table['columns'][1:] self.primary_key = self.field0name print 'Assuming that the primary key is the first key field' # Split the primary_key out of the list of columns self.columns_excluding_key = [x for x in self.columns if x[0] != self.primary_key] self.key_columns = [x for x in self.columns if x[0] == self.primary_key] if len(self.key_columns) == 0: print 'Error - primary key is not set of columns' sys.exit(1) self.primary_key_type = self.key_columns[0][1] key_table_col = [x for x in Table['columns'] if x['colname'] == self.primary_key] # Extract special field types that have to be massaged during create/update self.bools=[x['colname'] for x in Table['columns'] if x['schema_type'] == 'schema.Bool' and x['dbtype'] == 'boolean'] self.commalists=[x['colname'] for x in Table['columns'] if x.get('mapping_type', 'MappingProperty') == 'MappingList'] self.load_templates() def load_templates(self): """Load the template. Search for: templates/dbclass_sql_dialect_stereotype templates/dbclass_sql_dialect templates/dbclass_stereotype templates/dbclass Form library should be one of formlib or z3c (.form) """ stereotype = self.Table['stereotype'] sql_dialect = self.DSLModel['GENERAL']['sql_dialect'] import_paths=[ 'templates/dbclass_%s_%s' % (sql_dialect, stereotype), 'templates/dbclass_%s' % (sql_dialect), 'templates/dbclass_%s' % (stereotype), 'templates/dbclass'] self.templates = z3gen_utilities.ImportTemplate(import_paths) def filename(self): """Return the name of the file""" return '%s_db.py' % self.TableName def render(self): """Return a string containing the generated file""" self.classnames=[] self.classnames.append(self.Table['name']) file_content = self.templates.GenFile(self.DSLModel, self.Table, self) file_content = file_content.replace('\t', TAB).replace('\\"""', '"""') z3gen_utilities.ReplaceFile(self.DSLModel, self.Table, self.filename(), file_content, format="python") <file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/static/ploneide.js /* * Core functions for the editor * http://www.learningjquery.com/2007/10/a-plugin-development-pattern */ (function($) { // create closure $.ploneide = {}; $.ploneide.controllers = {}; $.ploneide.views = {}; $.ploneide._controllers = []; var href = document.getElementById("ploneide_base").href; $.ploneide.base_url = href.substring(href.length - 1) !== "/" ? href + "/" : href; $.ploneide.handle = function(type_name, method_name, data, success) { var params = {'type_name': type_name, 'method_name': method_name}; $.extend(params, data); return $.ajax({ url: $.ploneide.base_url + 'handler', type: 'GET', dataType: 'json', data: params, success: function(xml){ success(xml); } }); }; $.ploneide.register_controller = function(controller_name, controller) { $.ploneide.controllers[controller_name] = controller; }; $.ploneide.register_view = function(type_name, view, priority) { var reg = $.ploneide.views[type_name]; if (!reg) { reg = [] } reg[reg.length] = [priority, view]; // todo sort $.ploneide.views[type_name] = reg; }; // This is the controller base class $.ploneide.Controller = function() { this.init_super = function(type_name, unique_id, initial_data, model_data) { this.type_name = type_name; this.unique_id = unique_id; this.inital_data = initial_data; this.model_data = model_data; this._editors = []; }; this.draw_editors = function() { var i; var model = this.model_data.model; var views = $.ploneide.views[model]; if (views == 'undefined') { alert('No editors configured for model type ' + this.model_data.model); return; } for (i = 0; i < views.length; i++) { var editor = new views[i][1](this); editor.draw(); this._editors[this._editors.length] = editor; } }; this.destroy_editors = function() { }; }; // This is the baseclass for editors $.ploneide.Editor = function() { this.init_super = function(controller) { this.controller = controller; }; }; $.ploneide.edit_file = function(type_name, unique_id, initial_data) { return $.ploneide.handle(type_name, 'getFile', {'filename': unique_id}, success = function(xml) { // Got an object back - create a controller to handle it var controller_class = $.ploneide.controllers[type_name]; var controller = new controller_class(type_name, unique_id, initial_data, xml); controller.draw_editors(); $.ploneide._controllers[unique_id] = controller; return; }); }; })(jQuery); $(document).ready(function() { /* Initialise the Page Layout */ $("#simple-editor-layout").splitter({ splitVertical: true, outline: true, sizeLeft: true, resizeToWidth: true }); $("#simple-editor-layout #main").splitter({ splitHorizontal: true, outline: true, sizeTop: true }); $('#simple-editor-layout #main #top').bind('resize', function(e, size) { $('div.bespin').each(function(i, el) {var env = el.bespin; env.dimensionsChanged();}); return true; }); $("#navigation-pane").tabs("#navigation-pane div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null}); // setup ul.tabs to work as tabs for each div directly under div.panes $("ul.tabs").tabs("div.panes > div"); }); <file_sep>/trunk/generator/templates/dbclass.py # Templates for generating interfaces # # Uses the templet library from davidbau.com # from templet import stringfunction @stringfunction def GenFile(DSLModel, Table, View): r""" import types from base64 import encodestring from db import SQLDTML_Base class ${Table['name']}Base(SQLDTML_Base): \""" CREATE TABLE ${Table['name']} ( ${{ for i in range(len(Table['columns'])): column = Table['columns'][i] if i == len(Table['columns'])-1: comma='' else: comma=',' if column.has_key('dbextra'): dbextra = ' '+column['dbextra'] else: dbextra = '' out.append('\t\t%s %s%s%s\n' % (column['colname'], column['dbtype'], dbextra, comma)) }} ); \""" def Create(self, ${{ out.append('\t'+', '.join([col[0] for col in View.columns_excluding_key])) }}, ${View.primary_key} = None): \""" insert into ${Table['name']} ( ${{ out.append('\t\t'+', '.join([col[0] for col in View.columns_excluding_key])) }} <dtml-if expr="${View.primary_key} != None"> , ${View.primary_key} </dtml-if> ) values ( ${{ for (name, dbtype, required) in View.columns_excluding_key[:-1]: optional='' if not required: optional=' optional' out.append('\t\t\t<dtml-sqlvar %s type="%s"%s>,\n' % (name, dbtype, optional)) (name, dbtype, required) = View.columns_excluding_key[-1] optional='' if not required: optional=' optional' out.append('\t\t\t<dtml-sqlvar %s type="%s"%s>\n' % (name, dbtype, optional)) }} <dtml-if expr="${View.primary_key} != None"> , <dtml-sqlvar ${View.primary_key} type="${View.primary_key_type}"> </dtml-if> ); ${{if Table['primary_key_has_sequence']: out.append('\t\t<dtml-if expr="%s == None">\n' % View.primary_key) out.append("\t\t\tselect currval('%s') as %s;\n" % (Table['primary_key_sequence_name'], View.primary_key)) out.append('\t\t</dtml-if>\n') }} \""" params={} for (k,v) in locals().items(): if k in ['self', 'params']: continue if v is not None: params[k] = v result = self.execute('${Table['name']}.Create', self.Create.__doc__, **params) return result def Read(self, ${View.primary_key}): \"""select * from ${Table['name']} where ${View.primary_key} = <dtml-sqlvar ${View.primary_key} type="${View.primary_key_type}"> \""" params=locals().copy() del params['self'] result = self.execute('${Table['name']}.Read', self.Read.__doc__, **params) return result def Update(self, ${View.primary_key}, ${{field_names=[col[0] for col in View.columns[1:]] out.append('\t\t' + '=None, '.join(field_names) +'=None') }} ): \""" update ${Table['name']} set ${View.primary_key} = ${View.primary_key} ${{ for (col_name, col_type, required) in View.columns_excluding_key: out.append('\t\t\t<dtml-if expr="%s != None">\n' % col_name) out.append('\t\t\t\t, %s=<dtml-sqlvar %s type="%s">\n' % (col_name, col_name, col_type)) out.append('\t\t\t</dtml-if>\n') }} where ${View.primary_key} = <dtml-sqlvar ${View.primary_key} type="${View.primary_key_type}"> \""" params={} for (k,v) in locals().items(): if k in ['self', 'params']: continue params[k] = v result = self.execute('${Table['name']}.Update', self.Update.__doc__, **params) return result def Delete(self, ${View.primary_key}): \""" delete from ${Table['name']} where ${View.primary_key} = <dtml-sqlvar ${View.primary_key} type="${View.primary_key_type}"> \""" params=locals().copy() del params['self'] result = self.execute('${Table['name']}.Delete', self.Delete.__doc__, **params) return result def Keys(self): \""" select ${View.primary_key} from ${Table['name']} order by ${View.primary_key} \""" result = self.execute('${Table['name']}.Keys', self.Keys.__doc__) return result def Len(self): \""" select count(*) from ${Table['name']} \""" result = self.execute('${Table['name']}.Len', self.Len.__doc__) return result def Search(self, ${{ out.append('=None, '.join(Table['search_columns']) +'=None,') }} start=None, batch_size=None): \"""select * from ${Table['name']} where 1 = 1 ${{ for (col_name, col_type, required) in [ col for col in View.columns if col[0] in Table['search_columns']]: if col_type == 'string': match = 'ilike' else: match = '=' out.append('\t\t\t<dtml-if expr="%s != None">\n' % col_name) out.append('\t\t\t\tand %s %s <dtml-sqlvar %s type="%s">\n' % (col_name, match, col_name, col_type)) out.append('\t\t\t</dtml-if>\n') }} <dtml-if expr="start != None"> and id > <dtml-sqlvar start type="int"> </dtml-if> order by id <dtml-if expr="batch_size != None"> limit <dtml-sqlvar batch_size type="int"> </dtml-if> \""" params={} for (k,v) in locals().items(): if k in ['self', 'params']: continue if k in ['start', 'batch_size']: params[k] = v continue if type(v) in types.StringTypes: params[k] = v.replace('*', '%') else: params[k] = v result = self.execute('${Table['name']}.Search', self.Search.__doc__, **params) return result ${{if Table['primary_key_has_sequence']: out.append('\tdef NextPrimaryKey(self):\n') out.append('\t\t\"""\n') out.append("\t\t\tselect nextval('%s') as %s;\n" % (Table['primary_key_sequence_name'], View.primary_key)) out.append('\t\t\"""\n') out.append("\t\tresult = self.execute('%s.NextPrimaryKey', self.NextPrimaryKey.__doc__)\n" % Table['name']) out.append('\t\treturn result\n\n') }} # CAN_EDIT_AFTER_THIS_LINE ${{ for classname in View.classnames: out.append('class %s(%sBase):\n' % (classname, classname)) out.append('\tpass\n\n') }} """ <file_sep>/trunk/boston_pagelet_skin/navigation.py # Extra area added for global navigation from zope.viewlet.interfaces import IViewletManager from zope.viewlet.manager import WeightOrderedViewletManager import zope.interface class IGlobalMenu(IViewletManager): "Navigation Menu Viewlet Manager" class GlobalMenu(WeightOrderedViewletManager): zope.interface.implements(IGlobalMenu) <file_sep>/trunk/generator/psql2dsl.py #!/usr/bin/env python # Generate a dsl file from a postgres database table # TODO: Merge results with an existing output file import sys, os NAMESPACE='castingzone' PSQLCMD='echo \\\d %s | psql -t' # First Grab the Data Model def grab_schema(table): """Postgres mechanism to grab schema""" pipe = os.popen(PSQLCMD % table) # Now parse it rv=[] for row in pipe.readlines(): if len(row) == 0: continue if row[-1] in ['\n', '\r']: row = row[:-1] if len(row) == 0: continue if row[-1] in ['\n', '\r']: row = row[:-1] if len(row) == 0: continue parts = row.split('|') if len(parts) < 2: continue parts = [x.strip() for x in parts ] rv.append(parts) return rv def getSequenceId(s): """If the field is a serial, pull the sequence id out of the field""" parts = s.split('nextval') if len(parts) < 2: return '' parts = parts[1].split("'") return parts[1] def getLengthFromType(t): """Get the maximum length of a field from the postgres type""" if t.find('char') == -1: return None dimension = t.split('(')[1].split(')')[0] return int(dimension) # Guess a schema type based on the postgres type def PGTypeToSchemaType(pgname, pgtype, pgextra): if pgextra.find('not null') != -1: required=True else: required=False fields=[(u'title', pgname), (u'description', pgname)] if pgtype == 'integer': seq = getSequenceId(pgextra) if seq: fields.append((u'readonly', True)) else: fields.append((u'required', required)) return ('schema.Int', fields) fields.append((u'required', required)) if pgtype == 'double precision': return 'schema.Float', fields elif pgtype == 'boolean': return 'schema.Bool', fields elif pgtype == 'date': return 'schema.Date', fields elif pgtype == 'text': return 'schema.Text', fields elif pgtype.find('timestamp') != -1: return 'schema.Datetime', fields else: fieldlen = getLengthFromType(pgtype) if fieldlen != None: fields.append((u'max_length', fieldlen)) return 'schema.TextLine', fields print """GENERAL = { 'namespace': '%s', 'sql_dialect': 'postgresql', 'target_folder': 'tables', 'form_library': 'z3c', # formlib or z3c 'z3c_layer': 'boston_pagelet_skin.IPageletLayer', } """ % NAMESPACE print "TABLES=[" for table in sys.argv[1:]: schema = grab_schema(table) print "\t{" print "\t\t'name': '%s'," % table print '\t\t# Options should be : traversal-standard, traversal-group, standard, group, grid' print "\t\t'stereotype': 'traversal-standard'," # TODO: Get the primary key properly column = schema[0] print "\t\t'primary_key': ['%s'], " % column[0] # Check to see if the primary key has a sequence seq = getSequenceId(column[2]) if seq: print "\t\t'primary_key_has_sequence': True," print "\t\t'primary_key_sequence_name': '%s'," % seq else: print "\t\t'primary_key_has_sequence': False," print "\t\t'columns': [" for column in schema: print "\t\t\t{" print "\t\t\t\t'colname': '%s'," % column[0] print "\t\t\t\t'dbtype': '%s'," % column[1] if column[2]: print '\t\t\t\t"dbextra": "%s",' % column[2] if column[1] == 'boolean': print "\t\t\t\t'mapping_type': 'MappingBool'," (stype, sextra) = PGTypeToSchemaType(column[0], column[1], column[2]) print "\t\t\t\t'schema_type': '%s'," % stype print "\t\t\t\t'schema_fields': {" for (k,v) in sextra: if v in [True, False]: v = str(v) elif type(v) == type(0): v = str(v) else: v = "'"+str(v)+"'" print "\t\t\t\t\t'%s': %s," % (k,v) print "\t\t\t\t}," print "\t\t\t}," print "\t\t]," print "\t}," print "]" # End of tables list <file_sep>/trunk/boston_pagelet_skin/skin.py # Very simple skin so that we can show our viewlets # Modification of Boston for a change import zope.interface from zope.viewlet.interfaces import IViewletManager, IViewlet from zope.viewlet.manager import ConditionalViewletManager from zope.app.boston import Boston import z3c.layer.pagelet import z3c.form.interfaces import z3c.formui.interfaces from layer import IPageletLayer class ISkin( IPageletLayer, Boston, z3c.formui.interfaces.IDivFormLayer ): pass class IListingHeadshot(IViewletManager): "Headshot on Listings" class ListingHeadshot(ConditionalViewletManager): zope.interface.implements(IListingHeadshot) <file_sep>/trunk/generator/templates/__init__.py # Just used to allow the folder to be imported <file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/static/ploneide-edit-bespin.js /* * This is an editor using the bespin editor */ "use strict"; (function($) { var EditorBespin = function(controller) { this.init_super(controller); this.draw = function() { var tabs = $("ul.css-tabs"); var fn_parts = this.controller.model_data.filename.split('/'); var li = $('<li><a href="#" title="' + this.controller.model_data.filename +'">' + fn_parts[fn_parts.length-1] + '<span class="closer">x</span></a></li>'); tabs.append(li); /* TODO: need to style tooltip. position is all wrong */ li.find('a').tooltip({'position': "bottom center", 'relative': true, 'z-index': 100}); var panes = $("div.panes"); var pane = $('<div class="pane"><div class="toolbar">TOOLBAR</div></div>'); var el = $('<div class="editarea"/>'); pane.append(el); panes.append(pane); li.find('.closer').bind('click', function(e) { /* remove tab and pane */ /* TODO: data changed and cleanups */ li.remove(); pane.remove(); var api = tabs.data("tabs"); tabs.tabs("div.panes > div", { 'onClick': function(e, ti){ try { $("div.panes .bespin")[ti].bespin.dimensionsChanged(); } catch (e) { // no event on first pass } return true; }}); return false; }); var controller = this.controller; // Setup bespin and load the data // TODO: I would like to set the theme to white here. I don't know how to do it // warning - do not use stealfocus here - messes up window positioning bespin.useBespin(el[0]).then(function(env) { var editor = env.editor; editor.value = controller.model_data.payload; editor.syntax = controller.model_data.syntax; editor.setLineNumber(1); // Only convert to tabs after it is drawn - otherwise bespin screws up. tabs.tabs("div.panes > div", {'initialIndex': null, 'onClick': function(e, ti){ try { $("div.panes .bespin")[ti].bespin.dimensionsChanged(); } catch (e) { // no event on first pass } return true; }}); // Select the current tab - this way of getting the api is not comfortable // why not env.api? var api = tabs.data("tabs"); var tab_count = tabs.children().length; api.click(tab_count -1); // Save env for later use - seems from docs that should already be set el[0].bespin = env; }, function(error) {alert(error);}); }; }; EditorBespin.prototype = new $.ploneide.Editor(); /* register the editor for each of the model types (defined in navigator.py) */ $.ploneide.register_view('js', EditorBespin, 100); $.ploneide.register_view('pt', EditorBespin, 100); $.ploneide.register_view('py', EditorBespin, 100); $.ploneide.register_view('css', EditorBespin, 100); $.ploneide.register_view('txt', EditorBespin, 100); $.ploneide.register_view('cfg', EditorBespin, 100); $.ploneide.register_view('zcml', EditorBespin, 100); })(jQuery); <file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/__init__.py from zope.i18nmessageid import MessageFactory _ = MessageFactory('ploneide.core') from interfaces import IPloneIDE from interfaces import IPloneIDEModel # These are for including code from plugins into the rendered view from browser.managers import PloneIDENavigatorViewletManager from browser.managers import PloneIDEJSViewletManager from browser.managers import PloneIDECSSViewletManager from browser.managers import PloneIDEToolViewletManager <file_sep>/trunk/gentest/README.txt Zope Instance to test Generator =============================== This folder is intended to operate as a generator test instance. In the area where you hold your zope instances: 1. Use zopeproject to create an area called gentest 2. Copy this folder over your new gentest instance Run the system: bin/paste serve debug.ini Go to manage site, and create a database adapter. Register the adapter using the IZopeDatabaseAdapter Interface with the name 'gentest'. Test it to make sure it works. Now you are ready to run the generator. Create a dsl file. Go to the src folder: run python $HOME/generator/z3gen.py filename.dsl This should create a folder: src/tables/table_name Restart the zope instance and see if it has been picked up. <file_sep>/trunk/generator/z3gen_search.py # Generate a search form. Will be registered on the container import z3gen_utilities import os, os.path TAB=' ' class Generator: def __init__(self, DSLModel, Table): self.DSLModel = DSLModel self.Table = Table self.TableName = Table['name'] self.field0name = Table['columns'][0]['colname'] self.interface_name = 'I%s%s' % (self.TableName[0].upper(), self.TableName[1:]) self.z3c_layer='' try: self.z3c_layer='layer="%s"\n\t\t' % self.DSLModel['GENERAL']['z3c_layer'] except: pass # Extract the primary key from the list of fields. Don't allow the user # to change this on the edit screens self.primary_key=Table.get('primary_key', None) if self.primary_key != None: if type(self.primary_key) == type([]): # primary key DSL syntax can be list of fields if len(self.primary_key) > 1: print 'Error - only handle the case of a single primary key' sys.exit(1) self.primary_key = self.primary_key[0] else: # For now assume that it is the first field if the generator needs one. # later this should be an error self.fields_excluding_key = Table['columns'][1:] self.primary_key = self.field0name print 'Assuming that the primary key is the first key field' self.search_columns = Table.get('search_columns', [self.primary_key]) self.list_columns = Table.get('list_columns', None) if not self.list_columns: self.list_columns = [ col['colname'] for col in Table['columns'][:5]] # Set the search columns back into the table Table['search_columns'] = self.search_columns Table['list_columns'] = self.list_columns # The columns in the search schema self.schema_columns = [ col for col in Table['columns'] if col['colname'] in self.list_columns] self.load_templates() def load_templates(self): """Load the template. Search for: templates/search_form_library_stereotype templates/search_form_library templates/search_stereotype templates/search Form library should be one of formlib or z3c (.form) """ stereotype = self.Table['stereotype'] form_library = self.DSLModel['GENERAL']['form_library'] import_paths=[ 'templates/search_%s_%s' % (form_library, stereotype), 'templates/search_%s' % (form_library), 'templates/search_%s' % (stereotype), 'templates/search'] self.templates = z3gen_utilities.ImportTemplate(import_paths) def filename(self): """Return the name of the file""" return '%s_search.py' % self.TableName def render(self): """Generate the required files""" file_content = self.templates.GenFile(self.DSLModel, self.Table, self) file_content = file_content.replace('\t', TAB) z3gen_utilities.ReplaceFile(self.DSLModel, self.Table, self.filename(), file_content, format="python") # configure.zcml entries self.genConfiguration() # Write out the template - don't do it if it already exists TemplatesPath = "%s%s%s%stemplates" % (self.DSLModel['GENERAL']['target_folder'], os.sep, self.Table['name'], os.sep) TemplateFile= TemplatesPath + os.sep + 'list.pt' if not os.path.exists(TemplateFile): template_content = self.templates.GenTemplate(self.DSLModel, self.Table, self) fh = open(TemplateFile, 'w') fh.write(template_content) fh.close() def genConfiguration(self): """The configure.zcml entries required""" file_content = self.templates.GenConfiguration(self.DSLModel, self.Table, self) self.Table['config'].append(file_content) <file_sep>/trunk/gentest/setup.py from setuptools import setup, find_packages setup(name='gentest', # Fill in project info below version='0.1', description="", long_description="", keywords='', author='', author_email='', url='', license='', # Get more from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=['Programming Language :: Python', 'Environment :: Web Environment', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', 'Framework :: Zope3', ], packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data=True, zip_safe=False, install_requires=['setuptools', 'ZODB3', 'ZConfig', 'zdaemon', 'zope.publisher', 'zope.traversing', 'zope.app.wsgi>=3.4.0', 'zope.app.appsetup', 'zope.app.zcmlfiles', # The following packages aren't needed from the # beginning, but end up being used in most apps 'zope.annotation', 'zope.copypastemove', 'zope.formlib', 'zope.i18n', 'zope.app.authentication', 'zope.app.session', 'zope.app.intid', 'zope.app.keyreference', 'zope.app.catalog', # The following packages are needed for functional # tests only 'zope.testing', 'zope.app.testing', 'zope.app.securitypolicy', # These are all added locally for the generated code 'z3c.pagelet', 'z3c.layer', 'z3c.form', 'z3c.formui', 'zope.rdb', 'zope.app.boston', 'zope.app.sqlscript', 'psycopgda', ], entry_points = """ [console_scripts] gentest-debug = gentest.startup:interactive_debug_prompt gentest-ctl = gentest.startup:zdaemon_controller [paste.app_factory] main = gentest.startup:application_factory """ ) <file_sep>/trunk/kg.locationfield/kg/locationfield/tests/test_erase.py import unittest import transaction from AccessControl.SecurityManagement import newSecurityManager, \ noSecurityManager from Testing import ZopeTestCase as ztc from Products.CMFCore.utils import getToolByName from Products.PloneTestCase.layer import PloneSiteLayer from kg.locationfield.tests.base import \ LocationFieldTestCase class TestErase(LocationFieldTestCase): # we use here nested layer for not to make an impact on # the rest test cases, this test case check uninstall procedure # thus it has to uninstall package which will be required to # be installed for other test cases class layer(PloneSiteLayer): @classmethod def setUp(cls): app = ztc.app() portal = app.plone # elevate permissions user = portal.getWrappedOwner() newSecurityManager(None, user) tool = getToolByName(portal, 'portal_quickinstaller') product_name = 'kg.locationfield' if tool.isProductInstalled(product_name): tool.uninstallProducts([product_name,]) # drop elevated perms noSecurityManager() transaction.commit() ztc.close(app) def afterSetUp(self): self.loginAsPortalOwner() def test_factoryTool(self): tool = getToolByName(self.portal, 'portal_factory') self.failIf('FormLocationField' in tool._factory_types.keys(), 'FormLocationField type is still in portal_factory tool.') def test_typesTool(self): tool = getToolByName(self.portal, 'portal_types') self.failIf('FormLocationField' in tool.objectIds(), 'FormLocationField type is still in portal_types tool.') def test_propertiesTool(self): tool = getToolByName(self.portal, 'portal_properties') navtree = tool.navtree_properties self.failIf('FormLocationField' in navtree.metaTypesNotToList, 'FormLocationField is still in metaTypesNotToList property.') site = tool.site_properties self.failIf('FormLocationField' in site.types_not_searched, 'FormLocationField is still in types_not_searched property.') def test_skinsTool(self): tool = getToolByName(self.portal, 'portal_skins') self.failIf('locationfield' in tool.objectIds(), 'There is still locationfield folder in portal_skins.') for path_id, path in tool._getSelections().items(): layers = [l.strip() for l in path.split(',')] self.failIf('locationfield' in layers, 'locationfield layer is still in %s.' % path_id) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestErase)) return suite <file_sep>/trunk/generator/templates/search.py import types from templet import stringfunction @stringfunction def GenFile(DSLModel, Table, View): """ from zope.interface import Interface from zope.component import getMultiAdapter from zope import schema from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile from zope.traversing.browser.interfaces import IAbsoluteURL from zc.table import table, column from ${DSLModel['GENERAL']['target_folder']}.${Table['name']} import MessageFactory as _ import ${View.TableName}_db from z3c.form import form, button Fields = form.field.Fields from z3c.formui.form import Form class ISearchActions(Interface): search = button.Button(title=u'Search') delete = button.Button(title=u'Delete') class ISearchSchema(Interface): "Search Interface for this Container" ${{ for row in [col for col in Table['columns'] if col['colname'] in Table['search_columns']]: out.append('\t%s = %s(' % (row['colname'], row['schema_type'])) for (k,v) in row['schema_fields'].items(): if k in ['readonly', 'required']: continue if type(v) in types.StringTypes: out.append("%s=_(u'%s'), " % (k,v)) else: out.append("%s=%s, " % (k,v)) out.append("required=False, ") if row.has_key('value_type'): out.append("\\n\t\tvalue_type=%s(" % row['value_type']) for (k,v) in row['value_type_fields'].items(): if type(v) in types.StringTypes: out.append("%s=_(u'%s'), " % (k,v)) else: out.append("%s=%s, " % (k,v)) out.append(') ') out.append(')\\n') }} class SearchBase(Form): template=ViewPageTemplateFile("templates/list.pt") fields = Fields(ISearchSchema) label = "Search" buttons = button.Buttons(ISearchActions) search_buttons=['search'] result_buttons=['delete'] # Don't look to the context object for data ignoreContext = True Columns = [ ${{ for row in [col for col in Table['columns'] if col['colname'] in Table['search_columns']]: if row['colname'] != View.primary_key: if row['dbtype'].find('character') == -1: out.append("\t\tcolumn.GetterColumn(title='%s', getter=lambda p,f: p.%s == None and '' or str(p.%s)),\\n" % (row['colname'], row['colname'], row['colname'])) else: out.append("\t\tcolumn.GetterColumn(title='%s', getter=lambda p,f: p.%s and p.%s.decode('latin1') or ''),\\n" % (row['colname'], row['colname'], row['colname'])) }} ] def idLink(self, item, formatter): return '<a href="%s/%s">%s</a>'%(self.context_absolute_url, item.${View.primary_key}, item.${View.primary_key}) def checkBox(self, item, formmater): return '<input class="noborder slaveBox" name="ids:list" id="%s" value="%s" type="checkbox">' % ( item.${View.primary_key}, item.${View.primary_key}) def __init__(self, context, request): super(SearchBase, self).__init__(context, request) self.results=[] self.context_absolute_url = getMultiAdapter((context, request), IAbsoluteURL) def renderResults(self): if not self.results: return '' # the first row references back into the class so the columns array must # be local to the class columns = [ column.GetterColumn(title="", getter=self.checkBox), column.GetterColumn(title="${View.primary_key}", getter=self.idLink), ] + self.Columns formatter = table.StandaloneFullFormatter(self.context, self.request, self.results, prefix="form", columns=columns) formatter.cssClasses['table'] = 'listing' return formatter() @button.handler(ISearchActions['search']) def handle_search(self, action): "Create the result set, but the Template formats them" data, errors = self.extractData() table = ${View.TableName}_db.${View.TableName}(self.context) self.results= table.Search(**data) @button.handler(ISearchActions['delete']) def handle_delete(self, action): # The items to delete must be read from the request.form list, # since they are not form widgets and are not on form_fields try: ids = self.request.form[u'ids'] except: return if len(ids) > 0: table = ${View.TableName}_db.${View.TableName}(self.context) for id in ids: table.Delete(${View.primary_key}=id) # CAN_EDIT_AFTER_THIS_LINE class Search(SearchBase): pass """ @stringfunction def GenConfiguration(DSLModel, Table, View): r""" <!-- Search Configuration --> <z3c:pagelet name="search.html" for=".interfaces.${View.interface_name}Container" class=".${View.TableName}_search.Search" permission="zope.ManageContent" ${View.z3c_layer} /> <browser:menuItem title="Search" for=".interfaces.${View.interface_name}Container" menu="zmi_views" action="search.html" permission="zope.ManageContent" /> """ @stringfunction def GenTemplate(DSLModel, Table, View): r""" <h1 tal:content="view/label" i18n:translate="">Contents</h1> <div class="summary" tal:condition="view/status" tal:content="view/status" i18n:translate="">Status</div> <form class="edit-form" enctype="multipart/form-data" method="post" action="." tal:attributes="action request/URL"> <table> <tal:block omit-tag="" repeat="widget view/widgets/values"> <tr metal:define-macro="formrow" class="row" tal:condition="python:widget.mode != 'hidden'"> <td class="label" metal:define-macro="labelcell"> <label tal:attributes="for widget/id"> <span i18n:translate="" tal:content="widget/label"> label </span> <span class="required" tal:condition="widget/required"> * </span> </label> </td> <td class="field" metal:define-macro="widgetcell"> <div class="widget" tal:content="structure widget/render"> <input type="text" /> </div> <div class="error" tal:condition="widget/error"> <span tal:replace="structure widget/error"> error </span> </div> </td> </tr> </tal:block> </table> <div class="buttons"> <input tal:repeat="action view/search_buttons" tal:replace="structure python:view.actions[action].render()" /> </div> </form> <form tal:condition="view/renderResults" class="edit-form" enctype="multipart/form-data" method="post" action="." tal:attributes="action request/URL"> <h2>Search Results</h2> <span tal:replace="structure view/renderResults"></span> <div class="buttons"> <input tal:repeat="action view/result_buttons" tal:replace="structure python:view.actions[action].render()" /> </div> </form> """ <file_sep>/trunk/gentest/debug.ini [filter-app:main] # Change the last part from 'ajax' to 'pdb' for a post-mortem debugger # on the console: use = egg:z3c.evalexception#ajax next = zope [app:zope] use = egg:gentest [server:main] use = egg:Paste#http host = 0.0.0.0 port = 8080 <file_sep>/trunk/generator/z3gen.py #!/usr/bin/env python # z3gen.py # # WARNING: This module evaluates the dsl using the python interpreter # Only run this code on a file you are complete sure of # # This is a very simple generator for building content types # which are stored in the database. # # The generation works from a dsl file. # # You can generate a dsl file from a postgres database using the # psql2dsl.py command # szUsage="Usage: python zope3gen.py [options] dslfile\n" import sys, os import z3gen_utilities ####################################################################################### # Process the command line and get the DSLModel cmd_args=z3gen_utilities.parseCmdLine(sys.argv[1:]) dsl_filenames=cmd_args[1] if len(dsl_filenames) != 1: sys.stderr.write(szUsage) sys.exit(1) # Load the model from the DSL File dsl_filename=dsl_filenames[0] DSLModel={} execfile(dsl_filename, DSLModel) # Modify the model with any command line arguments (these affect the general section) for (k,v) in cmd_args[0]: DSLModel['GENERAL'][k]=v ####################################################################################### # Load the generators and generate import z3gen_interfaces import z3gen_dbclass import z3gen_content import z3gen_views import z3gen_search import templates.literal GENERATORS=[ z3gen_interfaces.Generator, z3gen_dbclass.Generator, z3gen_content.Generator, z3gen_views.Generator, z3gen_search.Generator, ] for Table in DSLModel['TABLES']: z3gen_utilities.BuildPath(DSLModel, Table) z3gen_utilities.AddNewPackage(DSLModel['GENERAL']['target_folder'], Table['name'], DSLModel['GENERAL']['namespace']) Table['config'] = [] # The generators can put configuration stuff here # These are the important generators - they output their own files for generator in GENERATORS: view = generator(DSLModel, Table) view.render() content = templates.literal.db_file(DSLModel, Table) z3gen_utilities.ReplaceFile(DSLModel, Table, 'db.py', content, format="python") content = templates.literal.config_file(DSLModel, Table) z3gen_utilities.ReplaceFile(DSLModel, Table, 'configure.zcml', content, format="zcml") content = templates.literal.init_file(DSLModel, Table) z3gen_utilities.ReplaceFile(DSLModel, Table, '__init__.py', content, format="python") content = templates.literal.schema_helpers(DSLModel, Table) z3gen_utilities.ReplaceFile(DSLModel, Table, 'schema_helpers.py', content, format="python") <file_sep>/trunk/gentest/src/boston_pagelet_skin/skin.py # Very simple skin so that we can show our viewlets # Modification of Boston for a change from zope.viewlet.interfaces import IViewletManager, IViewlet from zope.app.boston import Boston import z3c.layer.pagelet import z3c.form.interfaces import z3c.formui.interfaces from layer import IPageletLayer class ISkin( IPageletLayer, Boston, z3c.formui.interfaces.IDivFormLayer ): pass <file_sep>/trunk/gentest/deploy.ini [app:main] use = egg:gentest [server:main] use = egg:Paste#http host = 0.0.0.0 port = 8080 <file_sep>/trunk/utility/ump/interfaces.py from zope.interface import Interface, Attribute class IExternalObjectFolder(Interface): pass class IExternalObject(Interface): """The External Object Adapter Interface""" def Create(): """Create the object externally, and return the instance data which is required by the read method to reload it""" def Read(self, init_data): """Reload the data from the external object init data""" def Update(self): """Update the external data if changed""" pass def Delete(self): """Delete the external data""" pass <file_sep>/trunk/collective.editor/collective/editor/browser/editor_static/editor_core.js /* * Core functions for the editor */ $(document).ready(function() { /* Initialise the Page Layout */ $("#simple-editor-layout").splitter({ splitVertical: true, outline: true, sizeLeft: true, resizeToWidth: true }); $("#simple-editor-layout #main").splitter({ splitHorizontal: true, outline: true, sizeTop: true }); $('#simple-editor-layout #main #top').bind('resize', function(e, size) { $('div.bespin').each(function(i, el) {var env = el.bespin; env.dimensionsChanged();}); return true; }); $("#navigation-pane").tabs("#navigation-pane div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null}); var url_pathname = window.location.pathname; var process_file = function(title, path) { $.ajax({ url: url_pathname, type: 'GET', dataType: 'json', data: {'requestType': 'ajax', 'requestId': 'getFile', 'filename': path}, success: function(xml){ var tabs = $("ul.css-tabs"); var fn_parts = xml.filename.split('/'); var li = $('<li><a href="#" title="' + xml.filename +'">' + fn_parts[fn_parts.length-1] + '<span class="closer">x</span></a></li>'); tabs.append(li); /* TODO: need to style tooltip. position is all wrong */ li.find('a').tooltip({'position': "bottom center", 'relative': true, 'z-index': 100}); var panes = $("div.panes"); var pane = $('<div class="pane"><div class="toolbar">TOOLBAR</div></div>'); var el = $('<div class="editarea"/>'); pane.append(el); panes.append(pane); li.find('.closer').bind('click', function(e) { /* remove tab and pane */ /* TODO: data changed and cleanups */ li.remove(); pane.remove(); var api = tabs.data("tabs"); tabs.tabs("div.panes > div", { 'onClick': function(e, ti){ try { $("div.panes .bespin")[ti].bespin.dimensionsChanged(); } catch (e) { // no event on first pass } return true; }}); return false; }); // Setup bespin and load the data // TODO: I would like to set the theme to white here. I don't know how to do it // warning - do not use stealfocus here - messes up window positioning bespin.useBespin(el[0]).then(function(env) { var editor = env.editor; editor.value = xml.payload; editor.syntax = xml.syntax; editor.setLineNumber(1); // Only convert to tabs after it is drawn - otherwise bespin screws up. tabs.tabs("div.panes > div", {'initialIndex': null, 'onClick': function(e, ti){ try { $("div.panes .bespin")[ti].bespin.dimensionsChanged(); } catch (e) { // no event on first pass } return true; }}); // Select the current tab - this way of getting the api is not comfortable // why not env.api? var api = tabs.data("tabs"); var tab_count = tabs.children().length; api.click(tab_count -1); // Save env for later use - seems from docs that should already be set el[0].bespin = env; }, function(error) {alert(error);}); } }); }; var process_project = function(title, path) { alert('project' + path); }; var process_folder = function(title, path) { alert('folder' + path); }; /* Load the file system file info into a jstree */ $("#tree").jstree({ "json_data" : { "ajax" : { "url": url_pathname, "data" : function (n) { return { 'id' : n.attr ? n.attr("id") : 0, 'requestType': 'ajax', 'requestId': 'getNavigation' }; } }, }, "plugins" : [ "themes", "json_data" ] }); /* PROBLEM HERE _ HOW TO HANDLE CLICK ON A FILE */ $("#tree a").live("click", function(e) { var href = $(this).parent()[0].id; var linktype = href.split(':')[0]; var title = $(this).text(); if (linktype == 'file') { process_file(title, href.substr(5)); } else if (linktype == 'folder') { process_folder(title, href.substr(7)); } else if (linktype == 'project') { process_project(title, href.substr(8)); } else { alert ("You activated " + title + ", key=" + href); } return false; }); // setup ul.tabs to work as tabs for each div directly under div.panes $("ul.tabs").tabs("div.panes > div"); }); <file_sep>/trunk/generator/templates/views_z3c.py from templet import stringfunction @stringfunction def GenFile(DSLModel, Table, View): """ from zope.component import getMultiAdapter from zope.app.container.interfaces import INameChooser from zope.app.container.interfaces import IAdding from zope.traversing.browser.interfaces import IAbsoluteURL from z3c.form import form from z3c.formui.form import EditForm, AddForm, DisplayForm Fields = form.field.Fields import ${View.TableName}_content from interfaces import ${View.interface_name} class AddBase(AddForm): label="Add: ${View.TableName}" fields = Fields(${View.interface_name})${View.create_omit} def __init__(self, context, request): super(AddBase, self).__init__(context, request) if IAdding.providedBy(self.context): self.container = self.context.context else: self.container = self.context def create(self, data): # Create object newobj = ${View.TableName}_content.${View.TableName}() ${{ for row in Table['columns']: if row['colname'] == View.primary_key: continue out.append("\t\tnewobj.%s = data['%s']\\n" % (row['colname'], row['colname'])) }} # Name it - must be done at this stage for event subscribers nc = INameChooser(self.container) newobj.__name__ = nc.chooseName('', newobj) return newobj def add(self, object): self.new_object_id = object.__name__ self.container[object.__name__] = object return object def nextURL(self): container_url = getMultiAdapter((self.container, self.request), IAbsoluteURL) return '%s/%s/index.html'% (str(container_url), self.new_object_id) class EditBase(EditForm): label="Edit: ${View.TableName}" fields = Fields(${View.interface_name})${View.update_omit} class ViewBase(DisplayForm): label="View: ${View.TableName}" fields = Fields(${View.interface_name})${View.update_omit} # CAN_EDIT_AFTER_THIS_LINE ${{ for classname in View.classnames: out.append('class %s(%sBase):\\n' % (classname, classname)) out.append('\tpass\\n\\n') }} """ @stringfunction def GenConfiguration(DSLModel, Table, View): r""" <!-- View Configuration --> <z3c:pagelet name="index.html" for=".interfaces.${View.interface_name}" class=".${View.TableName}_views.View" permission="zope.Public" ${View.z3c_layer}/> <browser:menuItem title="View" for=".interfaces.${View.interface_name}" menu="zmi_views" action="@@index.html" permission="zope.Public" /> <z3c:pagelet name="edit.html" for=".interfaces.${View.interface_name}" class=".${View.TableName}_views.Edit" permission="zope.Public" ${View.z3c_layer}/> <browser:menuItem title="Edit" for=".interfaces.${View.interface_name}" menu="zmi_views" action="@@edit.html" permission="zope.ManageContent" /> <z3c:pagelet for="zope.app.container.interfaces.IAdding" name="add${View.TableName}.html" class=".${View.TableName}_views.Add" permission="zope.ManageContent" ${View.z3c_layer}/> <browser:addMenuItem title="Add ${View.TableName}" class=".${View.TableName}_content.${View.TableName}" permission="zope.ManageContent" view="add${View.TableName}.html" ${View.z3c_layer}/> <browser:containerViews for=".interfaces.${View.interface_name}Container" add="zope.ManageContent" contents="zope.View" index="zope.View" ${View.z3c_layer}/> """ <file_sep>/trunk/boston_pagelet_skin/__init__.py from layer import IPageletLayer from skin import ISkin <file_sep>/trunk/collective.editor/collective/editor/TODO.txt Well write the program These are bugs/workarounds which need to be backed out. 1. Could not get skin resource folder to work in Plone 3.3.5 - renamed to dskin 2. Could not get default static folder to work in Plone 3.3.5 - manually created 3. Dynatree needs jquery.ui - not part of Plone 4 switch to jstree <file_sep>/trunk/generator/examples/testschema.sql create table basic_types_test ( id serial, name varchar(20), salary float, startdate date, lastloging timestamp, initial char, initials char(3), biography text, lunchtime time, likeswork boolean ); <file_sep>/trunk/generator/z3gen_interfaces.py # Generator for interfaces import z3gen_utilities TAB=' ' class Generator: def __init__(self, DSLModel, Table): self.DSLModel = DSLModel self.Table = Table self.TableName = Table['name'] self.interface_name = 'I%s%s' % (self.TableName[0].upper(), self.TableName[1:]) self.load_templates() # Extract the primary key from the list of fields for separate # processing if required self.primary_key=Table.get('primary_key', None) if self.primary_key != None: if type(self.primary_key) == type([]): # primary key DSL syntax can be list of fields if len(self.primary_key) > 1: print 'Error - only handle the case of a single primary key' sys.exit(1) self.primary_key = self.primary_key[0] else: # For now assume that it is the first field if the generator needs one. # later this should be an error self.fields_excluding_key = Table['columns'][1:] self.primary_key = self.field0name print 'Assuming that the primary key is the first key field' def load_templates(self): """Load the template. Search for: templates/interfaces_stereotype templates/interfaces """ stereotype = self.Table['stereotype'] import_paths=['templates/interfaces_%s' % stereotype, 'templates/interfaces'] self.templates = z3gen_utilities.ImportTemplate(import_paths) def filename(self): """Return the name of the file""" return 'interfaces.py' def render(self): """Return a string containing the generated file""" self.classnames=[] self.classnames.append(self.interface_name) self.classnames.append('%sContainer' % self.interface_name) file_content = self.templates.GenFile(self.DSLModel, self.Table, self) file_content = file_content.replace('\t', TAB) z3gen_utilities.ReplaceFile(self.DSLModel, self.Table, self.filename(), file_content, format="python") <file_sep>/trunk/kg.locationfield/kg/locationfield/tests/base.py from Testing import ZopeTestCase as ztc from Products.Five import zcml from Products.Five import fiveconfigure from Products.PloneTestCase import PloneTestCase as ptc from Products.PloneTestCase.layer import onsetup ztc.installProduct('PloneFormGen') @onsetup def setup_package(): # roadrunner is not working without these 2 lines import Products.PloneFormGen zcml.load_config('configure.zcml', Products.PloneFormGen) fiveconfigure.debug_mode = True import kg.locationfield zcml.load_config('configure.zcml', kg.locationfield) fiveconfigure.debug_mode = False ztc.installPackage('kg.locationfield') setup_package() ptc.setupPloneSite(products=['kg.locationfield',]) class LocationFieldTestCase(ptc.PloneTestCase): """Common test base class""" class LocationFieldFunctionalTestCase(ptc.FunctionalTestCase): """Common functional test base class""" <file_sep>/trunk/kg.locationfield/kg/locationfield/tests/test_setup.py import unittest from Products.CMFCore.utils import getToolByName from kg.locationfield.tests.base import \ LocationFieldTestCase class TestSetup(LocationFieldTestCase): def afterSetUp(self): self.loginAsPortalOwner() def test_installerTool(self): tool = getToolByName(self.portal, 'portal_quickinstaller') self.failUnless(tool.isProductInstalled('PloneFormGen'), 'PloneFormGen product is not installed.') def test_factoryTool(self): tool = getToolByName(self.portal, 'portal_factory') self.failUnless('FormLocationField' in tool._factory_types.keys(), 'FormLocationField type is not in portal_factory tool.') def test_typesTool(self): tool = getToolByName(self.portal, 'portal_types') self.failUnless('FormLocationField' in tool.objectIds(), 'FormLocationField type is not in portal_types tool.') def test_propertiesTool(self): tool = getToolByName(self.portal, 'portal_properties') navtree = tool.navtree_properties self.failUnless('FormLocationField' in navtree.metaTypesNotToList, 'FormLocationField is not in metaTypesNotToList property.') site = tool.site_properties self.failUnless('FormLocationField' in site.types_not_searched, 'FormLocationField is not in types_not_searched property.') def test_skinsTool(self): tool = getToolByName(self.portal, 'portal_skins') self.failUnless('locationfield' in tool.objectIds(), 'There is no locationfield folder in portal_skins.') for path_id, path in tool._getSelections().items(): layers = [l.strip() for l in path.split(',')] self.failUnless('locationfield' in layers, 'locationfield layer is not registered for %s.' % path_id) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestSetup)) return suite <file_sep>/trunk/utility/ump/folder.py # Simple folder implementation # # The folder must provide the standard folder services # However, when an object is referenced that is not in # memory, the folder will attempt to load it # Note on caching - this module piggybacks on the ZODB # cache. When ZODB cache is cleared (i.e. reload) these # objects will be recycled. import sys, time import transaction from persistent import Persistent from zope.interface import Interface, implements, alsoProvides from zope.component import adapts, queryMultiAdapter from zope.location.interfaces import ILocation from zope.exceptions import DuplicationError from zope.publisher.interfaces import NotFound from zope.app.folder import folder from zope.app.container.contained import setitem, uncontained from interfaces import IExternalObjectFolder, IExternalObject ECHO=False #----------------------------------------------------------------------------------- class FolderDataManager: """This is a simple DataManager. It's purpose is to call the adapter to call its update method if an attribute is modified. I am using this to trigger calls to the SQL database, so I expect that second transaction manager to manage the conflicts etc. It would be useful for alternative deployments to allow this datamanager to be easily pluggable """ transactions={} def abort(self, transaction): pass def tpc_begin(self, transaction): pass def commit(self, transaction): pass def onBeforeCommit(self, transaction): """This handler is called before the commit. It executes the update actions for any updated objects. It must be called before the commit or vote since it may cause a new transaction handler to join the transaction""" try: changed_objects = self.transactions[transaction] except: return for o in changed_objects: adapter = o._v_external_object_adapter adapter.Update() o._p_changed = False def tpc_vote(self, transaction): pass def tpc_finish(self, transaction): del self.transactions[transaction] def tpc_abort(self, transaction): try: changed_objects = self.transactions[transaction] except: return for o in changed_objects: ref = o._v_external_object_reference ref._v_realInstance = None # orphan it def sortKey(self): return 1 def register(self, object): """Register an object with the data manager - in theory this should be called by the persistent module when the object is changed""" txn = transaction.get() if txn not in self.transactions: self.transactions[txn] = [] txn.join(self) txn.addBeforeCommitHook(self.onBeforeCommit, args=(txn,)) self.transactions[txn].append(object) #----------------------------------------------------------------------------------- # Simple data manager for basic use. Replace this on your subclass of one of the folders # below. _gFDM=FolderDataManager() #----------------------------------------------------------------------------------- class Broken(object): """A class to be returned if the object cannot be imported""" # TODO #----------------------------------------------------------------------------------- # This ObjectReference is used for transient objects. Here the key is not # stored on the database. class TransientObjectReference(object): """This is the actual reference to the object which is stored in the Folder, where they persistence is managed externally""" modulename = None globalname = None init_data = None def __init__(self, modulename, globalname, container, name, init_data): """Create the initial reference. This is only called when the object is added to the folder""" self.modulename = modulename self.globalname = globalname # Copy location information self.__parent__ = container self.__name__ = str(name) self.init_data = init_data def delInst(self): """Delete the object""" self._v_external_object_adapter.Delete() def setInst(self, inst, name): """Set the instance object""" # Locate it inst.__name__ = self.__name__ inst.__parent__ = self.__parent__ alsoProvides(inst, ILocation) # Now need to get an adapter adapter = queryMultiAdapter((inst, self.__parent__), IExternalObject) if adapter is None: print 'could not load source for ', self.modulename, self.globalname return inst._v_external_object_reference = self inst._v_external_object_adapter = adapter self._v_external_object_adapter = adapter self._v_realInstance = inst # Connect to data manager inst._p_jar = self.__parent__._DM() # Trigger the create method on the adapter self._v_external_object_adapter.Create(name=name) def getInst(self): """broken.py in the ZODB is the key point for creating objects - this is it's approach""" if hasattr(self, '_v_realInstance'): if self._v_realInstance is not None: return self._v_realInstance klass = None try: __import__(self.modulename) except ImportError: pass else: module = sys.modules[self.modulename] try: klass = getattr(module, self.globalname) except AttributeError: pass if klass is None: print 'could not load source for ', self.modulename, self.globalname return Broken() inst = klass.__new__(klass) if ECHO: print '***** Created object ****', inst # Locate it inst.__name__ = str(self.__name__) inst.__parent__ = self.__parent__ alsoProvides(inst, ILocation) # Now need to get an adapter adapter = queryMultiAdapter((inst, self.__parent__), IExternalObject) if adapter is None: print 'could not load source for ', self.modulename, self.globalname return Broken() inst._v_external_object_reference = self inst._v_external_object_adapter = adapter self._v_external_object_adapter = adapter self._v_realInstance = inst # Initialise the data self._v_external_object_adapter.Read(self.init_data) # Connect to data manager inst._p_jar = self.__parent__._DM() # Return the class return self._v_realInstance # This must subclass Persistent or the _v_ attributes are stored. class ObjectReference(Persistent, TransientObjectReference): """This is the actual reference to the object which is stored in the Folder, where they persistence is managed externally""" modulename = None globalname = None init_data = None def __init__(self, context, container, adapter): """Create the initial reference. This is only called when the object is added to the folder""" self.modulename = context.__class__.__module__ self.globalname = context.__class__.__name__ context._v_external_object_reference = self context._v_external_object_adapter = adapter self._v_external_object_adapter = adapter self._v_realInstance = context # Copy location information self.__parent__ = context.__parent__ self.__name__ = str(context.__name__) # Connect to data manager context._p_jar = self.__parent__._DM() # self.init_data is initialised by Create() self.init_data = adapter.Create() #----------------------------------------------------------------------------------- class Folder(folder.Folder): """A Folder which handles the User Mode Peristence. The mapped object is either a standard Zope object or it is a reference to an object whos persistence is managed by the application """ # Marker interface for adapter implements(IExternalObjectFolder) def _DM(self): """Return the data manager object""" return _gFDM def incarnate_object(self, reference): """Given the ObjectReference, return an object""" if ECHO: print 'Folder:incarnate_object', reference if type(reference) != ObjectReference: # Just a stored object return reference return reference.getInst() def object_toStoredForm(self, object): """Given an object, either do user mode persistence and return a reference or return the object""" if ECHO: print 'Folder:toStoredForm', object if hasattr(object, '_v_external_object_reference'): # Already bound return object._v_external_object_reference # Is there an adapter for it rv = queryMultiAdapter((object, self), IExternalObject) if rv is not None: # This is a create - if the object had been loaded from the # database it would already have an __v_external_object_reference reference = ObjectReference(object, self, rv) return reference # Default - just store the object return object def values(self): """Return a sequence-like object containing the objects that appear in the folder. """ if ECHO: print 'Folder:values' for val in self.data.values(): yield self.incarnate_object(val) def items(self): """Return a sequence-like object containing tuples of the form (name, object) for the objects that appear in the folder. """ if ECHO: print 'Folder:items' for (k,v) in self.data.items(): yield(k, self.incarnate_object(v)) def __getitem__(self, name): """Return the named object, or raise ``KeyError`` if the object is not found. """ if ECHO: print 'Folder:__getitem__', name obj = self.data[name] rv = self.incarnate_object(obj) if ECHO: print 'Folder:__getitem__ returning ',rv return rv def get(self, name, default=None): """Return the named object, or the value of the `default` argument if the object is not found. """ if ECHO: print 'Folder:get', name obj = self.data.get(name, default) return self.incarnate_object(obj) def __setitem__(self, name, object): """Add the given object to the folder under the given name.""" if ECHO: print 'Folder:setitem' if not (isinstance(name, str) or isinstance(name, unicode)): raise TypeError("Name must be a string rather than a %s" % name.__class__.__name__) try: unicode(name) except UnicodeError: raise TypeError("Non-unicode names must be 7-bit-ascii only") if not name: raise TypeError("Name must not be empty") if name in self.data: raise DuplicationError("name, %s, is already in use" % name) # TODO: need to change setitem so that events are fired for the object, # not the object stored form - override the __setitem__ method of self.data setitem(self, self.set_data_item, name, object) def set_data_item(self, name, object): if ECHO: print 'Folder:set_data_item' newobj = self.object_toStoredForm(object) self.data.__setitem__(name, newobj) def __delitem__(self, name): """Delete the named object from the folder. Raises a KeyError if the object is not found.""" if ECHO: print 'Folder:__delitem__' # Have to pull in the object to make this happen object = self.get(name) if hasattr(object, '_v_external_object_reference'): object._v_external_object_reference.delInst() object._v_external_object_reference = None try: uncontained(self.data[name], self, name) except: pass del self.data[name] def clear_cache(self): """For test purposes""" for ref in self.data.values(): if ref is not None and hasattr(ref, _v_realInstance): ref._v_realInstance = None # orphan it class ExternalFolder(folder.Folder): """This folder should not have a persistent data attribute. The keys are retrieved from an external location, i.e. a database table primary keys. The storage should be efficiently mapped, i.e. inserts/deletes should log to an external table to track modification date/time. Assumes the row modifications do not change the primary key Subclass must set up the modulename, globalname and reload Note: Externally keys are strings, internally they are integers """ # Marker interface for adapter implements(IExternalObjectFolder) modulename=None # Set by inheritance globalname=None def _DM(self): """Return the data manager object""" return _gFDM def need_reload(self): """Default - reload after 2 minutes. If mapped to a relational database, underlying table should utilitise triggers on insert/delete to track table modification times to allow this to me more efficient""" try: last_load_time = self._v_last_load_time except: return True age = time.time() - last_load_time if age > 120: return True return False def reload(self): """Reload the underlying data. Return a list of primary keys""" raise NotImplemented, 'reload' def verify_data(self): """Ensure that the _v_data is setup""" if not hasattr(self, '_v_data'): self._v_data = {} data_list = self.reload() for k in [int(k) for k in data_list]: self._v_data[k] = None self._v_last_load_time = time.time() return if self.need_reload(): data_list = self.reload() """Use sets to find items added and removed""" old_keys = set(self._v_data.keys()) new_keys = set([int(k) for k in data_list]) for k in old_keys - new_keys: del self._v_data[k] for k in new_keys - old_keys: self._v_data[k] = None self._v_last_load_time = time.time() def incarnate_object(self, key): """Given the ObjectReference, return an object""" if ECHO: print 'ExternalFolder:incarnate_object', key self.verify_data() try: key = int(key) except: raise KeyError, key # If the object is not in the _v_data, check the database # directly again. This will add it into the _v_data if it exists try: reference = self._v_data[key] except: reference = None if reference is None: try: reference = TransientObjectReference(self.modulename, self.globalname, self, key, key) self._v_data[int(key)] = reference except: raise KeyError, key reference = self._v_data[int(key)] return reference.getInst() def values(self): """Return a sequence-like object containing the objects that appear in the folder. """ if ECHO: print 'ExternalFolder:values' self.verify_data() for key in self._v_data.keys(): yield self.incarnate_object(val) def items(self): """Return a sequence-like object containing tuples of the form (name, object) for the objects that appear in the folder. """ if ECHO: print 'ExternalFolder:items' self.verify_data() for k in self._v_data.keys(): yield(str(k), self.incarnate_object(k)) def __getitem__(self, name): """Return the named object, or raise ``KeyError`` if the object is not found. """ if ECHO: print 'ExternalFolder:__getitem__', name rv = self.incarnate_object(name) if ECHO: print 'ExternalFolder:__getitem__ returning ',rv return rv def get(self, name, default=None): """Return the named object, or the value of the `default` argument if the object is not found. """ if ECHO: print 'ExternalFolder:get', name try: return self.incarnate_object(name) except: return default def __setitem__(self, name, object): """Add the given object to the folder under the given name. Note, the map is from ids to reference objects, not actual objects.""" if ECHO: print 'ExternalFolder:setitem' self.verify_data() reference = TransientObjectReference(self.modulename, self.globalname, self, name, name) reference.setInst(object, name) self._v_data[int(name)] = reference def __delitem__(self, name): """Delete the named object from the folder. Raises a KeyError if the object is not found.""" if ECHO: print 'ExternalFolder:__delitem__' self.verify_data() reference = self._v_data[int(name)] # Trigger the delete method on the adapter reference.delInst() del self._v_data[int(name)] def __len__(self): self.verify_data() return len(self._v_data) def clear_cache(self): """For test purposes""" for ref in self._v_data.values(): if ref is not None and hasattr(ref, '_v_realInstance'): ref._v_realInstance = None # orphan it <file_sep>/trunk/generator/z3gen_utilities.py # Some utility functions import os, os.path PYTHON_MARKER = "# CAN_EDIT_AFTER_THIS_LINE" ZCML_MARKER = "<!-- CAN_EDIT_AFTER_THIS_LINE -->" def parseCmdLine(cmdLine): """Roll my own parser, so that I don't have to be final about the valid options""" files=[] modifiers=[] for i in range(len(cmdLine)): arg = cmdLine[i] if arg[:2] != '--': files = cmdLine[i:] return (modifiers, files) arg = arg[2:] parts = arg.split('=',1) modifiers.append((parts[0], parts[1])) return (modifiers, files) def BuildPath(DSLModel, table): """Create target folders if necessary""" folders = [ DSLModel['GENERAL']['target_folder'], "%s%s%s" % (DSLModel['GENERAL']['target_folder'], os.sep, table['name']) ] for folder in folders: if not os.path.exists(folder): os.mkdir(folder) init_path = folder + os.sep + '__init__.py' if not os.path.exists(init_path): fh = open(init_path, 'w') fh.write('# Module Initialiation File') fh.close() TemplatesPath = "%s%s%s%stemplates" % (DSLModel['GENERAL']['target_folder'], os.sep, table['name'], os.sep) if not os.path.exists(TemplatesPath): os.mkdir(TemplatesPath) def MergeUserChanges(oldcontent, newcontent, marker): """Copy user changes from old file to new file. User changes are signified by a comment, PYTHON_MARKER or ZCML_MARKER """ oldlines = oldcontent.split('\n') oldedits = None for i in range(len(oldlines)): line = oldlines[i] if line.find(marker) != -1: oldedits = oldlines[i+1:] if not oldedits: # Nothing in the old return newcontent newlines = newcontent.split('\n') for i in range(len(newlines)): line = newlines[i] if line.find(marker) != -1: # Found it - append and return newlines = newlines[:i+1] + oldedits return '\n'.join(newlines) return newcontent def FileExists(DSLModel, table, filename): """Test whether a file exists""" fullpath="%s%s%s%s%s" % (DSLModel['GENERAL']['target_folder'], os.sep, table['name'], os.sep, filename) return os.access(fullpath, os.F_OK) def ReplaceFile(DSLModel, table, filename, content, format="python"): fullpath="%s%s%s%s%s" % (DSLModel['GENERAL']['target_folder'], os.sep, table['name'], os.sep, filename) # replace tabs - more convenient for editing after content = content.replace('\t', ' ') if os.access(fullpath, os.F_OK): # File already exists. # First merge any changes from the original file into content fh = open(fullpath) oldcontent = fh.read() fh.close() if format == 'python': content = MergeUserChanges(oldcontent, content, marker=PYTHON_MARKER) elif format == 'zcml': content = MergeUserChanges(oldcontent, content, marker=ZCML_MARKER) if content == oldcontent: return # No change # Back-up old file backup=fullpath+'~' if os.access(backup, os.F_OK): os.unlink(backup) os.rename(fullpath, backup) fh = open(fullpath, 'w') fh.write(content) fh.close() def AddNewPackage(path, package_name, namespace): """Add the new package to the list of packages. Will normally be there already.""" new_line = '<include package=".%s" />' % package_name fullpath=path + '/configure.zcml' try: fh=open(fullpath) lines=fh.readlines() for i in range(len(lines)): if len(lines[i]) == 0: continue if lines[i][-1] in ['\n', '\r']: lines[i] = lines[i][:-1] if len(lines[i]) == 0: continue if lines[i][-1] in ['\n', '\r']: lines[i] = lines[i][:-1] fh.close() except: lines=[ '<configure', '\txmlns="http://namespaces.zope.org/zope"', '\ti18n_domain="%s">\n' % namespace, '\t<!-- END OF PACKAGES -->', '\n</configure>'] # See if our file is present for l in lines: if l.find(new_line) != -1: return # all done # Find the marker and insert at that point for i in range(len(lines)): l = lines[i] if l.find('<!-- END OF PACKAGES -->') != -1: lines = lines[:i] + ['\t'+new_line] + lines[i:] break # rewrite the file if os.access(fullpath, os.F_OK): backup=fullpath+'~' if os.access(backup, os.F_OK): os.unlink(backup) os.rename(fullpath, backup) fh = open(fullpath, 'w') fh.write('\n'.join([l.replace('\t', ' ') for l in lines])) fh.close() def ImportTemplate(template_names): """Work through the names and try each until an import works. Then return the imported file""" for file in template_names: try: return __import__(file) except ImportError: pass raise ImportError, 'No files matching %s' % template_names <file_sep>/trunk/utility/ump/README.txt UMP - User Mode Persistence =========================== This module implements a set of hooks for implementing a persistent object simply. The notion is that you can implement the object as a standard Zope3 object and later implement your own persistence adapter to manage it. interfaces.IExternalObjectFolder -------------------------------- This is a marker interface on the container. This interface indicates that it supports the external object storage. The actual implementation of that external object storage is determined by a user provided adapter. interfaces.IExternalObject -------------------------- This is the interface implemeneted by your adapter. You must adapt a container and your object to provide this interface: queryMultiAdapter((object, container), IExternalObject) folder.Folder ------------- This is a folder which implements the IExternalObjectFolder interface. If an adapter is provided for an object which is stored in the folder, then it will store a reference to an external object. Otherwise it stores the object. folder.ExternalFolder --------------------- This folder is intended to map a set of items where the ids are stored externally, i.e. for mapping to a folder or database table. folder.FolderDataManager ------------------------ This data manager is connected to the object via the Persistence class. This object calls back to the adapter Update() method where the underlying object has been modified in a transaction. This data manager does not implement conflict management. The underlying object will probably be subject to another datamanager, e.g. mapped to a relational database, so conflict management at this level would be obsolete. The Data manager is returned by the _DM() method on the folder, so it can be easily replaced on subclasses of folder. <file_sep>/trunk/gentest/src/boston_pagelet_skin/layer.py # This is the layer for registering z3c.form and z3c.pagelets against import z3c.layer.pagelet import z3c.form.interfaces class IPageletLayer( z3c.form.interfaces.IFormLayer, z3c.layer.pagelet.IPageletBrowserLayer): pass <file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/interfaces.py # interfaces.py # # This file should contain the full set of public interfaces for the project. # These should be of use to plugin developers. from zope.interface import Interface class IPloneIDE(Interface): """This is a marker interface for the PloneIDE object.""" class IPloneIDEModel(Interface): """Interface to register handlers for different object types, e.g. 'python' for python files. Naming matches controllers on client side. The Interface will be located as : getMultiAdapter((IPloneIDE, request), IPloneIDEModel, name="python") """ def handle(type_name, method_name, params): """ The type_name will be the name underwhich the adapter was looked up. The same adapter can be registered from multiple type_names. The method_name is the name passed from the client, i.e. the javascript client. params are the parameters passed from the client """ <file_sep>/trunk/generator/templates/content.py from templet import stringfunction @stringfunction def GenFile(DSLModel, Table, View): """ from persistent import Persistent from zope.component import adapts from zope.interface import implements from zope.schema.fieldproperty import FieldProperty from zope.dublincore.zopedublincore import ZopeDublinCore from zope.dublincore.interfaces import IZopeDublinCore from zope.app.container.contained import NameChooser from utility.ump.folder import ExternalFolder from ${DSLModel['GENERAL']['target_folder']}.${Table['name']} import MessageFactory as _ from interfaces import ${View.interface_name}, ${View.interface_name}Container import ${Table['name']}_db class ${Table['name']}Base(Persistent): implements(${View.interface_name}) ${{ for column in Table['columns']: if column['colname'] == View.primary_key: continue out.append("\t%s = FieldProperty(%s['%s'])\\n" % (column['colname'], View.interface_name, column['colname'])) }} class ${Table['name']}ContainerBase(ExternalFolder): implements(${View.interface_name}Container) modulename='tables.${View.TableName}.${View.TableName}_content' globalname='${View.TableName}' def reload(self): table = ${View.TableName}_db.${View.TableName}(self) cursor = table.Keys() return [str(row.${View.primary_key}) for row in cursor] class ${View.TableName}_dublincoreBase(ZopeDublinCore): adapts(${View.interface_name}) implements(IZopeDublinCore) def initialiseData(self, dcdata): dcdata['Title'] = [self.context.__name__] dcdata['Description'] = [self.context.__name__] def __init__(self, context): self.context = context dcdata = {} self.initialiseData(dcdata) ZopeDublinCore.__init__(self, dcdata) class ${View.TableName}ContainerNameChooserBase(NameChooser): "Name chooser which forces integers" adapts(${View.interface_name}Container) def checkName(self, name, object): "Rule - valid integer" i = int(name) def chooseName(self, name, object): table = ${View.TableName}_db.${View.TableName}(self.context) return '%d'%(table.NextPrimaryKey()[0].${View.primary_key}) # CAN_EDIT_AFTER_THIS_LINE ${{ for classname in View.classnames: out.append('class %s(%sBase):\\n' % (classname, classname)) out.append('\tpass\\n\\n') }} """ @stringfunction def GenConfiguration(DSLModel, Table, View): """ <!-- Content Configuration --> <class class=".${View.TableName}_content.${View.TableName}"> <require permission="zope.View" interface=".interfaces.${View.interface_name}" /> <require permission="zope.ManageContent" set_schema=".interfaces.${View.interface_name}" /> </class> <class class=".${View.TableName}_content.${View.TableName}Container"> <require permission="zope.View" interface="zope.app.container.interfaces.IReadContainer" /> <require permission="zope.ManageContent" interface="zope.app.container.interfaces.IWriteContainer" /> <implements interface="zope.annotation.interfaces.IAttributeAnnotatable" /> </class> <browser:addMenuItem title="${View.TableName} Container" class=".${View.TableName}_content.${View.TableName}Container" permission="zope.ManageContent" /> <class class=".${View.TableName}_content.${View.TableName}_dublincore"> <require permission="zope.View" interface="zope.dublincore.interfaces.IZopeDublinCore" /> </class> <adapter factory=".${View.TableName}_content.${View.TableName}_dublincore" provides="zope.dublincore.interfaces.IZopeDublinCore" for=".interfaces.${View.interface_name}" trusted="True" /> <adapter factory=".${View.TableName}_storage.${View.TableName}_Storage" /> <adapter factory=".${View.TableName}_content.${View.TableName}ContainerNameChooser" /> """ @stringfunction def GenStorageFile(DSLModel, Table, View): """ from zope.interface import implements from zope.component import adapts from zope.publisher.interfaces import NotFound from utility.ump.interfaces import IExternalObject from schema_helpers import Bool_toStorage, Bool_fromStorage, List_toStorage, \\ List_fromStorage, BinaryToBase64_toStorage, BinaryToBase64_fromStorage from ${DSLModel['GENERAL']['target_folder']}.${Table['name']} import MessageFactory as _ from interfaces import ${View.interface_name}, ${View.interface_name}Container import ${Table['name']}_db class ${Table['name']}_StorageBase(object): adapts(${View.interface_name}, ${View.interface_name}Container) implements(IExternalObject) def __init__(self, context, container): self.context = context self.container = container self.table = ${Table['name']}_db.${Table['name']}(self.context) def ContextToStorage(self, data): "Save the context object to the data object passed in" ${{ for column in Table['columns']: if column['colname'] == View.primary_key: continue mapping_type = column.get('mapping_type', None) if mapping_type is None: out.append("\t\tdata['%s'] = self.context.%s\\n" % (column['colname'],column['colname'])) else: out.append("\t\tdata['%s'] = %s_toStorage(self.context.%s)\\n" % (column['colname'], mapping_type, column['colname'])) }} def StorageToContext(self, row): "Save the storage (database row) to the context object" ${{ for column in Table['columns']: if column['colname'] == View.primary_key: continue mapping_type = column.get('mapping_type', None) if mapping_type is None: mapped = 'row.%s' % column['colname'] else: mapped = '%s_fromStorage(row.%s)' % (mapping_type, column['colname']) schema_type = column.get('schema_type', 'TextLine') if schema_type == 'schema.Set': mapped = 'set(%s)' % mapped out.append("\t\tself.context.%s = %s\\n" % (column['colname'], mapped)) }} def Create(self, name=None): "Create the object externally, and return the instance" "data which is required by the read method to reload it" data = {} if name is not None: data['${View.primary_key}'] = int(name) else: data['${View.primary_key}'] = self.table.NextPrimaryKey()[0].${View.primary_key} self.context.__name__ = str(data['${View.primary_key}']) self.ContextToStorage(data) self.table.Create(**data) return data['${View.primary_key}'] def Read(self, init_data): "Reload the data from the external object init data" cursor = self.table.Read(${View.primary_key} = init_data) if len(cursor) == 0: raise NotFound(self.container, str(init_data), None) row = cursor[0] self.context.__name__ = str(row.${View.primary_key}) self.StorageToContext(row) def Update(self): "Update the external data if changed" data = {'${View.primary_key}': self.context.__name__} self.ContextToStorage(data) cursor = self.table.Update(**data) def Delete(self): "Delete the external data" data = {'${View.primary_key}': self.context.__name__} cursor = self.table.Delete(**data) # CAN_EDIT_AFTER_THIS_LINE class ${Table['name']}_Storage(${Table['name']}_StorageBase): pass """ <file_sep>/trunk/kg.locationfield/kg/locationfield/setuphandlers.py from Products.CMFCore.utils import getToolByName def cleanUpFactoryTool(portal): tool = getToolByName(portal, 'portal_factory') if 'FormLocationField' in tool._factory_types.keys(): del tool._factory_types['FormLocationField'] def uninstall(context): # Only run step if a flag file is present (e.g. not an extension profile) if context.readDataFile( 'kg.locationfield_uninstall.txt') is None: return out = [] site = context.getSite() cleanUpFactoryTool(site) <file_sep>/trunk/generator/templates/interfaces.py # Templates for generating interfaces # # Uses the templet library from davidbau.com # from templet import stringfunction import types @stringfunction def GenFile(DSLModel, Table, View): """ from zope import schema from zope.app.container.interfaces import IContainer, IContained from zope.app.container.constraints import contains, containers from ${DSLModel['GENERAL']['target_folder']}.${Table['name']} import MessageFactory as _ class ${View.interface_name}Base(IContained): ${{ for row in Table['columns']: if row['colname'] == View.primary_key: continue out.append('\t%s = %s(' % (row['colname'], row['schema_type'])) for (k,v) in row['schema_fields'].items(): if type(v) in types.StringTypes: out.append("%s=_(u'%s'), " % (k,v)) else: out.append("%s=%s, " % (k,v)) if row.has_key('value_type'): out.append("\\n\t\tvalue_type=%s(" % row['value_type']) for (k,v) in row['value_type_fields'].items(): if type(v) in types.StringTypes: out.append("%s=_(u'%s'), " % (k,v)) else: out.append("%s=%s, " % (k,v)) out.append(') ') out.append(')\\n') }} containers('${DSLModel['GENERAL']['target_folder']}.${Table['name']}.interfaces.${View.interface_name}Container') class ${View.interface_name}ContainerBase(IContainer): contains('${DSLModel['GENERAL']['target_folder']}.${Table['name']}.interfaces.${View.interface_name}') # CAN_EDIT_AFTER_THIS_LINE ${{ for classname in View.classnames: out.append('class %s(%sBase):\\n' % (classname, classname)) out.append('\tpass\\n\\n') }} """ <file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/browser/managers.py from five import grok from ploneide.core import IPloneIDE class PloneIDENavigatorViewletManager(grok.ViewletManager): """The manager for the left hand side navigation panel. To implement your own navigator... from five import grok from ploneide.core import PloneIDENavigatorViewletManager class MyNavigator(grok.Viewlet): grok.name('mynavigator') grok.require('cmf.ManagePortal') grok.viewletmanager(PloneIDENavigatorViewletManager) # Viewlets should contain a 'weight' attribute to manage ordering. grok.order(200) def render(self): # Navigator must provide code to fit into the jstree structure. return '<h2>title</h2><div>Body</div>' """ grok.name('ploneide.core.Navigator') grok.context(IPloneIDE) class PloneIDEJSViewletManager(grok.ViewletManager): """The manager for including javascript resources into the editor. This manager will be rendered in the head, Jquery should be included at 10 ploneide.js should be included at 100 bespin editor plugin should be included at 1000 To include your own javascript - TODO: see how to do this directly with a resource declaration To include your own javascript... from five import grok from ploneide.core import PloneIDEJSViewletManager class MyJSResource(grok.Viewlet): grok.name('my-js-resource') grok.require('cmf.ManagePortal') grok.viewletmanager(PloneIDEJSViewletManager) # Viewlets should contain a 'weight' attribute to manage ordering. grok.order(200) def render(self): return '<script type="text/javascript" src="your path"></script>' """ grok.name('ploneide.core.JS') grok.context(IPloneIDE) class PloneIDECSSViewletManager(grok.ViewletManager): """The manager for including CSS resources into the editor. This manager will be rendered in the head, ploneide.css should be included at 100 To include your own CSS... from five import grok from ploneide.core import PloneIDECSSViewletManager class MyCSSResource(grok.Viewlet): grok.name('my-css-resource') grok.require('cmf.ManagePortal') grok.viewletmanager(PloneIDECSSViewletManager) # Viewlets should contain a 'weight' attribute to manage ordering. grok.order(200) def render(self): return '<style type="text/css">@import url(my-css-path);</style>' """ grok.name('ploneide.core.CSS') grok.context(IPloneIDE) class PloneIDEToolViewletManager(grok.ViewletManager): """The manager for including html into the tools area, i.e. the bottom of the page. To implement your own tool... from five import grok from ploneide.core import PloneIDEToolViewletManager class MyTool(grok.Viewlet): grok.name('my-tool') grok.require('cmf.ManagePortal') grok.viewletmanager(PloneIDEToolViewletManager) # Viewlets should contain a 'weight' attribute to manage ordering. grok.order(200) def render(self): # tools must provide code to fit into the jstree structure. return '<h2>title</h2><div>Body</div>' """ grok.name('ploneide.core.Tool') grok.context(IPloneIDE) <file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/browser/handler.py import json import logging from zope.component import getMultiAdapter from ploneide.core import IPloneIDE from ploneide.core import IPloneIDEModel from five import grok logger = logging.getLogger('PloneIDE') class Handler(grok.View): grok.context(IPloneIDE) grok.name('handler') grok.require('cmf.ManagePortal') def render(self): logger.info(self.request.form) type_name = self.request.get('type_name', None) if type_name is None: raise NotImplemented method_name = self.request.get('method_name', None) if method_name is None or method_name.startswith('_'): raise NotImplemented handler = getMultiAdapter((self.context, self.request), IPloneIDEModel, name=type_name) rv = handler.handle(type_name, method_name, self.request.form) if type(rv) in [str, unicode]: return rv else: self.request.response.setHeader('content-type', 'text/json') return json.dumps(rv) <file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/static/ploneide-fs-navigator.js "use strict"; (function($) { var ploneide_base = document.getElementById("ploneide_base").href; ploneide_base = ploneide_base.substring(ploneide_base.length - 1) !== "/" ? ploneide_base + "/" : ploneide_base; var process_click = function(title, href) { // href could have trailing data e.g. line number var type_name = href.split(':')[0]; var unique_id = href.split(':')[1]; var path = href.substr(href.length + 1 + unique_id.length + 1); /* Ask the global ploneide object to open this object */ $.ploneide.edit_file(type_name, unique_id, null); }; /* register a controller for mapping navigator-filesystem objects between view and model */ var ControllerFS = function(type_name, unique_id, initial_data, model_data) { this.init_super(type_name, unique_id, initial_data, model_data); }; ControllerFS.prototype = new $.ploneide.Controller(); $.ploneide.register_controller('navigator-filesystem', ControllerFS, 100); /* Initialise the navigator */ $(document).ready(function(){ $("#tree").jstree({ "json_data" : { "ajax" : { "url": ploneide_base + '@@handler', "data" : function (n) { return { 'id' : n.attr ? n.attr("id") : 0, 'type_name': 'navigator-filesystem', 'method_name': 'getNavigation' }; } }, }, "plugins" : [ "themes", "json_data" ] }); $("#tree a").live("click", function(e) { var href = $(this).parent()[0].id; var title = $(this).text(); process_click(title, href); return false; }); }); })(jQuery); <file_sep>/trunk/kg.locationfield/kg/locationfield/tests/test_docs.py import unittest import doctest from Testing import ZopeTestCase as ztc from kg.locationfield.tests.base import \ LocationFieldFunctionalTestCase def test_suite(): return unittest.TestSuite([ ztc.FunctionalDocFileSuite( 'locationfield.txt', package='kg.locationfield.tests', test_class=LocationFieldFunctionalTestCase, optionflags= doctest.REPORT_ONLY_FIRST_FAILURE | \ doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS), ]) <file_sep>/trunk/generator/templates/views.py from templet import stringfunction @stringfunction def GenFile(DSLModel, Table, View): """ import copy from zope.formlib import form from zope.traversing.browser import absoluteURL import ${View.TableName}_db from interfaces import ${View.interface_name} class AddBase(form.AddForm): label="Add: ${View.TableName}" form_fields = form.Fields(${View.interface_name})${View.create_omit} def create(self, data): table = ${View.TableName}_db.${View.TableName}(self.context) ${{ if Table['primary_key_has_sequence']: out.append("\t\tdata['%s'] = table.NextPrimaryKey()[0].%s\\n" % (View.primary_key, View.primary_key)) }} table.Create(**data) self.${View.primary_key} = data['${View.primary_key}'] def add(self, object): self.request.response.redirect( absoluteURL(self.context.__parent__, self.request) + '/%s/@@SelectedManagementView.html'% self.${View.primary_key}) class EditBase(form.EditForm): label="Edit: ${View.TableName}" form_fields = form.Fields(${View.interface_name})${View.update_omit} @form.action('Save', name='save') def handle_save(self, action, data): table = ${View.TableName}_db.${View.TableName}(self.context) res = table.Update(${View.primary_key} = self.context.${View.primary_key}, **data) self.context.LoadFromDatabase(self.context, self.request) class ViewBase(form.EditForm): label="View: ${View.TableName}" form_fields = form.Fields(${View.interface_name})${View.update_omit} for field in form_fields: field.field = copy.copy(field.field) field.field.readonly=True # CAN_EDIT_AFTER_THIS_LINE ${{ for classname in View.classnames: out.append('class %s(%sBase):\\n' % (classname, classname)) out.append('\tpass\\n\\n') }} """ @stringfunction def GenConfiguration(DSLModel, Table, View): r""" <!-- View Configuration --> <browser:addMenuItem title="${View.TableName}" class=".${View.TableName}_content.${View.TableName}" view="${View.TableName}.add${View.TableName}" permission="zope.ManageContent" /> <browser:page name="index.html" for=".interfaces.${View.interface_name}" class=".${View.TableName}_views.View" permission="zope.Public" menu="zmi_views" title="View" /> <browser:page name="edit.html" for=".interfaces.${View.interface_name}" class=".${View.TableName}_views.Edit" permission="zope.Public" menu="zmi_views" title="Edit" /> <browser:page for="zope.app.container.interfaces.IAdding" name="${View.TableName}.add${View.TableName}" class=".${View.TableName}_views.Add" permission="zope.ManageContent" /> <browser:containerViews for=".interfaces.${View.interface_name}Container" add="zope.ManageContent" contents="zope.View" index="zope.View" /> """ <file_sep>/trunk/gentest/src/tables/__init__.py # Module Initialiation File<file_sep>/ploneide.core/trunk/ploneide.core/ploneide/core/README.txt PLONE IDE ========= My initial vision of this product is to be a plugable tool to make it easier for Plone users to become Plone developers. Inspiration for this comes from the bespin project and many similar products. Roadmap'ish 0.1.0 Pluggable --------------- Version 0.1.0 of this product is focussed on developing a mechanism for maximum plugability. It should be easy to extend the editor using standard zope views and viewlets and if you are more daring it should be relatively easy to add javascript products. PloneIDE should focus on beginners. To this end... - dexterity focus - integration of code generation - integration of snippets 0.2.0 Web-sockets ----------------- Version 0.2.0 of this product is focussed on developing a mechanism for using web-sockets in a Plone server. If I can get web-sockets to work, I should be able to get a debugger to work TTW. 0.3.0 Test driven development ------------------------------ <file_sep>/trunk/collective.editor/collective/editor/__init__.py from zope.i18nmessageid import MessageFactory _ = MessageFactory('collective.editor') <file_sep>/trunk/generator/templates/tests.py from templet import stringfunction @stringfunction def GenTestLoader(DSLModel, Table, View): """ import unittest from doctest import DocFileSuite def test_suite(): return unittest.TestSuite((DocFileSuite('${Table['name']}.txt'),)) if __name__ == '__main__': unittest.main(defaultTest = 'test_suite') """ @stringfunction def GenDocTests(DSLModel, Table, View): """ Doc Test for ${Table['name']} ================= Run these from the same area that your start your zope instance, using this command: ./bin/test -s tables.${Table['name']} Once this file exists, it should not be replaced by the generator Note, you will need to have a test database which works with the schema implemented. Edit the DB_CONNECTION_STRING below as appropriate. To echo SQL statement, set the flag below. This causes tests to fail. >>> DB_CONNECTION_STRING='dbi://' >>> DB_ECHO_SQL=False Create a site: >>> from zope.app.testing import setup >>> root = setup.placefulSetUp(site=True) >>> sitemanager = setup.createSiteManager(root) >>> from zope.component import getSiteManager >>> sitemanager = getSiteManager() Connect to the database: >>> import psycopgda.adapter as adapter >>> from psycopgda.adapter import PsycopgAdapter >>> db_adapter = PsycopgAdapter(DB_CONNECTION_STRING) >>> from zope.rdb.interfaces import IZopeDatabaseAdapter >>> from tables.${Table['name']} import CONNECTION_NAME >>> sitemanager.registerUtility(db_adapter, provided=IZopeDatabaseAdapter, name=CONNECTION_NAME) Set up a database connection utility >>> from zope.component import getUtility >>> connection = getUtility(IZopeDatabaseAdapter, CONNECTION_NAME)() >>> from zope.rdb import queryForResults >>> rowcount = queryForResults(connection, 'select count(*) from ${Table['name']}')[0].count Set up dummy vocabularies for all of the required vocabularies [ The utility registry does not seem to work with vocabularies in a unit test. I am forced to register them directly to the vocabulary registry ] >>> from zope.interface import alsoProvides >>> from zope.schema.vocabulary import SimpleVocabulary >>> from zope.schema.interfaces import IVocabularyFactory >>> def testvocab(context): ... return SimpleVocabulary.fromValues(['x']) >>> alsoProvides(testvocab, IVocabularyFactory) >>> from zope.schema.vocabulary import getVocabularyRegistry >>> vr = getVocabularyRegistry() ${{ for vocab in View.required_vocabularies: out.append("\\t>>> vr.register( u'%s', testvocab)\\n" % vocab) }} Verify that all of our modules import >>> import tables.${Table['name']} >>> from tables.${Table['name']} import schema_helpers >>> from tables.${Table['name']} import db >>> db.ECHO_SQL = DB_ECHO_SQL >>> from tables.${Table['name']} import interfaces >>> from tables.${Table['name']} import ${Table['name']}_db >>> from tables.${Table['name']} import ${Table['name']}_storage >>> from tables.${Table['name']} import ${Table['name']}_content >>> from tables.${Table['name']} import ${Table['name']}_views >>> from tables.${Table['name']} import ${Table['name']}_search Register the adapters: >>> factory=${Table['name']}_storage.${Table['name']}_Storage >>> sitemanager.registerAdapter(factory) >>> factory=${Table['name']}_content.${Table['name']}ContainerNameChooser >>> sitemanager.registerAdapter(factory) >>> factory=${Table['name']}_content.${Table['name']}_dublincore >>> sitemanager.registerAdapter(factory) Create the container >>> container = ${Table['name']}_content.${Table['name']}Container() >>> container.__name__ = '${Table['name']}' >>> root[container.__name__] = container >>> container = root[container.__name__] Create a ${Table['name']} object >>> import transaction >>> from zope.app.container.interfaces import INameChooser >>> newobj = ${Table['name']}_content.${Table['name']}() >>> from datetime import date ${{ for column in Table['columns']: if column['colname'] == View.primary_key: continue schema_type = column.get('schema_type', 'TextLine') value = None if schema_type == 'schema.TextLine': max_length = column['schema_fields'].get('max_length', '1') value = 'A' * int(max_length) value = 'u"' + value + '"' if schema_type == 'schema.Int': value = '1' if schema_type == 'schema.Float': value = '1.0' if schema_type == 'schema.List': value = '[]' if schema_type == 'schema.Set': value = 'set([])' if schema_type == 'schema.Text': value = 'u"TEXT"' if schema_type == 'schema.Date': import time t = time.localtime() value = 'date(%d, %02.2d, %02.2d)' % (t[0], t[1], t[2]) if value is not None: out.append("\t>>> newobj.%s = %s\\n" % (column['colname'], value)) }} >>> nc = INameChooser(container) >>> newobj.__name__ = nc.chooseName('', newobj) >>> container[newobj.__name__] = newobj >>> transaction.get().commit() >>> contained_obj = container[newobj.__name__] >>> contained_obj == newobj True Update a ${Table['name']} object ${{ for column in Table['columns']: if column['colname'] == View.primary_key: continue schema_type = column.get('schema_type', 'TextLine') value = None if schema_type == 'schema.TextLine': max_length = column['schema_fields'].get('max_length', '1') value = 'x' * int(max_length) value = 'u"' + value + '"' if schema_type == 'schema.Int': value = '0' if schema_type == 'schema.Float': value = '0.0' if schema_type == 'schema.List': value = '[]' if schema_type == 'schema.Set': value = 'set([])' if schema_type == 'schema.Text': value = 'u"text"' if schema_type == 'schema.Date': import time t = time.localtime() value = 'date(%d, %02.2d, %02.2d)' % (t[0], t[1], t[2]) if value is not None: out.append("\t>>> newobj.%s = %s\\n" % (column['colname'], value)) }} >>> transaction.get().commit() Read an actor object back. We need to clear the cache to for external storage Read(). >>> container.clear_cache() >>> oldobj = container[newobj.__name__] >>> oldobj != newobj True >>> newobj = oldobj Verify the DublinCore Annotations >>> from zope.dublincore.interfaces import IZopeDublinCore >>> dc = IZopeDublinCore(newobj) >>> dc.title == newobj.__name__ True >>> dc.description == newobj.__name__ True Delete the ${Table['name']} object >>> del container[newobj.__name__] >>> transaction.get().commit() """ <file_sep>/trunk/generator/README.txt Generator ========= This is a simple generator to generate Zope content types from the database. The toolchain is: python psql2dsl.py table_name > dsl_file_name python z3gen.py dsl_file_name Motivation ---------- This is essentially a teaching tool. I developed it because my tutorial on ZSQLScript with Zope3 was too complicated. The configuration is just too complex to keep explaining it in every tutorial. It should also be useful for kick-starting a project, much the same as ArchgenXML in Plone. psql2dsl.py ----------- This script will pull a definition from a postgresql database and generate a dsl (domain specific language) file for it. You will need to edit the psql2dsl.py script if your psql command requires parameters, i.e. a username or database name. z3gen.py -------- This script generates a content object from the dsl definition. The ouput is written to a folder called 'tables/table_name'. The entire content object is stored in one folder. The DSL ------- The DSL is python. There are two sections, GENERAL and TABLES. GENERAL ------- This defines the following: namespace: used for the translation domain and the name of the IZopeDatabaseAdapter to be used for accessing the database; sql_dialect: set to postgresql - intended to allow you to provide alternative templates for other SQL targets target_folder: where to put the generated files form_library: either formlib or z3c z3c_layer: If you are using z3c, you can specify a layer for the configuration. The demonstration project (gentest) uses boston_pagelet_skin.IPageletLayer. TABLES ------ List if tables to be generated: name: The table name stereotype: Used to select alternative templates during generation primary_key: The list of columns for primary key - only one column supported primary_key_has_sequence: Boolean if the primary key has a sequence primary_key_sequence_name: Name of the sequence if the primary key has a sequence columns: The database columns colname: the name of the column dbtype: the type specification as per the database dbextra: extra information from db, e.g. constraints mapping_type: The name of the class to map the underlying data object to the value expected by the client. For example, MappingList maps between an underlying comma separated string and a list. schema_type: zope schema type schema_fields: fields passed verbatim to the zope schema definition value_type: for list type schema entries, the information about the values value_type_fields: pass verbatim to the value_type section of the schema Examples: ======== See examples folder Issues, Bugs and Incompletnesses: -------------------------------- The generator (currently) has only one template so can only generate a single output type. However, when more templates are produced, they can be added via stereotype fields. The conversion from postgresql to dsl makes a lot of assumptions. The z3c.form code does not work with the IAdding menu. The mapping between application types and underlying data is performed in two places. The content object and the DMTL to created/update the record. See MappingList in the code for more information. Templates and Code Structure ---------------------------- z3gen.py This is the driver code. The code performs a number of steps to generate the output: z3gen_content This generates the content object and the related configuration. It uses the templates/content*py z3gen_dbclass This generates the database access methods. It uses the templates/dbclass*py z3gen_interfaces.py This generates the Zope schema. It uses the templates/interfaces*py z3gen_views.py This geneerates the view code. It uses the templates/view*py z3gen_utilities.py Provides a number of utilty functions. templet.py This is a templating library developed by <NAME>, see http://davidbau.com/templet.
100b052aa1fdb1c70251b7a3c7296529486e92ed
[ "SQL", "JavaScript", "INI", "Python", "Text" ]
57
Python
BGCX261/zope3tutorial-svn-to-git
a9c57eba51b70e4c31d13ba07979e0b2e5fceca4
2a9684ab78814c88549d3a46635f63d8cdac791e
refs/heads/master
<file_sep>package com.wzq.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wzq.dao.UserMapper; import com.wzq.model.User; @Service public class UserServices { @Autowired UserMapper userMapper; public User findUser(Long id) { User user = userMapper.selectByPrimaryKey(id); return user; } }
777bc859a363e98701401378d46b9f5a167d62bb
[ "Java" ]
1
Java
scauwzq/framework
ac7aa9154c6f388a9069774e3891e394d1d1b0ad
150a886c9893d1ed47a4c13a0163f49950d087c7