code
stringlengths
1
2.06M
language
stringclasses
1 value
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Written by Danny Bickson, CMU */ #ifndef _GRAPHCHI_PARSERS_COMMON #define _GRAPHCHI_PARSERS_COMMON #include <map> #include <string> #include "graphchi_basic_includes.hpp" using namespace graphchi; mutex mymutex; struct double_map{ std::map<std::string,uint> string2nodeid; std::map<uint,std::string> nodeid2hash; uint maxid; double_map(){ maxid = 0; } }; double_map frommap; double_map tomap; template<typename T1> void load_map_from_txt_file(T1 & map, const std::string filename, int fields){ logstream(LOG_INFO)<<"loading map from txt file: " << filename << std::endl; FILE * f = fopen(filename.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL)<<"Failed to open file: " << filename << std::endl; char * linebuf = NULL; size_t linesize; int line = 0; while (true){ int rc = getline(&linebuf, &linesize, f); char * to_free = linebuf; if (rc == -1) break; if (fields == 1){ char *pch = strtok(linebuf,"\r\n\t"); if (!pch) logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl; map[pch] = ++line; } else { char *pch = strtok(linebuf," \r\n\t"); if (!pch){ logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl; } char * pch2 = strtok(NULL,"\n"); if (!pch2) logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl; map[pch] = atoi(pch2); line++; } //free(to_free); } logstream(LOG_INFO)<<"Map size is: " << map.size() << std::endl; fclose(f); } void save_map_to_text_file(const std::map<std::string,uint> & map, const std::string filename, int optional_offset = 0){ std::map<std::string,uint>::const_iterator it; out_file fout(filename); unsigned int total = 0; for (it = map.begin(); it != map.end(); it++){ fprintf(fout.outf, "%s %u\n", it->first.c_str(), it->second + optional_offset); total++; } logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl; } void save_map_to_text_file(const std::map<unsigned long long,uint> & map, const std::string filename, int optional_offset = 0){ std::map<unsigned long long,uint>::const_iterator it; out_file fout(filename); unsigned int total = 0; for (it = map.begin(); it != map.end(); it++){ fprintf(fout.outf, "%llu %u\n", it->first, it->second + optional_offset); total++; } logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl; } void save_map_to_text_file(const std::map<uint,std::string> & map, const std::string filename){ std::map<uint,std::string>::const_iterator it; out_file fout(filename); unsigned int total = 0; for (it = map.begin(); it != map.end(); it++){ fprintf(fout.outf, "%u %s\n", it->first, it->second.c_str()); total++; } logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl; } /* * assign a consecutive id from either the [from] or [to] ids. */ void assign_id(double_map& dmap, unsigned int & outval, const std::string &name){ std::map<std::string,uint>::iterator it = dmap.string2nodeid.find(name); //if an id was already assigned, return it if (it != dmap.string2nodeid.end()){ outval = it->second; return; } mymutex.lock(); //assign a new id outval = dmap.string2nodeid[name]; if (outval == 0){ dmap.string2nodeid[name] = dmap.maxid; dmap.nodeid2hash[dmap.maxid] = name; outval = dmap.maxid; dmap.maxid++; } mymutex.unlock(); } #endif //_GRAPHCHI_PARSERS_COMMON
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Written by Danny Bickson, CMU * * * This program reads a text input file, where each line * is taken from another document. The program counts the number of word * occurances for each line (document) and outputs a document word count to be used * in LDA. */ #include <cstdio> #include <iostream> #include <map> #include <omp.h> #include <assert.h> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/timer.hpp" #include "../collaborative_filtering/util.hpp" #include "common.hpp" using namespace std; using namespace graphchi; bool debug = false; timer mytime; size_t lines; unsigned long long total_lines = 0; string dir; string outdir; std::vector<std::string> in_files; int min_threshold = 1; //output to file, token that appear at least min_threshold times int max_threshold = 1234567890; //output to file tokens that appear at most max_threshold times //non word tokens that will be removed in the parsing //it is possible to add additional special characters or remove ones you want to keep const char spaces[] = {" \r\n\t!?@#$%^&*()-+.,~`'\";:"}; void parse(int i){ in_file fin(in_files[i]); out_file fout((outdir + in_files[i] + ".out")); size_t linesize = 0; char * saveptr = NULL, * linebuf = NULL; size_t line = 1; uint id; while(true){ std::map<uint,uint> wordcount; int rc = getline(&linebuf, &linesize, fin.outf); if (rc < 1) break; if (strlen(linebuf) <= 1) //skip empty lines continue; char *pch = strtok_r(linebuf, spaces, &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } assign_id(frommap, id, pch); wordcount[id]+= 1; while(pch != NULL){ pch = strtok_r(NULL, spaces ,&saveptr); if (pch != NULL && strlen(pch) > 1){ assign_id(frommap, id, pch); wordcount[id]+= 1; } } total_lines++; std::map<uint,uint>::const_iterator it; for (it = wordcount.begin(); it != wordcount.end(); it++){ if ((int)it->second >= min_threshold && (int)it->second <= max_threshold) fprintf(fout.outf, "%lu %u %u\n", line, it->first, it->second); } line++; if (lines && line>=lines) break; if (debug && (line % 50000 == 0)) logstream(LOG_INFO) << "Parsed line: " << line << " map size is: " << frommap.string2nodeid.size() << std::endl; if (frommap.string2nodeid.size() % 500000 == 0) logstream(LOG_INFO) << "Hash map size: " << frommap.string2nodeid.size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl; } logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl << "total map size: " << frommap.string2nodeid.size() << endl; } int main(int argc, const char *argv[]) { logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any " " comments or bug reports to danny.bickson@gmail.com " << std::endl; global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); debug = get_option_int("debug", 0); dir = get_option_string("file_list"); lines = get_option_int("lines", 0); min_threshold = get_option_int("min_threshold", min_threshold); max_threshold = get_option_int("max_threshold", max_threshold); omp_set_num_threads(get_option_int("ncpus", 1)); mytime.start(); FILE * f = fopen(dir.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl; while(true){ char buf[256]; int rc = fscanf(f, "%s\n", buf); if (rc < 1) break; in_files.push_back(buf); } if (in_files.size() == 0) logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl; #pragma omp parallel for for (int i=0; i< (int)in_files.size(); i++) parse(i); std::cout << "Finished in " << mytime.current_time() << std::endl; save_map_to_text_file(frommap.string2nodeid, outdir + dir + "map.text"); save_map_to_text_file(frommap.nodeid2hash, outdir + dir + "reverse.map.text"); return 0; }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Written by Danny Bickson, CMU * * * This program reads a text input file, where each line * is taken from another document. The program counts the number of word * occurances for each line (document) and outputs a document word count to be used * in LDA. */ #include <cstdio> #include <iostream> #include <map> #include <omp.h> #include <assert.h> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/timer.hpp" #include "../collaborative_filtering/util.hpp" #include "common.hpp" #include <math.h> #include <iomanip> using namespace std; using namespace graphchi; bool debug = false; timer mytime; size_t lines; unsigned long long total_lines = 0; string dir; string outdir; std::vector<std::string> in_files; //non word tokens that will be removed in the parsing //it is possible to add additional special characters or remove ones you want to keep const char spaces[] = {" \r\n\t!?@#$%^&*()-+.,~`\";:/"}; const char qoute[] = {",\""}; const char comma[] = {","}; int has_header_titles = 1; std::map<std::string, int> p_x; std::map<std::string, int> p_y; int n = 0; std::vector<std::string> header_titles; int from_val = -1; int to_val = -1; void parse(int i){ in_file fin(in_files[i]); size_t linesize = 0; char * saveptr = NULL, * saveptr2 = NULL,* linebuf = NULL; size_t line = 1; uint id; if (has_header_titles){ char * linebuf = NULL; size_t linesize; char linebuf_debug[1024]; /* READ LINE */ int rc = getline(&linebuf, &linesize, fin.outf); if (rc == -1) logstream(LOG_FATAL)<<"Error header line " << " [ " << linebuf_debug << " ] " << std::endl; strncpy(linebuf_debug, linebuf, 1024); char *pch = strtok(linebuf,"\t,\r;\""); if (pch == NULL) logstream(LOG_FATAL)<<"Error header line " << " [ " << linebuf_debug << " ] " << std::endl; for (int j=0; j < strlen(pch); j++) if (pch[j] == ' ') pch[j] = '_'; header_titles.push_back(pch); if (debug) printf("Found title: %s\n", pch); while (pch != NULL){ pch = strtok(NULL, "\t,\r;\""); if (pch == NULL || pch[0] == '\0') break; for (int j=0; j < strlen(pch); j++) if (pch[j] == ' ') pch[j] = '_'; header_titles.push_back(pch); if (debug) printf("Found title: %s\n", pch); } } while(true){ int rc = getline(&linebuf, &linesize, fin.outf); if (rc < 1) return; int index = 0; char frombuf[256]; char tobuf[256]; char *pch = strtok_r(linebuf, ",\"", &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } if (debug) printf("Found token 1 %s\n", pch); if (pch[0] == '"') pch++; index++; bool found_from = false, found_to = false; int from,to; if (index == from_val){ strncpy(frombuf, pch, 256); found_from = true; } if (index == to_val){ strncpy(tobuf, pch, 256); found_to = true; } while(true){ pch = strtok_r(NULL, ",\"", &saveptr); if (pch == NULL) break; index++; if (debug) printf("Found token %d %s\n", index, pch); if (pch[0] == '"') pch++; if (index > from_val && index > to_val) break; if (index == from_val){ strncpy(frombuf, pch, 256); found_from = true; } if (index == to_val){ strncpy(tobuf, pch, 256); found_to = true; } } char totalbuf[512]; assert(found_from && found_to); sprintf(totalbuf, "%s_%s", frombuf, tobuf); if (debug) printf("Incrementing map: %s\n", totalbuf); frommap.string2nodeid[totalbuf]++; p_x[frombuf]++; p_y[tobuf]++; n++; } } int main(int argc, const char *argv[]) { logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any " " comments or bug reports to danny.bickson@gmail.com " << std::endl; global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); debug = get_option_int("debug", 0); dir = get_option_string("file_list"); lines = get_option_int("lines", 0); omp_set_num_threads(get_option_int("ncpus", 1)); from_val = get_option_int("from_val", from_val); to_val = get_option_int("to_val", to_val); if (from_val == -1) logstream(LOG_FATAL)<<"Must set from/to " << std::endl; mytime.start(); FILE * f = fopen(dir.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl; while(true){ char buf[256]; int rc = fscanf(f, "%s\n", buf); if (rc < 1) break; in_files.push_back(buf); } if (in_files.size() == 0) logstream(LOG_FATAL)<<"Failed to read any file frommap from the list file: " << dir << std::endl; #pragma omp parallel for for (int i=0; i< (int)in_files.size(); i++) parse(i); std::cout << "Finished in " << mytime.current_time() << std::endl; int total_x =0 , total_y = 0; std::map<std::string, int>::iterator it; double h = 0; for (it = p_x.begin(); it != p_x.end(); it++){ total_x+= it->second; h-= (it->second / (double)n)*log2(it->second / (double)n); } for (it = p_y.begin(); it != p_y.end(); it++) total_y+= it->second; assert(total_x == n); assert(total_y == n); double mi = 0; std::map<std::string, uint>::iterator iter; assert(n != 0); int total_p_xy = 0; for (iter = frommap.string2nodeid.begin() ; iter != frommap.string2nodeid.end(); iter++){ double p_xy = iter->second / (double)n; assert(p_xy > 0); char buf[256]; strncpy(buf, iter->first.c_str(), 256); char * first = strtok(buf, "_"); char * second = strtok(NULL, "\n\r "); assert(first && second); double px = p_x[first] / (double)n; double py = p_y[second] / (double)n; assert(px > 0 && py > 0); mi += p_xy * log2(p_xy / (px * py)); total_p_xy += iter->second; } assert(total_p_xy == n); logstream(LOG_INFO)<<"Total examples: " <<n << std::endl; logstream(LOG_INFO)<<"Unique p(x) " << p_x.size() << std::endl; logstream(LOG_INFO)<<"Unique p(y) " << p_y.size() << std::endl; logstream(LOG_INFO)<<"Average F(x) " << total_x / (double)p_x.size() << std::endl; logstream(LOG_INFO)<<"Average F(y) " << total_y / (double)p_y.size() << std::endl; std::cout<<"Mutual information of " << from_val << " [" << header_titles[from_val-1] << "] <-> " << to_val << " [" << header_titles[to_val-1] << "] is: " ; if (mi/h > 1e-3) std::cout<<std::setprecision(3) << mi << std::endl; else std::cout<<"-"<<std::endl; save_map_to_text_file(frommap.string2nodeid, outdir + dir + "map.text"); logstream(LOG_INFO)<<"Saving map file " << outdir << dir << "map.text" << std::endl; return 0; }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Written by Danny Bickson, CMU * * This program takes a file in the following graph format format: * 1 1 050803 156 * 1 1 050803 12 * 2 2 050803 143 * 3 3 050803 0 * 4 4 050803 0 * 5 5 050803 1 * 6 6 050803 68 * * Namely, a text file where the first field is a "from" field (uint >=1), second field is a "to" field (uint > = 1) * and then there is a list of fields seperated by spaces (either strings or numbers) which characterize this edge. * * The input file is sorted by the from and to fields. * * The output of this program is a sorted graph, where edges values are aggregated together, s.t. each edge * appears only once: * 1 1 050803 168 * 2 2 050803 143 * 3 3 050803 0 * 4 4 050803 0 * 5 5 050803 1 * 6 6 050803 68 * * Namely, an aggregation of the value in column defined by --col=XX command line flag, * in the above example 168 = 156+12 * */ #include <cstdio> #include <map> #include <iostream> #include <map> #include <omp.h> #include <assert.h> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/timer.hpp" #include "../collaborative_filtering/util.hpp" using namespace std; using namespace graphchi; bool debug = false; timer mytime; size_t lines; unsigned long long total_lines = 0; string dir; string outdir; std::vector<std::string> in_files; int col = 3; //non word tokens that will be removed in the parsing //it is possible to add additional special characters or remove ones you want to keep const char spaces[] = {" \r\n\t!?@#$%^&*()-+.,~`'\";:"}; void parse(int i){ in_file fin(in_files[i]); out_file fout((outdir + in_files[i] + ".out")); size_t linesize = 0; char * saveptr = NULL, * linebuf = NULL; size_t line = 1; double total = 0; uint from = 0, to = 0; uint last_from = 0, last_to = 0; while(true){ int rc = getline(&linebuf, &linesize, fin.outf); if (rc < 1) break; if (strlen(linebuf) <= 1) //skip empty lines continue; //identify from and to fields char *pch = strtok_r(linebuf, spaces, &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; continue; } from = atoi(pch); pch = strtok_r(NULL, spaces ,&saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; continue; } to = atoi(pch); int col_num = 3; //go over the rest of the line while(true){ pch = strtok_r(NULL, spaces ,&saveptr); if (pch == NULL && col_num > col) break; if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; continue; } //aggregate the requested column if (col == col_num){ if (from != last_from || to != last_to){ if (last_from != 0 && last_to != 0) fprintf(fout.outf, "%u %u %g\n", last_from, last_to, total); total = atof(pch); } else total += atof(pch); } col_num++; } last_from = from; last_to = to; total_lines++; line++; if (lines && line>=lines) break; if (debug && (line % 50000 == 0)) logstream(LOG_INFO) << "Parsed line: " << line << std::endl; } if (last_from != 0 && last_to != 0) fprintf(fout.outf, "%u %u %g\n", last_from, last_to, total); logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl; } int main(int argc, const char *argv[]) { logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any " " comments or bug reports to danny.bickson@gmail.com " << std::endl; global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); debug = get_option_int("debug", 0); dir = get_option_string("file_list"); lines = get_option_int("lines", 0); col = get_option_int("col", 3); omp_set_num_threads(get_option_int("ncpus", 1)); mytime.start(); FILE * f = fopen(dir.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl; while(true){ char buf[256]; int rc = fscanf(f, "%s\n", buf); if (rc < 1) break; in_files.push_back(buf); } if (in_files.size() == 0) logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl; #pragma omp parallel for for (int i=0; i< (int)in_files.size(); i++) parse(i); std::cout << "Finished in " << mytime.current_time() << std::endl; return 0; }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Code by Yucheng Low, UW * Adapted by Danny Bickson, CMU * * File for counting the number of unsigned int occurances in a text file * Where each line has one value * * For example, input file named "in" has the following lines: * * 1 * 2 * 2 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * * The output of "./count in" * 1 1 * 2 2 * 3 8 */ #include <iostream> #include <string> #include <fstream> #include <map> #include <stdint.h> #include <stdlib.h> using namespace std; int main(int argc, char** argv) { if (argc <= 1){ std::cerr<<"Usage: counter <input file name>" << std::endl; exit(1); } std::ifstream fin(argv[1]); map<uint32_t, uint32_t> count; size_t lines = 0; while(fin.good()) { std::string b; ++lines; getline(fin, b); if (fin.eof()) break; int32_t bid = atol(b.c_str()); if (lines >= 3){ ++count[bid]; //std::cout<<"adding: " << bid << std::endl; if (lines % 5000000 == 0) { std::cerr << lines << " lines\n"; } } } fin.close(); map<uint32_t, uint32_t>::iterator itr; for(itr = count.begin(); itr != count.end(); ++itr){ if ((*itr).second > 0 ) std::cout<< (*itr).first << " " <<(*itr).second<<std::endl; } }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Written by Stefan Weigert, TUD based on the * "consecutive_matrix_market.cpp" parser */ #include <cstdio> #include <map> #include <omp.h> #include <cassert> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/util.hpp" using namespace graphchi; // global options int debug = 0; int csv = 0; int tsv = 0; const char* token; std::vector<std::string> in_files; // global data-structs mutex ids_mutex; std::map<unsigned int, unsigned int> ids; /* * The expected format is one of the following: * * * <source-ip>\t<dst-ip>\t<some attribute> * <source-ip>,<dst-ip>,<other stuff> * <source-ip> <dst-ip> <other stuff> */ void parse(int i) { uint64_t max_id = 1; in_file fin(in_files[i].c_str()); out_file fout(std::string(in_files[i] + ".out").c_str()); uint64_t lines = 0; uint64_t hits = 0; while(true) { struct in_addr caller; struct in_addr callee; char line[256]; char* res = fgets(line, 256, fin.outf); // end of file if (res == NULL) { break; } char* caller_str = strtok(line, token); assert(caller_str != NULL); char* callee_str = strtok(NULL, token); assert(callee_str != NULL); char* attribute = strtok(NULL, token); assert(attribute != NULL); // try to convert caller - if it goes wrong just continue if (inet_aton(caller_str, &caller) == 0) { if (debug) logstream(LOG_WARNING) << "could not convert caller-ip:" << caller_str << std::endl; continue; } // try to convert caller - if it goes wrong just continue if (inet_aton(callee_str, &callee) == 0) { if (debug) logstream(LOG_WARNING) << "could not convert callee-ip:" << caller_str << std::endl; continue; } // check if we know that ip already if (ids.find(caller.s_addr) == ids.end()) { // we don't - IDs are global to all threads and files, so // lock ids_mutex.lock(); // another thread might have added that IP // meanwhile. non-existing keys have a value of 0 // initially if (ids[caller.s_addr] == 0) { // do the actual update ids[caller.s_addr] = max_id; ++max_id; } ids_mutex.unlock(); } else { ++hits; } // repeat the same for the callee if (ids.find(callee.s_addr) == ids.end()) { ids_mutex.lock(); if (ids[callee.s_addr] == 0) { ids[callee.s_addr] = max_id; ++max_id; } ids_mutex.unlock(); } else { ++hits; } // attribute already contains the '\n' since it's the last // string on the line if (tsv) { fprintf(fout.outf, "%u\t%u\t%s", ids[caller.s_addr], ids[callee.s_addr], attribute); } else if (csv) { fprintf(fout.outf, "%u,%u,%s", ids[caller.s_addr], ids[callee.s_addr], attribute); } else { fprintf(fout.outf, "%u %u %s", ids[caller.s_addr], ids[callee.s_addr], attribute); } if (++lines % 100000 == 0) { logstream(LOG_INFO) << "Edges: " << lines << ", Ids: " << ids.size() << ", Hits: " << hits << "\n"; } } logstream(LOG_INFO) << "Finished parsing " << in_files[i] << std::endl; } int main(int argc, const char *argv[]) { global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); // get options debug = get_option_int("debug", 0); std::string dir = get_option_string("file"); omp_set_num_threads(get_option_int("ncpus", 1)); tsv = get_option_int("tsv", 0); // is this tab seperated file? csv = get_option_int("csv", 0); // is the comma seperated file? if (tsv) token = "\t"; else if (csv) token = ","; else token = " "; // read list-of files FILE * f = fopen(dir.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL) << "Failed to open file list!" << std::endl; while(true){ char buf[256]; int rc = fscanf(f, "%s\n", buf); if (rc < 1) break; in_files.push_back(buf); } // process each file (possibly in parallel) #pragma omp parallel for(unsigned i = 0; i < in_files.size(); ++i) { parse(i); } // serialize the id-map logstream(LOG_INFO) << "serializing ids..." << std::endl; out_file fout(std::string(dir + ".map").c_str()); for (std::map<unsigned int, unsigned int>::const_iterator it = ids.begin(); it != ids.end(); ++it) { if (tsv) fprintf(fout.outf, "%u\t%u\n", it->first, it->second); else if (csv) fprintf(fout.outf, "%u,%u\n", it->first, it->second); else fprintf(fout.outf, "%u %u\n", it->first, it->second); } return 0; }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Written by Danny Bickson, CMU * * File for converting graph in SNAP format to GraphChi CF toolkit format. * See SNAP format explanation here: http://docs.graphlab.org/graph_formats.html * See GraphChi matrix market format here: http://bickson.blogspot.co.il/2012/02/matrix-market-format.html */ #include <cstdio> #include <map> #include <iostream> #include <map> #include <omp.h> #include <assert.h> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/timer.hpp" #include "../collaborative_filtering/util.hpp" #include "../../example_apps/matrix_factorization/matrixmarket/mmio.h" #include "../../example_apps/matrix_factorization/matrixmarket/mmio.c" using namespace std; using namespace graphchi; bool debug = false; map<string,uint> string2nodeid; map<uint,string> nodeid2hash; map<string,uint> string2nodeid2; map<uint,string> nodeid2hash2; uint conseq_id; uint conseq_id2; mutex mymutex; timer mytime; size_t lines; unsigned long long total_lines = 0; string dir; string outdir; std::vector<std::string> in_files; uint M,N; size_t nnz = 0; const char * string_to_tokenize; int csv = 0; int tsv = 0; int binary = 0; //edges are binary, contain no weights int single_domain = 0; //both user and movies ids are from the same id space:w const char * spaces = " \r\n\t"; const char * tsv_spaces = "\t\n"; const char * csv_spaces = ",\n"; void save_map_to_text_file(const std::map<std::string,uint> & map, const std::string filename){ std::map<std::string,uint>::const_iterator it; out_file fout(filename); unsigned int total = 0; for (it = map.begin(); it != map.end(); it++){ fprintf(fout.outf, "%s %u\n", it->first.c_str(), it->second); total++; } logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl; } void save_map_to_text_file(const std::map<uint,std::string> & map, const std::string filename){ std::map<uint,std::string>::const_iterator it; out_file fout(filename); unsigned int total = 0; for (it = map.begin(); it != map.end(); it++){ fprintf(fout.outf, "%u %s\n", it->first, it->second.c_str()); total++; } logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl; } /* * assign a consecutive id from either the [from] or [to] ids. */ void assign_id(map<string,uint> & string2nodeid, map<uint,string> & nodeid2hash, uint & outval, const string &name, bool from){ map<string,uint>::iterator it = string2nodeid.find(name); //if an id was already assigned, return it if (it != string2nodeid.end()){ outval = it->second; return; } mymutex.lock(); //assign a new id outval = string2nodeid[name]; if (outval == 0){ //update the mapping between string to the id string2nodeid[name] = (from? ++conseq_id : ++conseq_id2); //return the id outval = (from? conseq_id : conseq_id2); //store the reverse mapping between id to string nodeid2hash[outval] = name; if (from) M = std::max(M, conseq_id); else N = std::max(N, conseq_id2); } mymutex.unlock(); } /* example file format: * 2884424247 11 1210682095 1789803763 1879013170 1910216645 2014570227 * 2109318072 2268277425 2289674265 2340794623 2513611825 2770280793 * 2884596247 31 1191220232 1191258123 1225281292 1240067740 * 2885009247 16 1420862042 1641392180 1642909335 1775498871 1781379945 * 1784537661 1846581167 1934183965 2011304655 2016713117 2017390697 * 2128869911 2132021133 2645747085 2684129850 2866009832 */ void parse(int i){ in_file fin(in_files[i]); out_file fout((outdir + in_files[i] + ".out")); size_t linesize = 0; char * saveptr = NULL, * linebuf = NULL; char linebuf_debug[1024]; size_t line = 1; uint from,to; bool matrix_market = false; while(true){ int rc = getline(&linebuf, &linesize, fin.outf); strncpy(linebuf_debug, linebuf, 1024); if (rc < 1) break; if (strlen(linebuf) <= 1) //skip empty lines continue; //skipping over matrix market header (if any) if (!strncmp(linebuf, "%%MatrixMarket", 14)){ matrix_market = true; continue; } if (matrix_market && linebuf[0] == '%'){ continue; } if (matrix_market && linebuf[0] != '%'){ matrix_market = false; continue; } //read [FROM] char *pch = strtok_r(linebuf,string_to_tokenize, &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf_debug << "]" << std::endl; return; } assign_id(string2nodeid,nodeid2hash, from, pch, true); //read [NUMBER OF EDGES] pch = strtok_r(NULL,string_to_tokenize, &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf_debug << "]" << std::endl; return; } int num_edges = atoi(pch); if (num_edges < 0) { logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf_debug << "] - number of edges < 0" << std::endl; return; } for (int k=0; k< num_edges; k++){ pch = strtok_r(NULL, "\n\t\r, ", &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf_debug << "]" << std::endl; return; } assign_id(single_domain ? string2nodeid:string2nodeid2, single_domain ? nodeid2hash : nodeid2hash2, to, pch, single_domain ? true : false); if (tsv) fprintf(fout.outf, "%u\t%u\n", from, to); else if (csv) fprintf(fout.outf, "%u,%un", from, to); else fprintf(fout.outf, "%u %u\n", from, to); nnz++; } line++; total_lines++; if (lines && line>=lines) break; if (debug && (line % 50000 == 0)) logstream(LOG_INFO) << "Parsed line: " << line << " map size is: " << string2nodeid.size() << std::endl; if (string2nodeid.size() % 500000 == 0) logstream(LOG_INFO) << "Hash map size: " << string2nodeid.size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl; } logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl << "total map size: " << string2nodeid.size() << endl; } int main(int argc, const char *argv[]) { logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any " " comments or bug reports to danny.bickson@gmail.com " << std::endl; global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); debug = get_option_int("debug", 0); dir = get_option_string("file_list"); lines = get_option_int("lines", 0); omp_set_num_threads(get_option_int("ncpus", 1)); tsv = get_option_int("tsv", 0); //is this tab seperated file? csv = get_option_int("csv", 0); // is the comma seperated file? binary = get_option_int("binary", 0); single_domain = get_option_int("single_domain", 0); mytime.start(); string_to_tokenize = spaces; if (tsv) string_to_tokenize = tsv_spaces; else if (csv) string_to_tokenize = csv_spaces; FILE * f = fopen(dir.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl; while(true){ char buf[256]; int rc = fscanf(f, "%s\n", buf); if (rc < 1) break; in_files.push_back(buf); } if (in_files.size() == 0) logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl; //#pragma omp parallel for for (uint i=0; i< in_files.size(); i++) parse(i); std::cout << "Finished in " << mytime.current_time() << std::endl; save_map_to_text_file(string2nodeid, outdir + dir + "user.map.text"); save_map_to_text_file(nodeid2hash, outdir + dir + "user.reverse.map.text"); if (!single_domain){ save_map_to_text_file(string2nodeid2, outdir + dir + "movie.map.text"); save_map_to_text_file(nodeid2hash2, outdir + dir + "movie.reverse.map.text"); } logstream(LOG_INFO)<<"Writing matrix market header into file: matrix_market.info" << std::endl; out_file fout("matrix_market.info"); MM_typecode out_typecode; mm_clear_typecode(&out_typecode); mm_set_integer(&out_typecode); mm_set_sparse(&out_typecode); mm_set_matrix(&out_typecode); mm_write_banner(fout.outf, out_typecode); mm_write_mtx_crd_size(fout.outf, M, single_domain ? M : N, nnz); return 0; }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Written by Danny Bickson, CMU */ #include <cstdio> #include <map> #include <iostream> #include <map> #include <omp.h> #include <assert.h> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/timer.hpp" #include "../collaborative_filtering/util.hpp" #include "../../example_apps/matrix_factorization/matrixmarket/mmio.h" #include "../../example_apps/matrix_factorization/matrixmarket/mmio.c" #include "common.hpp" using namespace std; using namespace graphchi; #define DIVIDE_FACTOR 1 mutex mymutexarray[DIVIDE_FACTOR]; bool debug = false; map<unsigned long long,uint> string2nodeid[DIVIDE_FACTOR]; //map<uint,string> nodeid2hash; map<unsigned long long,uint> string2nodeid2[DIVIDE_FACTOR]; //map<uint,string> nodeid2hash2; uint conseq_id; uint conseq_id2; timer mytime; size_t lines; unsigned long long total_lines = 0; string dir; string outdir; std::vector<std::string> in_files; uint M,N; size_t nnz = 0; const char * string_to_tokenize; int csv = 0; int tsv = 0; int binary = 0; //edges are binary, contain no weights int single_domain = 0; //both user and movies ids are from the same id space:w const char * spaces = " \r\n\t"; const char * tsv_spaces = "\t\n"; const char * csv_spaces = ",\n"; timer mytimer; int ncpus = 1; /* * assign a consecutive id from either the [from] or [to] ids. */ void assign_id(map<unsigned long long,uint> & string2nodeid, uint & outval, const unsigned long long name, bool from, int mod){ map<unsigned long long,uint>::iterator it = string2nodeid.find(name); //if an id was already assigned, return it if (it != string2nodeid.end()){ outval = it->second; return; } if (ncpus > 1) mymutexarray[mod].lock(); //assign a new id outval = string2nodeid[name]; if (outval == 0){ //update the mapping between string to the id string2nodeid[name] = ((from || single_domain)? ++conseq_id : ++conseq_id2); //return the id outval = ((from || single_domain)? conseq_id : conseq_id2); } if (ncpus > 1) mymutexarray[mod].unlock(); } void parse(int i){ in_file fin(in_files[i]); out_file fout((outdir + in_files[i] + ".out")); size_t linesize = 0; char * saveptr = NULL, * linebuf = NULL; size_t line = 1; uint from,to; bool matrix_market = false; while(true){ int rc = getline(&linebuf, &linesize, fin.outf); if (rc < 1) break; if (strlen(linebuf) <= 1){ //skip empty lines continue; } //skipping over matrix market header (if any) if (!strncmp(linebuf, "%%MatrixMarket", 14)){ matrix_market = true; continue; } if (matrix_market && linebuf[0] == '%'){ continue; } if (matrix_market && linebuf[0] != '%'){ matrix_market = false; continue; } //read [FROM] char *pch = strtok_r(linebuf,string_to_tokenize, &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } unsigned long long id = atoll(pch); int mod = id % DIVIDE_FACTOR; assign_id(string2nodeid[mod], from, atoll(pch), true, mod); //read [TO] pch = strtok_r(NULL,string_to_tokenize, &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } id = atoll(pch); int mod2 = id % DIVIDE_FACTOR; assign_id(single_domain ? string2nodeid[mod]:string2nodeid2[mod2], to, atoll(pch), single_domain ? true : false, single_domain ? mod : mod2); //read the rest of the line if (!binary){ pch = strtok_r(NULL, "\n", &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } } if (tsv) fprintf(fout.outf, "%d%u\t%d%u\t%s\n", mod, from, mod2, to, binary? "": pch); else if (csv) fprintf(fout.outf, "%d%u,%d%u,%s\n", mod, from, mod2, to, binary? "" : pch); else fprintf(fout.outf, "%d%u %d%u %s\n", mod, from, mod2, to, binary? "" : pch); nnz++; line++; total_lines++; if (lines && line>=lines) break; if (debug && (line % 1000000 == 0)) logstream(LOG_INFO) << mytimer.current_time() << ") Parsed line: " << line << " map size is: " << string2nodeid[0].size() << std::endl; if (string2nodeid[0].size() % 100000 == 0) logstream(LOG_INFO) << mytimer.current_time() << ") Hash map size: " << string2nodeid[0].size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl; } logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl << "total map size: " << string2nodeid[0].size() << endl; } int main(int argc, const char *argv[]) { logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any " " comments or bug reports to danny.bickson@gmail.com " << std::endl; global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); mytimer.start(); debug = get_option_int("debug", 0); dir = get_option_string("file_list"); lines = get_option_int("lines", 0); ncpus = get_option_int("ncpus", ncpus); omp_set_num_threads(ncpus); tsv = get_option_int("tsv", 0); //is this tab seperated file? csv = get_option_int("csv", 0); // is the comma seperated file? binary = get_option_int("binary", 0); single_domain = get_option_int("single_domain", 0); mytime.start(); string_to_tokenize = spaces; if (tsv) string_to_tokenize = tsv_spaces; else if (csv) string_to_tokenize = csv_spaces; FILE * f = fopen(dir.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl; while(true){ char buf[256]; int rc = fscanf(f, "%s\n", buf); if (rc < 1) break; in_files.push_back(buf); } if (in_files.size() == 0) logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl; #pragma omp parallel for for (uint i=0; i< in_files.size(); i++) parse(i); std::cout << "Finished in " << mytime.current_time() << std::endl; M = 0; for (int i=0; i< DIVIDE_FACTOR; i++) M += string2nodeid[i].size(); if (single_domain) N = M; else { N = 0; for (int i=0; i< DIVIDE_FACTOR; i++) N += string2nodeid2[i].size(); } #pragma omp parallel for for (int i=0; i< DIVIDE_FACTOR; i++){ char buf[256]; sprintf(buf, "user.map.%d", i); save_map_to_text_file(string2nodeid[i], outdir + std::string(buf)); if (!single_domain){ save_map_to_text_file(string2nodeid2[i], outdir + std::string(buf)); } } logstream(LOG_INFO)<<"Writing matrix market header into file: matrix_market.info" << std::endl; out_file fout("matrix_market.info"); MM_typecode out_typecode; mm_clear_typecode(&out_typecode); mm_set_integer(&out_typecode); mm_set_sparse(&out_typecode); mm_set_matrix(&out_typecode); mm_write_banner(fout.outf, out_typecode); mm_write_mtx_crd_size(fout.outf, M, N, nnz); return 0; }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Written by Danny Bickson, CMU */ #include <cstdio> #include <map> #include <iostream> #include <map> #include <omp.h> #include <assert.h> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/timer.hpp" #include "../collaborative_filtering/util.hpp" #include "../../example_apps/matrix_factorization/matrixmarket/mmio.h" #include "../../example_apps/matrix_factorization/matrixmarket/mmio.c" #include "common.hpp" using namespace std; using namespace graphchi; bool debug = false; map<string,uint> string2nodeid; //map<uint,string> nodeid2hash; map<string,uint> string2nodeid2; //map<uint,string> nodeid2hash2; uint conseq_id; uint conseq_id2; timer mytime; size_t lines; unsigned long long total_lines = 0; string dir; string outdir; std::vector<std::string> in_files; uint M,N; size_t nnz = 0; const char * string_to_tokenize; int csv = 0; int tsv = 0; int binary = 0; //edges are binary, contain no weights int single_domain = 0; //both user and movies ids are from the same id space:w const char * spaces = " \r\n\t"; const char * tsv_spaces = "\t\n"; const char * csv_spaces = "\",\n"; timer mytimer; int has_header_titles = 0; int ignore_rest_of_line = 0; /* * assign a consecutive id from either the [from] or [to] ids. */ void assign_id(map<string,uint> & string2nodeid, uint & outval, const string &name, bool from){ map<string,uint>::iterator it = string2nodeid.find(name); //if an id was already assigned, return it if (it != string2nodeid.end()){ outval = it->second; return; } mymutex.lock(); //assign a new id outval = string2nodeid[name]; if (outval == 0){ //update the mapping between string to the id string2nodeid[name] = ((from || single_domain)? ++conseq_id : ++conseq_id2); //return the id outval = ((from || single_domain)? conseq_id : conseq_id2); } mymutex.unlock(); } void parse(int i){ in_file fin(in_files[i]); out_file fout((outdir + in_files[i] + ".out")); size_t linesize = 0; char * saveptr = NULL, * linebuf = NULL; size_t line = 1; uint from,to; bool matrix_market = false; while(true){ int rc = getline(&linebuf, &linesize, fin.outf); if (rc < 1) break; if (strlen(linebuf) <= 1){ //skip empty lines line++; continue; } if (has_header_titles && line == 1){ line++; continue; } //skipping over matrix market header (if any) if (!strncmp(linebuf, "%%MatrixMarket", 14)){ matrix_market = true; continue; } if (matrix_market && linebuf[0] == '%'){ continue; } if (matrix_market && linebuf[0] != '%'){ matrix_market = false; continue; } //read [FROM] char *pch = strtok_r(linebuf,string_to_tokenize, &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } assign_id(string2nodeid, from, pch, true); //read [TO] pch = strtok_r(NULL,string_to_tokenize, &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } assign_id(single_domain ? string2nodeid:string2nodeid2, to, pch, single_domain ? true : false); //read the rest of the line if (!binary){ if (ignore_rest_of_line) pch = strtok_r(NULL, string_to_tokenize, &saveptr); else pch = strtok_r(NULL, "\n", &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } } if (tsv) fprintf(fout.outf, "%u\t%u\t%s\n", from, to, binary? "": pch); else if (csv) fprintf(fout.outf, "%u %u %s\n", from, to, binary? "" : pch); else fprintf(fout.outf, "%u %u %s\n", from, to, binary? "" : pch); nnz++; line++; total_lines++; if (lines && line>=lines) break; if (debug && (line % 50000 == 0)) logstream(LOG_INFO) << mytimer.current_time() << ") Parsed line: " << line << " map size is: " << string2nodeid.size() << std::endl; if (string2nodeid.size() % 500000 == 0) logstream(LOG_INFO) << mytimer.current_time() << ") Hash map size: " << string2nodeid.size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl; } logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl << "total map size: " << string2nodeid.size() << endl; } int main(int argc, const char *argv[]) { logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any " " comments or bug reports to danny.bickson@gmail.com " << std::endl; global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); mytimer.start(); debug = get_option_int("debug", 0); dir = get_option_string("file_list"); lines = get_option_int("lines", 0); omp_set_num_threads(get_option_int("ncpus", 1)); tsv = get_option_int("tsv", 0); //is this tab seperated file? csv = get_option_int("csv", 0); // is the comma seperated file? binary = get_option_int("binary", 0); single_domain = get_option_int("single_domain", 0); has_header_titles = get_option_int("has_header_titles", has_header_titles); ignore_rest_of_line = get_option_int("ignore_rest_of_line", ignore_rest_of_line); mytime.start(); string_to_tokenize = spaces; if (tsv) string_to_tokenize = tsv_spaces; else if (csv) string_to_tokenize = csv_spaces; FILE * f = fopen(dir.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl; while(true){ char buf[256]; int rc = fscanf(f, "%s\n", buf); if (rc < 1) break; in_files.push_back(buf); } if (in_files.size() == 0) logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl; #pragma omp parallel for for (uint i=0; i< in_files.size(); i++) parse(i); std::cout << "Finished in " << mytime.current_time() << std::endl; M = string2nodeid.size(); if (single_domain) N = M; else N = string2nodeid2.size(); save_map_to_text_file(string2nodeid, outdir + dir + "user.map.text"); if (!single_domain){ save_map_to_text_file(string2nodeid2, outdir + dir + "movie.map.text"); } logstream(LOG_INFO)<<"Writing matrix market header into file: matrix_market.info" << std::endl; out_file fout("matrix_market.info"); MM_typecode out_typecode; mm_clear_typecode(&out_typecode); mm_set_integer(&out_typecode); mm_set_sparse(&out_typecode); mm_set_matrix(&out_typecode); mm_write_banner(fout.outf, out_typecode); mm_write_mtx_crd_size(fout.outf, M, N, nnz); return 0; }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * */ #include <cstdio> #include <map> #include <iostream> #include <map> #include <omp.h> #include <assert.h> #include <algorithm> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/timer.hpp" #include "../collaborative_filtering/util.hpp" using namespace std; using namespace graphchi; bool debug = false; map<string,uint> string2nodeid; map<uint,string> nodeid2hash; map<uint,uint> tweets_per_user; uint conseq_id; mutex mymutex; timer mytime; size_t lines = 0, links_found = 0, http_links = 0, missing_names = 0, retweet_found = 0, wide_tweets = 0; unsigned long long total_lines = 0; string dir; string outdir; std::vector<std::string> in_files; const char user_chars_tokens[] = {" \r\n\t,.\"!?#%^&*()|-\'+$/:"}; uint maxfrom = 0; uint maxto = 0; void save_map_to_text_file(const std::map<std::string,uint> & map, const std::string filename){ std::map<std::string,uint>::const_iterator it; out_file fout(filename); unsigned int total = 0; for (it = map.begin(); it != map.end(); it++){ fprintf(fout.outf, "%s %u\n", it->first.c_str(), it->second); total++; } logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl; } void save_map_to_text_file(const std::map<uint,std::string> & map, const std::string filename){ std::map<uint,std::string>::const_iterator it; out_file fout(filename); unsigned int total = 0; for (it = map.begin(); it != map.end(); it++){ fprintf(fout.outf, "%u %s\n", it->first, it->second.c_str()); total++; } logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl; } void save_map_to_text_file(const std::map<uint,uint> & map, const std::string filename){ std::map<uint,uint>::const_iterator it; out_file fout(filename); unsigned int total = 0; for (it = map.begin(); it != map.end(); it++){ fprintf(fout.outf, "%u %u\n", it->first, it->second); total++; } logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl; } /* * If this is a legal user name, assign an integer id to this user name * * What Characters Are Allowed in Twitter Usernames * * Taken from: http://kagan.mactane.org/blog/2009/09/22/what-characters-are-allowed-in-twitter-usernames/ * * A while back, when I was writing Hummingbird, I needed to look for Twitter usernames in various strings. More recently, I’m doing some work that involves Twitter at my new job. Once again, I need to find and match on Twitter usernames. * * Luckily, this time, Twitter seems to have updated its signup page with some nice AJAX that constrains the user’s options, and provides helpful feedback. So, for anyone else who needs this information in the future, here’s the scoop: * * Letters, numbers, and underscores only. It’s case-blind, so you can enter hi_there, Hi_There, or HI_THERE and they’ll all work the same (and be treated as a single account). * There is apparently no minimum-length requirement; the user a exists on Twitter. Maximum length is 15 characters. * There is also no requirement that the name contain letters at all; the user 69 exists, as does a user whose name I can’t pronounce */ bool assign_id(uint & outval, string name, const int line, const string &filename){ if (name.size() == 0 || strstr(name.c_str(), "/") || strstr(name.c_str(), ":") || name.size() > 15) return false; for (uint i=0; i< name.size(); i++) name[i] = tolower(name[i]); const char shtrudel[]= {"@"}; name.erase (std::remove(name.begin(), name.end(), shtrudel[0]), name.end()); map<string,uint>::iterator it = string2nodeid.find(name); if (it != string2nodeid.end()){ outval = it->second; return true; } mymutex.lock(); outval = string2nodeid[name]; if (outval == 0){ string2nodeid[name] = ++conseq_id; outval = conseq_id; nodeid2hash[outval] = name; } mymutex.unlock(); return true; } /* * U http://twitter.com/xlamp */ bool extract_user_name(const char * linebuf, size_t line, int i, char * saveptr, char * userid){ char *pch = strtok_r(NULL, user_chars_tokens,&saveptr); //HTTP if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } pch = strtok_r(NULL,user_chars_tokens,&saveptr); //TWITTER if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } pch = strtok_r(NULL,user_chars_tokens,&saveptr); //COM if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } pch = strtok_r(NULL,user_chars_tokens,&saveptr); //USERNAME if (!pch){ logstream(LOG_WARNING) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; missing_names++; return false; } for (uint j=0; j< strlen(pch); j++) pch[j] = tolower(pch[j]); //make user name lower strncpy(userid, pch, 256); return true; } bool convert_string_to_time(const char * linebuf, size_t line, int i, char * saveptr, long int & outtime){ struct tm ptm; char *year = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!year){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_year = atoi(year) - 1900; char *month = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!month){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_mon = atoi(month) - 1; char *day = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!day){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_mday = atoi(day); char *hour = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!hour){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_hour = atoi(hour); char *minute = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!minute){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_min = atoi(minute); char *second = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!second){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_sec = atoi(second); outtime = mktime(&ptm); return true; } bool parse_links(const char * linebuf, size_t line, int i, char * saveptr, uint id, long int ptime, FILE * f){ uint otherid = 0; if (strstr(linebuf, "http://")) http_links++; bool found = false; char * pch = NULL; do { pch = strtok_r(NULL, user_chars_tokens, &saveptr); if (!pch || strlen(pch) == 0) return found; if (pch[0] == '@'){ bool ok = assign_id(otherid, pch+1, line, linebuf); if (ok){ fprintf(f, "%u %u %ld 1\n", id, otherid, ptime); maxfrom = std::max(maxfrom, id); maxto = std::max(maxto, otherid); links_found++; found = true; } if (debug && line < 20) printf("found link between : %u %u in time %ld\n", id, otherid, ptime); } else if (!strncmp(pch, "RT", 2)){ pch = strtok_r(NULL, user_chars_tokens, &saveptr); if (!pch || strlen(pch) == 0) continue; bool ok = assign_id(otherid, pch, line, linebuf); if (ok){ fprintf(f, "%u %u %ld 2\n", id, otherid, ptime); retweet_found++; found = true; } } } while (pch != NULL); return found; } /* * Twitter input format is: * * T 2009-06-11 16:56:42 * U http://twitter.com/tiffnic85 * W Bus is pulling out now. We gotta be in LA by 8 to check into the Paragon. * * T 2009-06-11 16:56:42 * U http://twitter.com/xlamp * W 灰を灰皿に落とそうとすると高確率でヘッドセットの線を根性焼きする形になるんだが * * T 2009-06-11 16:56:43 * U http://twitter.com/danilaselva * W @carolinesweatt There are no orphans...of God! :) Miss your face! * */ void parse(int i){ in_file fin(in_files[i]); out_file fout((outdir + in_files[i] + ".out")); size_t linesize = 0; char * saveptr = NULL, * linebuf = NULL, buf1[256], linebuf_debug[1024]; size_t line = 1; uint id; long int ptime; bool ok; bool first = true; while(true){ int rc = getline(&linebuf, &linesize, fin.outf); strncpy(linebuf_debug, linebuf, 1024); total_lines++; if (rc < 1) break; if (strlen(linebuf) <= 1) //skip empty lines continue; if (first){ first = false; continue; } //skip first line char *pch = strtok_r(linebuf," \r\n\t:/-", &saveptr); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } switch(*pch){ case 'T': ok = convert_string_to_time(linebuf_debug, total_lines, i, saveptr, ptime); if (!ok) return; break; case 'U': ok = extract_user_name(linebuf_debug, total_lines, i, saveptr, buf1); if (ok) assign_id(id, buf1, line, in_files[i]); tweets_per_user[id]++; break; case 'W': ok = parse_links(linebuf_debug, total_lines, i, saveptr, id, ptime, fout.outf); if (debug && line < 20) printf("Found user: %s id %u time %ld\n", buf1, id, ptime); if (!ok) wide_tweets++; break; default: logstream(LOG_ERROR)<<"Error: expecting with T U or W first character" << std::endl; return; } line++; if (lines && line>=lines) break; if (debug && (line % 50000 == 0)) logstream(LOG_INFO) << "Parsed line: " << line << " map size is: " << string2nodeid.size() << std::endl; if (string2nodeid.size() % 500000 == 0) logstream(LOG_INFO) << "Hash map size: " << string2nodeid.size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl; } logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl << "total map size: " << string2nodeid.size() << endl; } int main(int argc, const char *argv[]) { logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any " " comments or bug reports to danny.bickson@gmail.com " << std::endl; global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); debug = get_option_int("debug", 0); dir = get_option_string("file_list"); lines = get_option_int("lines", 0); omp_set_num_threads(get_option_int("ncpus", 1)); mytime.start(); FILE * f = fopen(dir.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl; while(true){ char buf[256]; int rc = fscanf(f, "%s\n", buf); if (rc < 1) break; in_files.push_back(buf); } if (in_files.size() == 0) logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl; #pragma omp parallel for for (uint i=0; i< in_files.size(); i++) parse(i); std::cout << "Finished in " << mytime.current_time() << std::endl << "\t direct tweets found: " << links_found << " \t global tweets: " << wide_tweets << "\t http links: " << http_links << "\t retweets: " << retweet_found << "\t total lines in input file : " << total_lines << " \t invalid records (missing names) " << missing_names << std::endl; save_map_to_text_file(string2nodeid, outdir + "map.text"); save_map_to_text_file(nodeid2hash, outdir + "reverse.map.text"); save_map_to_text_file(tweets_per_user, outdir + "tweets_per_user.text"); out_file fout("mm.info"); fprintf(fout.outf, "%%%%MatrixMarket matrix coordinate real general\n"); fprintf(fout.outf, "%u %u %lu\n", maxfrom+1, maxto+1, links_found); return 0; }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * */ #include <cstdio> #include <iostream> #include <omp.h> #include <assert.h> #include <algorithm> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/timer.hpp" #include "../collaborative_filtering/util.hpp" using namespace std; using namespace graphchi; bool debug = false; timer mytime; size_t lines = 0; unsigned long long total_lines = 0; string dir; string outdir; std::vector<std::string> in_files; const char user_chars_tokens[] = {" \r\n\t,.\"!?#%^&*()|-\'+$/:"}; uint maxfrom = 0; uint maxto = 0; /* 2011-12-05 00:00:00 */ bool convert_string_to_time(char * linebuf, size_t line, int i, long int & outtime){ char * saveptr = NULL; struct tm ptm; memset(&ptm, 0, sizeof(ptm)); char *year = strtok_r(linebuf," \r\n\t:/-",&saveptr); if (!year){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_year = atoi(year) - 1900; char *month = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!month){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_mon = atoi(month) - 1; char *day = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!day){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_mday = atoi(day); char *hour = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!hour){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_hour = atoi(hour); char *minute = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!minute){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_min = atoi(minute); char *second = strtok_r(NULL," \r\n\t:/-",&saveptr); if (!second){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; } ptm.tm_sec = atoi(second); outtime = mktime(&ptm); return true; } /* * The CDR line format is: * * * 2011-12-05 00:00:00 15 15 9 591 * 2011-12-05 00:00:00 15 22 1 39 * 2011-12-05 00:00:00 15 134 1 482 * 2011-12-05 00:00:00 15 180 2 1686 * 2011-12-05 00:00:00 15 355 1 119 * 2011-12-05 00:00:00 15 815 1 63 */ void parse(int i){ in_file fin(in_files[i]); out_file fout((outdir + in_files[i] + ".out")); size_t linesize = 0; char * saveptr2 = NULL, * linebuf = NULL, linebuf_debug[1024]; size_t line = 1; uint from, to, duration1, duration2; long int ptime; while(true){ int rc = getline(&linebuf, &linesize, fin.outf); strncpy(linebuf_debug, linebuf, 1024); total_lines++; if (rc < 1) break; bool ok = convert_string_to_time(linebuf_debug, total_lines, i, ptime); if (!ok) return; char *pch = strtok_r(linebuf,"\t", &saveptr2); //skip the date if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } pch = strtok_r(NULL," \r\n\t:/-", &saveptr2); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } from = atoi(pch); maxfrom = std::max(from, maxfrom); pch = strtok_r(NULL," \r\n\t:/-", &saveptr2); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } to = atoi(pch); maxto = std::max(to, maxto); pch = strtok_r(NULL," \r\n\t:/-", &saveptr2); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } duration1 = atoi(pch); pch = strtok_r(NULL," \r\n\t:/-", &saveptr2); if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; } duration2 = atoi(pch); line++; if (lines && line>=lines) break; if (debug && (line % 100000 == 0)) logstream(LOG_INFO)<<"Parsed line: " << line << endl; fprintf(fout.outf, "%u %u %lu %u\n", from, to, ptime, duration2); } logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl; } int main(int argc, const char *argv[]) { logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any " " comments or bug reports to danny.bickson@gmail.com " << std::endl; global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); debug = get_option_int("debug", 0); dir = get_option_string("file_list"); lines = get_option_int("lines", 0); omp_set_num_threads(get_option_int("ncpus", 1)); mytime.start(); FILE * f = fopen(dir.c_str(), "r"); if (f == NULL) logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl; while(true){ char buf[256]; int rc = fscanf(f, "%s\n", buf); if (rc < 1) break; in_files.push_back(buf); } if (in_files.size() == 0) logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl; //#pragma omp parallel for for (uint i=0; i< in_files.size(); i++) parse(i); std::cout << "Finished in " << mytime.current_time() << std::endl << "\t total lines in input file : " << total_lines << "\t max from: " << maxfrom << "\t max to: " <<maxto << std::endl; return 0; }
C++
/** * Copyright (c) 2009 Carnegie Mellon University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * Written by Danny Bickson, CMU * * This program takes a file in the following graph format format: * 1 61 0.9 * 1 8 0.6 * 2 1 1.2 * 2 2 0.9 * 2 3 0.4 * 2 18 0.13 * 2 21 0.11 * * Namely, a text file where the first field is a "from" field (uint >=1), second field is a "to" field (uint > = 1) * and a numeric value. Note that the file is assumed to be sorted by the "from" field and then the "val" field. *` * The output file is top K values for each entries (or less if there where fewer in the input file) * In the abive example, assuming K = 2 the ouput will be: * 1 61 8 * 2 1 2 * Namely, in each line the first is the "from" frield and the rest are the "to" top fields. * * A second output is * 1 0.9 0.6 * 2 1.2 0.9 * */ #include <cstdio> #include <map> #include <iostream> #include <map> #include <omp.h> #include <assert.h> #include "graphchi_basic_includes.hpp" #include "../collaborative_filtering/timer.hpp" #include "../collaborative_filtering/util.hpp" #include "../collaborative_filtering/eigen_wrapper.hpp" using namespace std; using namespace graphchi; bool debug = false; timer mytime; size_t lines; unsigned long long total_lines = 0; string dir; string outdir; std::vector<std::string> in_files; int col = 3; int K = 10; int has_value = 1; //non word tokens that will be removed in the parsing //it is possible to add additional special characters or remove ones you want to keep const char spaces[] = {" \r\n\t;:"}; void dump_entry(uint from, vec & to_vec, vec & vals_vec, int pos, FILE * out_ids, FILE * out_vals){ assert(pos <= K); fprintf(out_ids, "%u ", from); if (has_value) fprintf(out_vals, "%u ", from); for (int i=0; i< pos; i++){ fprintf(out_ids, "%u ", (uint)to_vec[i]); if (has_value) fprintf(out_vals, "%12.6g ", vals_vec[i]); } fprintf(out_ids, "\n"); if (has_value) fprintf(out_vals, "\n"); } void parse(int i){ in_file fin(in_files[i]); out_file ids_out((outdir + in_files[i] + ".ids")); out_file val_out((outdir + in_files[i] + ".vals")); vec to_vec = zeros(K); vec val_vec = zeros(K); int pos = 0; size_t linesize = 0; char * saveptr = NULL, * linebuf = NULL; size_t line = 1; uint from = 0, to = 0; uint last_from = 0; while(true){ int rc = getline(&linebuf, &linesize, fin.outf); if (rc < 1) break; //char * line_to_free = linebuf; //find from char *pch = strtok_r(linebuf, spaces, &saveptr); if (!pch || atoi(pch)<= 0) logstream(LOG_FATAL) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; from = atoi(pch); //find to pch = strtok_r(NULL, spaces ,&saveptr); if (!pch || atoi(pch)<=0) logstream(LOG_FATAL) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; to = atoi(pch); //find val if (has_value){ pch = strtok_r(NULL, spaces ,&saveptr); if (!pch) logstream(LOG_FATAL) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; } if (from != last_from){ // fprintf(fout.outf, "%u %u %g\n", last_from, last_to, total); if (last_from != 0){ dump_entry(last_from, to_vec, val_vec, pos, ids_out.outf, val_out.outf); pos = 0; } } if (pos>= K) continue; val_vec[pos] = has_value?atof(pch):1.0; to_vec[pos] = to; pos++; //free(line_to_free); last_from = from; total_lines++; line++; if (lines && line>=lines) break; if (debug && (line % 50000 == 0)) logstream(LOG_INFO) << "Parsed line: " << line << std::endl; } if (last_from != 0) dump_entry(last_from, to_vec, val_vec, pos, ids_out.outf, val_out.outf); logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl; } int main(int argc, const char *argv[]) { logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any " " comments or bug reports to danny.bickson@gmail.com " << std::endl; global_logger().set_log_level(LOG_INFO); global_logger().set_log_to_console(true); graphchi_init(argc, argv); debug = get_option_int("debug", 0); lines = get_option_int("lines", 0); has_value = get_option_int("has_value", has_value); K = get_option_int("K", K); if (K < 1) logstream(LOG_FATAL)<<"Number of top elements (--K=) should be >= 1"<<std::endl; omp_set_num_threads(get_option_int("ncpus", 1)); mytime.start(); std::string training = get_option_string("training"); in_files.push_back(training); if (in_files.size() == 0) logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl; parse(0); std::cout << "Finished in " << mytime.current_time() << std::endl; return 0; }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/appenderskeleton.h> #include <vector> #include <log4cxx/spi/loggingevent.h> namespace log4cxx { /** An appender that appends logging events to a vector. */ class VectorAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(VectorAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(VectorAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() std::vector<spi::LoggingEventPtr> vector; /** This method is called by the AppenderSkeleton#doAppend method. */ void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p); const std::vector<spi::LoggingEventPtr>& getVector() const { return vector; } void close(); bool isClosed() const { return closed; } bool requiresLayout() const { return false; } }; typedef helpers::ObjectPtrT<VectorAppender> VectorAppenderPtr; }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(LOG4CXX_TEST_INSERT_WIDE) #define LOG4CXX_TEST_INSERT_WIDE 1 #include <ostream> #include <string> #if LOG4CXX_WCHAR_T_API std::ostream& operator<<(std::ostream& os, const std::wstring& str); #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API std::ostream& operator<<(std::ostream& os, const std::basic_string<log4cxx::UniChar>& str); #endif #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../logunit.h" #include <log4cxx/logmanager.h> #include <log4cxx/logger.h> using namespace log4cxx; LOGUNIT_CLASS(TestCase1) { LOGUNIT_TEST_SUITE(TestCase1); LOGUNIT_TEST(noneTest); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { LogManager::shutdown(); } void noneTest() { LoggerPtr root = Logger::getRootLogger(); LOG4CXX_DEBUG(root, "Hello, world"); bool rootIsConfigured = !root->getAllAppenders().empty(); LOGUNIT_ASSERT(!rootIsConfigured); } }; LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TestCase1)
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG4CXX_TEST 1 #include <log4cxx/private/log4cxx_private.h> #include <log4cxx/logmanager.h> #include <log4cxx/logger.h> #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; LOGUNIT_CLASS(TestCase2) { LOGUNIT_TEST_SUITE(TestCase2); LOGUNIT_TEST(xmlTest); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { LogManager::shutdown(); } void xmlTest() { LoggerPtr root = Logger::getRootLogger(); LOG4CXX_DEBUG(root, "Hello, world"); bool rootIsConfigured = !root->getAllAppenders().empty(); LOGUNIT_ASSERT(rootIsConfigured); AppenderList list = root->getAllAppenders(); AppenderPtr appender = list.front(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("D1"), appender->getName()); } }; LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TestCase2)
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG4CXX_TEST 1 #include <log4cxx/private/log4cxx_private.h> #include <log4cxx/logmanager.h> #include <log4cxx/logger.h> #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; LOGUNIT_CLASS(TestCase4) { LOGUNIT_TEST_SUITE(TestCase4); LOGUNIT_TEST(combinedTest); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { LogManager::shutdown(); } void combinedTest() { LoggerPtr root = Logger::getRootLogger(); LOG4CXX_DEBUG(root, "Hello, world"); bool rootIsConfigured = !root->getAllAppenders().empty(); LOGUNIT_ASSERT(rootIsConfigured); AppenderList list = root->getAllAppenders(); LOGUNIT_ASSERT_EQUAL((size_t) 1, list.size()); AppenderPtr appender = list.front(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("D1"), appender->getName()); } }; LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TestCase4)
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logmanager.h> #include <log4cxx/logger.h> #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; LOGUNIT_CLASS(TestCase3) { LOGUNIT_TEST_SUITE(TestCase3); LOGUNIT_TEST(testProperties); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { LogManager::shutdown(); } void testProperties() { LoggerPtr root = Logger::getRootLogger(); LOG4CXX_DEBUG(root, "Hello, world"); bool rootIsConfigured = !root->getAllAppenders().empty(); LOGUNIT_ASSERT(rootIsConfigured); AppenderList list = root->getAllAppenders(); AppenderPtr appender = list.front(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("D3"), appender->getName()); } }; LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TestCase3)
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> #include "util/compare.h" #include "xml/xlevel.h" #include "logunit.h" #include "testchar.h" #include <log4cxx/spi/loggerrepository.h> using namespace log4cxx; /** Test the configuration of the hierarchy-wide threshold. */ LOGUNIT_CLASS(HierarchyThresholdTestCase) { LOGUNIT_TEST_SUITE(HierarchyThresholdTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST(test7); LOGUNIT_TEST(test8); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { logger->getLoggerRepository()->resetConfiguration(); } void test1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold1.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.1"))); } void test2() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold2.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.2"))); } void test3() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold3.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.3"))); } void test4() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold4.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.4"))); } void test5() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold5.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.5"))); } void test6() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold6.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.6"))); } void test7() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold7.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.7"))); } void test8() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold8.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.8"))); } static void common() { logger->log(XLevel::getTrace(), LOG4CXX_TEST_STR("m0")); logger->debug(LOG4CXX_TEST_STR("m1")); logger->info(LOG4CXX_TEST_STR("m2")); logger->warn(LOG4CXX_TEST_STR("m3")); logger->error(LOG4CXX_TEST_STR("m4")); logger->fatal(LOG4CXX_TEST_STR("m5")); } private: static File TEMP; static LoggerPtr logger; }; File HierarchyThresholdTestCase::TEMP(LOG4CXX_FILE("output/temp")); LoggerPtr HierarchyThresholdTestCase::logger = Logger::getLogger(LOG4CXX_TEST_STR("HierarchyThresholdTestCase")); LOGUNIT_TEST_SUITE_REGISTRATION(HierarchyThresholdTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/ndc.h> #include <log4cxx/file.h> #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> #include "insertwide.h" #include "logunit.h" #include "util/compare.h" using namespace log4cxx; LOGUNIT_CLASS(NDCTestCase) { static File TEMP; static LoggerPtr logger; LOGUNIT_TEST_SUITE(NDCTestCase); LOGUNIT_TEST(testPushPop); LOGUNIT_TEST(test1); LOGUNIT_TEST(testInherit); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { logger->getLoggerRepository()->resetConfiguration(); } /** * Push and pop a value from the NDC */ void testPushPop() { NDC::push("trivial context"); LogString actual(NDC::pop()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("trivial context"), actual); } void test1() { PropertyConfigurator::configure(File("input/ndc/NDC1.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, File("witness/ndc/NDC.1"))); } static void common() { commonLog(); NDC::push("n1"); commonLog(); NDC::push("n2"); NDC::push("n3"); commonLog(); NDC::pop(); commonLog(); NDC::clear(); commonLog(); } static void commonLog() { LOG4CXX_DEBUG(logger, "m1"); LOG4CXX_INFO(logger, "m2"); LOG4CXX_WARN(logger, "m3"); LOG4CXX_ERROR(logger, "m4"); LOG4CXX_FATAL(logger, "m5"); } void testInherit() { NDC::push("hello"); NDC::push("world"); NDC::Stack* clone = NDC::cloneStack(); NDC::clear(); NDC::push("discard"); NDC::inherit(clone); LogString expected1(LOG4CXX_STR("world")); LOGUNIT_ASSERT_EQUAL(expected1, NDC::pop()); LogString expected2(LOG4CXX_STR("hello")); LOGUNIT_ASSERT_EQUAL(expected2, NDC::pop()); LogString expected3; LOGUNIT_ASSERT_EQUAL(expected3, NDC::pop()); } }; File NDCTestCase::TEMP("output/temp"); LoggerPtr NDCTestCase::logger(Logger::getLogger("org.apache.log4j.NDCTestCase")); LOGUNIT_TEST_SUITE_REGISTRATION(NDCTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/spi/loggingevent.h> #include "../util/serializationtesthelper.h" #include <log4cxx/logmanager.h> #include <log4cxx/ndc.h> #include <log4cxx/mdc.h> #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::util; using namespace log4cxx::spi; using namespace std; /** Unit tests for LoggingEvent */ LOGUNIT_CLASS(LoggingEventTest) { LOGUNIT_TEST_SUITE(LoggingEventTest); LOGUNIT_TEST(testSerializationSimple); LOGUNIT_TEST(testSerializationWithLocation); LOGUNIT_TEST(testSerializationNDC); LOGUNIT_TEST(testSerializationMDC); LOGUNIT_TEST_SUITE_END(); public: void setUp() { NDC::clear(); MDC::clear(); } void tearDown() { LogManager::shutdown(); } /** * Serialize a simple logging event and check it against * a witness. * @throws Exception if exception during test. */ void testSerializationSimple() { LoggingEventPtr event = new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LocationInfo::getLocationUnavailable()); LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare( "witness/serialization/simple.bin", event, 237)); } /** * Serialize a logging event with an exception and check it against * a witness. * @throws Exception if exception during test. * */ void testSerializationWithLocation() { LoggingEventPtr event = new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LOG4CXX_LOCATION); LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare( "witness/serialization/location.bin", event, 237)); } /** * Serialize a logging event with ndc. * @throws Exception if exception during test. * */ void testSerializationNDC() { NDC::push("ndc test"); LoggingEventPtr event = new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LocationInfo::getLocationUnavailable()); LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare( "witness/serialization/ndc.bin", event, 237)); } /** * Serialize a logging event with mdc. * @throws Exception if exception during test. * */ void testSerializationMDC() { MDC::put("mdckey", "mdcvalue"); LoggingEventPtr event = new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, world."), LocationInfo::getLocationUnavailable()); LOGUNIT_ASSERT_EQUAL(true, SerializationTestHelper::compare( "witness/serialization/mdc.bin", event, 237)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LoggingEventTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(_LOG4CXX_LOGUNIT_H) #define _LOG4CXX_LOGUNIT_H #if defined(_MSC_VER) #pragma warning (push) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include "abts.h" #include <exception> #include <map> #include <string> #include <vector> #include <log4cxx/logstring.h> namespace LogUnit { class TestException : public std::exception { public: TestException(); TestException(const TestException&); TestException& operator=(const TestException&); }; class AssertException : public std::exception { public: AssertException(std::string msg, int lineno); AssertException(bool expected, const char* actualExpr, int lineno); AssertException(const AssertException&); AssertException& operator=(const AssertException&); virtual ~AssertException() throw(); std::string getMessage() const; int getLine() const; private: std::string msg; int lineno; }; class TestFixture { public: TestFixture(); virtual ~TestFixture(); void setCase(abts_case* tc); virtual void setUp(); virtual void tearDown(); void assertEquals(const int expected, const int actual, int lineno); void assertEquals(const std::string expected, const std::string actual, const char* expectedExpr, const char* actualExpr, int lineno); void assertEquals(const char* expected, const char* actual, const char* expectedExpr, const char* actualExpr, int lineno); #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_WCHAR_T_API void assertEquals(const std::wstring expected, const std::wstring actual, const char* expectedExpr, const char* actualExpr, int lineno); #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API void assertEquals(const std::basic_string<log4cxx::UniChar> expected, const std::basic_string<log4cxx::UniChar> actual, const char* expectedExpr, const char* actualExpr, int lineno); #endif template<class T> void assertEquals(const T& expected, const T& actual, const char* expectedExpr, const char* actualExpr, int lineno) { if (expected != actual) { std::string msg(expectedExpr); msg.append(" != "); msg.append(actualExpr); abts_fail(tc, msg.c_str(), lineno); } } private: TestFixture(const TestFixture&); TestFixture& operator=(const TestFixture&); abts_case* tc; }; template<class T> void runTest(abts_case* tc, void (T::*func)()) { T ti; ti.setCase(tc); ti.setUp(); try { (ti.*func)(); } catch(TestException&) { } catch(AssertException& fx) { abts_fail(tc, fx.getMessage().c_str(), fx.getLine()); } catch(...) { abts_fail(tc, "Unexpected exception", -1); } ti.tearDown(); } template<class T, class X> void runTestWithException(abts_case* tc, void (T::*func)()) { T ti; ti.setCase(tc); ti.setUp(); try { (ti.*func)(); } catch(TestException&) { } catch(AssertException& fx) { abts_fail(tc, fx.getMessage().c_str(), fx.getLine()); } catch(X&) { } catch(...) { abts_fail(tc, "Unexpected exception", -1); } ti.tearDown(); } class TestSuite { public: TestSuite(const char* filename); void addTest(const char* testName, test_func func); abts_suite* run(abts_suite* suite) const; std::string getName() const; void setDisabled(bool newVal); bool isDisabled() const; private: TestSuite(const TestSuite&); TestSuite& operator=(const TestSuite&); typedef std::vector<test_func> TestList; TestList test_funcs; std::string filename; bool disabled; }; typedef std::vector< std::pair<std::string, const TestSuite*> > SuiteList; SuiteList& getAllSuites(); template<class T> class RegisterSuite { public: RegisterSuite() { T::populateSuite(); TestSuite* suite = T::getSuite(); LogUnit::getAllSuites().push_back(SuiteList::value_type(suite->getName(), suite)); } }; template<class T> class RegisterDisabledSuite { public: RegisterDisabledSuite() { T::populateSuite(); TestSuite* suite = T::getSuite(); suite->setDisabled(true); LogUnit::getAllSuites().push_back(SuiteList::value_type(suite->getName(), suite)); } }; } #define LOGUNIT_CLASS(x) class x : public LogUnit::TestFixture #define LOGUNIT_TEST_SUITE(TF) \ public: \ static LogUnit::TestSuite* getSuite() { \ static LogUnit::TestSuite suite(__FILE__); \ return &suite; \ } \ private: \ class RegisterSuite { \ public: \ typedef TF ThisFixture; #define LOGUNIT_TEST(testName) \ class testName ## Registration { \ public: \ testName ## Registration() { \ ThisFixture::getSuite()->addTest(#testName, &testName ## Registration :: run); \ } \ static void run(abts_case* tc, void*) { \ LogUnit::runTest<ThisFixture>(tc, &ThisFixture::testName); \ } \ } register ## testName; #define LOGUNIT_TEST_EXCEPTION(testName, Exception) \ class testName ## Registration { \ public: \ testName ## Registration() { \ ThisFixture::getSuite()->addTest(#testName, &testName ## Registration :: run); \ } \ static void run(abts_case* tc, void*) { \ LogUnit::runTestWithException<ThisFixture, Exception>(tc, &ThisFixture::testName); \ } \ } register ## testName; #define LOGUNIT_TEST_SUITE_END() \ }; \ public: \ static void populateSuite() { \ static RegisterSuite registration; \ } #define LOGUNIT_TEST_SUITE_REGISTRATION(TF) \ static LogUnit::RegisterSuite<TF> registration; #define LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TF) \ static LogUnit::RegisterDisabledSuite<TF> registration; #define LOGUNIT_ASSERT(x) { if (!(x)) throw LogUnit::AssertException(true, #x, __LINE__); } #define LOGUNIT_ASSERT_EQUAL(expected, actual) assertEquals(expected, actual, #expected, #actual, __LINE__) #define LOGUNIT_FAIL(msg) throw LogUnit::AssertException(msg, __LINE__) #if defined(_MSC_VER) #pragma warning (pop) #endif #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/inetaddress.h> #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(InetAddressTestCase) { LOGUNIT_TEST_SUITE(InetAddressTestCase); LOGUNIT_TEST(testGetLocalHost); LOGUNIT_TEST(testByNameLocal); LOGUNIT_TEST(testAllByNameLocal); LOGUNIT_TEST(testUnreachable); LOGUNIT_TEST_SUITE_END(); public: /** * Tests the InetAddress::getLocalHost() method. */ void testGetLocalHost() { InetAddressPtr addr = InetAddress::getLocalHost(); LOGUNIT_ASSERT(addr->getHostAddress() == LOG4CXX_STR("127.0.0.1")); LOGUNIT_ASSERT(!addr->getHostName().empty()); } /** * Tests the InetAddress::getByName() method with the * "localhost" host name. */ void testByNameLocal() { InetAddressPtr addr = InetAddress::getByName(LOG4CXX_STR("localhost")); LOGUNIT_ASSERT(addr->getHostAddress() == LOG4CXX_STR("127.0.0.1")); LOGUNIT_ASSERT(!addr->getHostName().empty()); } /** * Tests the InetAddress::getAllByName() method with the * "localhost" host name. */ void testAllByNameLocal() { std::vector<InetAddressPtr> addr = InetAddress::getAllByName(LOG4CXX_STR("localhost")); LOGUNIT_ASSERT(addr.size() > 0); } /** * Tests the UnknownHostException. */ void testUnknownHost() { InetAddressPtr addr = InetAddress::getByName(LOG4CXX_STR("unknown.invalid")); } /** * Tests an (likely) unreachable address. */ void testUnreachable() { InetAddressPtr addr(InetAddress::getByName(LOG4CXX_STR("192.168.10.254"))); LogString addrStr(addr->toString()); LOGUNIT_ASSERT_EQUAL(addrStr.size() - 15, addrStr.find(LOG4CXX_STR("/192.168.10.254"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(InetAddressTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../logunit.h" #include <log4cxx/helpers/syslogwriter.h> using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(SyslogWriterTest) { LOGUNIT_TEST_SUITE(SyslogWriterTest); LOGUNIT_TEST(testUnknownHost); LOGUNIT_TEST_SUITE_END(); public: /** * Tests writing to an unknown host. */ void testUnknownHost() { SyslogWriter writer(LOG4CXX_STR("unknown.invalid")); writer.write(LOG4CXX_STR("Hello, Unknown World.")); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SyslogWriterTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/charsetdecoder.h> #include "../logunit.h" #include "../insertwide.h" #include <log4cxx/helpers/bytebuffer.h> using namespace log4cxx; using namespace log4cxx::helpers; #define APR_SUCCESS ((log4cxx_status_t) 0) LOGUNIT_CLASS(CharsetDecoderTestCase) { LOGUNIT_TEST_SUITE(CharsetDecoderTestCase); LOGUNIT_TEST(decode1); LOGUNIT_TEST(decode2); LOGUNIT_TEST(decode8); LOGUNIT_TEST_SUITE_END(); enum { BUFSIZE = 256 }; public: void decode1() { char buf[] = "Hello, World"; ByteBuffer src(buf, strlen(buf)); CharsetDecoderPtr dec(CharsetDecoder::getDefaultDecoder()); LogString greeting; log4cxx_status_t stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 12, src.position()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Hello, World"), greeting); } void decode2() { char buf[BUFSIZE + 6]; memset(buf, 'A', BUFSIZE); buf[BUFSIZE - 3] = 0; #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strcat_s(buf, sizeof buf, "Hello"); #else strcat(buf, "Hello"); #endif ByteBuffer src(buf, strlen(buf)); CharsetDecoderPtr dec(CharsetDecoder::getDefaultDecoder()); LogString greeting; log4cxx_status_t stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 0, src.remaining()); stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LogString manyAs(BUFSIZE - 3, LOG4CXX_STR('A')); LOGUNIT_ASSERT_EQUAL(manyAs, greeting.substr(0, BUFSIZE - 3)); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("Hello")), greeting.substr(BUFSIZE - 3)); } void decode8() { char buf[] = { 'H', 'e', 'l', 'l', 'o', ',', 0, 'W', 'o', 'r', 'l', 'd'}; ByteBuffer src(buf, 12); CharsetDecoderPtr dec(CharsetDecoder::getDefaultDecoder()); LogString greeting; log4cxx_status_t stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 12, src.position()); const logchar expected[] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x00, 0x57, 0x6F, 0x72, 0x6C, 0x64 }; LOGUNIT_ASSERT_EQUAL(LogString(expected, 12), greeting); } }; LOGUNIT_TEST_SUITE_REGISTRATION(CharsetDecoderTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/messagebuffer.h> #include <iomanip> #include "../insertwide.h" #include "../logunit.h" #include <log4cxx/logstring.h> #if LOG4CXX_CFSTRING_API #include <CoreFoundation/CFString.h> #endif using namespace log4cxx; using namespace log4cxx::helpers; /** * Test MessageBuffer. */ LOGUNIT_CLASS(MessageBufferTest) { LOGUNIT_TEST_SUITE(MessageBufferTest); LOGUNIT_TEST(testInsertChar); LOGUNIT_TEST(testInsertConstStr); LOGUNIT_TEST(testInsertStr); LOGUNIT_TEST(testInsertString); LOGUNIT_TEST(testInsertNull); LOGUNIT_TEST(testInsertInt); LOGUNIT_TEST(testInsertManipulator); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(testInsertConstWStr); LOGUNIT_TEST(testInsertWString); LOGUNIT_TEST(testInsertWStr); #endif #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(testInsertConstUStr); LOGUNIT_TEST(testInsertUString); #endif #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(testInsertCFString); #endif LOGUNIT_TEST_SUITE_END(); public: void testInsertChar() { MessageBuffer buf; std::string greeting("Hello, World"); CharMessageBuffer& retval = buf << "Hello, Worl" << 'd'; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertConstStr() { MessageBuffer buf; std::string greeting("Hello, World"); CharMessageBuffer& retval = buf << "Hello" << ", World"; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertStr() { MessageBuffer buf; std::string greeting("Hello, World"); char* part1 = (char*) malloc(10*sizeof(wchar_t)); strcpy(part1, "Hello"); char* part2 = (char*) malloc(10*sizeof(wchar_t)); strcpy(part2, ", World"); CharMessageBuffer& retval = buf << part1 << part2; free(part1); free(part2); LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertString() { MessageBuffer buf; std::string greeting("Hello, World"); CharMessageBuffer& retval = buf << std::string("Hello") << std::string(", World"); LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertNull() { MessageBuffer buf; std::string greeting("Hello, null"); CharMessageBuffer& retval = buf << "Hello, " << (const char*) 0; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertInt() { MessageBuffer buf; std::string greeting("Hello, 5"); std::ostream& retval = buf << "Hello, " << 5; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(true, buf.hasStream()); } void testInsertManipulator() { MessageBuffer buf; std::string greeting("pi=3.142"); std::ostream& retval = buf << "pi=" << std::setprecision(4) << 3.1415926; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(true, buf.hasStream()); } #if LOG4CXX_WCHAR_T_API void testInsertConstWStr() { MessageBuffer buf; std::wstring greeting(L"Hello, World"); WideMessageBuffer& retval = buf << L"Hello" << L", World"; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertWString() { MessageBuffer buf; std::wstring greeting(L"Hello, World"); WideMessageBuffer& retval = buf << std::wstring(L"Hello") << std::wstring(L", World"); LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertWStr() { MessageBuffer buf; std::wstring greeting(L"Hello, World"); wchar_t* part1 = (wchar_t*) malloc(10*sizeof(wchar_t)); wcscpy(part1, L"Hello"); wchar_t* part2 = (wchar_t*) malloc(10*sizeof(wchar_t)); wcscpy(part2, L", World"); WideMessageBuffer& retval = buf << part1 << part2; free(part1); free(part2); LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } #endif #if LOG4CXX_UNICHAR_API void testInsertConstUStr() { MessageBuffer buf; const log4cxx::UniChar hello[] = { 'H', 'e', 'l', 'l', 'o', 0 }; const log4cxx::UniChar world[] = { ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; const log4cxx::UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; UniCharMessageBuffer& retval = buf << hello << world; LOGUNIT_ASSERT_EQUAL(std::basic_string<log4cxx::UniChar>(greeting), buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertUString() { MessageBuffer buf; const log4cxx::UniChar hello[] = { 'H', 'e', 'l', 'l', 'o', 0 }; const log4cxx::UniChar world[] = { ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; const log4cxx::UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; UniCharMessageBuffer& retval = buf << std::basic_string<log4cxx::UniChar>(hello) << std::basic_string<log4cxx::UniChar>(world); LOGUNIT_ASSERT_EQUAL(std::basic_string<log4cxx::UniChar>(greeting), buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } #endif #if LOG4CXX_CFSTRING_API void testInsertCFString() { MessageBuffer buf; const log4cxx::UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; UniCharMessageBuffer& retval = buf << CFSTR("Hello") << CFSTR(", World"); LOGUNIT_ASSERT_EQUAL(std::basic_string<log4cxx::UniChar>(greeting), buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(MessageBufferTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/timezone.h> #include "../insertwide.h" #include "../logunit.h" #include <apr_time.h> using namespace log4cxx; using namespace log4cxx::helpers; //Define INT64_C for compilers that don't have it #if (!defined(INT64_C)) #define INT64_C(value) value ## LL #endif /** Unit test {@link TimeZone}. */ LOGUNIT_CLASS(TimeZoneTestCase) { LOGUNIT_TEST_SUITE(TimeZoneTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); #if !defined(__BORLANDC__) LOGUNIT_TEST(test3); #endif LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST_SUITE_END(); #define MICROSECONDS_PER_DAY APR_INT64_C(86400000000) public: /** * Checks the GMT timezone */ void test1() { TimeZonePtr tz(TimeZone::getGMT()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT"), tz->getID()); } /** * Get "GMT-6" time zone */ void test2() { TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT-6"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT-06:00"), tz->getID()); apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420; apr_time_exp_t exploded; tz->explode(&exploded, jan2); LOGUNIT_ASSERT_EQUAL(-6 * 3600, exploded.tm_gmtoff); LOGUNIT_ASSERT_EQUAL(18, exploded.tm_hour); } /** * Get the default timezone name */ void test3() { TimeZonePtr tz(TimeZone::getDefault()); LogString tzName(tz->getID()); LOGUNIT_ASSERT(tzName.length() > 0); } /** * Get "GMT+0010" time zone */ void test4() { TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT+0010"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT+00:10"), tz->getID()); apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420; apr_time_exp_t exploded; tz->explode(&exploded, jan2); LOGUNIT_ASSERT_EQUAL(600, exploded.tm_gmtoff); LOGUNIT_ASSERT_EQUAL(0, exploded.tm_hour); LOGUNIT_ASSERT_EQUAL(10, exploded.tm_min); } /** * Get "GMT+6" time zone */ void test5() { TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT+6"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT+06:00"), tz->getID()); apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420; apr_time_exp_t exploded; tz->explode(&exploded, jan2); LOGUNIT_ASSERT_EQUAL(6 * 3600, exploded.tm_gmtoff); LOGUNIT_ASSERT_EQUAL(6, exploded.tm_hour); } /** * Checks the GMT timezone */ void test6() { TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT"), tz->getID()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TimeZoneTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/stringhelper.h> #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; /** Unit test for StringHelper. */ LOGUNIT_CLASS(StringHelperTestCase) { LOGUNIT_TEST_SUITE( StringHelperTestCase ); LOGUNIT_TEST( testStartsWith1 ); LOGUNIT_TEST( testStartsWith2 ); LOGUNIT_TEST( testStartsWith3 ); LOGUNIT_TEST( testStartsWith4 ); LOGUNIT_TEST( testStartsWith5 ); LOGUNIT_TEST( testEndsWith1 ); LOGUNIT_TEST( testEndsWith2 ); LOGUNIT_TEST( testEndsWith3 ); LOGUNIT_TEST( testEndsWith4 ); LOGUNIT_TEST( testEndsWith5 ); LOGUNIT_TEST_SUITE_END(); public: /** * Check that startsWith("foobar", "foo") returns true. */ void testStartsWith1() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("foo"))); } /** * Check that startsWith("bar", "foobar") returns false. */ void testStartsWith2() { LOGUNIT_ASSERT_EQUAL(false, StringHelper::startsWith(LOG4CXX_STR("foo"), LOG4CXX_STR("foobar"))); } /** * Check that startsWith("foobar", "foobar") returns true. */ void testStartsWith3() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("foobar"))); } /** * Check that startsWith("foobar", "") returns true. */ void testStartsWith4() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR(""))); } /** * Check that startsWith("foobar", "abc") returns false. */ void testStartsWith5() { LOGUNIT_ASSERT_EQUAL(false, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("abc"))); } /** * Check that endsWith("foobar", "bar") returns true. */ void testEndsWith1() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::endsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("bar"))); } /** * Check that endsWith("bar", "foobar") returns false. */ void testEndsWith2() { LOGUNIT_ASSERT_EQUAL(false, StringHelper::endsWith(LOG4CXX_STR("bar"), LOG4CXX_STR("foobar"))); } /** * Check that endsWith("foobar", "foobar") returns true. */ void testEndsWith3() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::endsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("foobar"))); } /** * Check that endsWith("foobar", "") returns true. */ void testEndsWith4() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::endsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR(""))); } /** * Check that endsWith("foobar", "abc") returns false. */ void testEndsWith5() { LOGUNIT_ASSERT_EQUAL(false, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("abc"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(StringHelperTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/charsetencoder.h> #include "../logunit.h" #include "../insertwide.h" #include <log4cxx/helpers/bytebuffer.h> #include <log4cxx/helpers/thread.h> #include <log4cxx/helpers/mutex.h> #include <log4cxx/helpers/condition.h> #include <log4cxx/helpers/synchronized.h> #include <apr.h> #include <apr_atomic.h> using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(CharsetEncoderTestCase) { LOGUNIT_TEST_SUITE(CharsetEncoderTestCase); LOGUNIT_TEST(encode1); LOGUNIT_TEST(encode2); LOGUNIT_TEST(encode3); LOGUNIT_TEST(encode4); #if APR_HAS_THREADS LOGUNIT_TEST(thread1); #endif LOGUNIT_TEST_SUITE_END(); enum { BUFSIZE = 256 }; public: void encode1() { const LogString greeting(LOG4CXX_STR("Hello, World")); CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("US-ASCII"))); char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT(iter == greeting.end()); stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 12, out.position()); out.flip(); std::string encoded((const char*) out.data(), out.limit()); LOGUNIT_ASSERT_EQUAL((std::string) "Hello, World", encoded); LOGUNIT_ASSERT(iter == greeting.end()); } void encode2() { LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A')); greeting.append(LOG4CXX_STR("Hello")); CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("US-ASCII"))); char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 0, out.remaining()); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR('o'), *(iter+1)); out.flip(); std::string encoded((char*) out.data(), out.limit()); out.clear(); stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 2, out.position()); LOGUNIT_ASSERT(iter == greeting.end()); stat = enc->encode(greeting, iter, out); out.flip(); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); encoded.append(out.data(), out.limit()); std::string manyAs(BUFSIZE - 3, 'A'); LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3)); LOGUNIT_ASSERT_EQUAL(std::string("Hello"), encoded.substr(BUFSIZE - 3)); } void encode3() { #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greet[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 }; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const char greet[] = { 'A', (char) 0xD8, (char) 0x85, (char) 0xD4, (char) 0xB0, (char) 0xE0, (char) 0xA6, (char) 0x86, (char) 0xE4, (char) 0xB8, (char) 0x83, (char) 0xD0, (char) 0x80, 0 }; #endif LogString greeting(greet); CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("US-ASCII"))); char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = enc->encode(greeting, iter, out); out.flip(); LOGUNIT_ASSERT_EQUAL(true, CharsetEncoder::isError(stat)); LOGUNIT_ASSERT_EQUAL((size_t) 1, out.limit()); LOGUNIT_ASSERT_EQUAL(greet[1], *iter); LOGUNIT_ASSERT_EQUAL('A', out.data()[0]); } void encode4() { const char utf8_greet[] = { 'A', (char) 0xD8, (char) 0x85, (char) 0xD4, (char) 0xB0, (char) 0xE0, (char) 0xA6, (char) 0x86, (char) 0xE4, (char) 0xB8, (char) 0x83, (char) 0xD0, (char) 0x80, 0 }; #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greet[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 }; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar *greet = utf8_greet; #endif LogString greeting(greet); CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("UTF-8"))); char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(false, CharsetEncoder::isError(stat)); stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(false, CharsetEncoder::isError(stat)); out.flip(); LOGUNIT_ASSERT_EQUAL((size_t) 13, out.limit()); for(size_t i = 0; i < out.limit(); i++) { LOGUNIT_ASSERT_EQUAL((int) utf8_greet[i], (int) out.data()[i]); } LOGUNIT_ASSERT(iter == greeting.end()); } #if APR_HAS_THREADS class ThreadPackage { public: ThreadPackage(CharsetEncoderPtr& enc, int repetitions) : p(), lock(p), condition(p), passCount(0), failCount(0), enc(enc), repetitions(repetitions) { } void await() { synchronized sync(lock); condition.await(lock); } void signalAll() { synchronized sync(lock); condition.signalAll(); } void fail() { apr_atomic_inc32(&failCount); } void pass() { apr_atomic_inc32(&passCount); } apr_uint32_t getFail() { return apr_atomic_read32(&failCount); } apr_uint32_t getPass() { return apr_atomic_read32(&passCount); } int getRepetitions() { return repetitions; } CharsetEncoderPtr& getEncoder() { return enc; } private: ThreadPackage(const ThreadPackage&); ThreadPackage& operator=(ThreadPackage&); Pool p; Mutex lock; Condition condition; volatile apr_uint32_t passCount; volatile apr_uint32_t failCount; CharsetEncoderPtr enc; int repetitions; }; static void* LOG4CXX_THREAD_FUNC thread1Action(apr_thread_t* /* thread */, void* data) { ThreadPackage* package = (ThreadPackage*) data; #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar greet[] = { 'H', 'e', 'l', 'l', 'o', ' ', (char) 0xC2, (char) 0xA2, // cent sign (char) 0xC2, (char) 0xA9, // copyright (char) 0xc3, (char) 0xb4, // latin small letter o with circumflex 0 }; #endif #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greet[] = { L'H', L'e', L'l', L'l', L'o', L' ', 0x00A2, 0x00A9, 0x00F4 , 0 }; #endif const char expected[] = { 'H', 'e', 'l', 'l', 'o', ' ', (char) 0x00A2, (char) 0x00A9, (char) 0x00F4 }; LogString greeting(greet); package->await(); for(int i = 0; i < package->getRepetitions(); i++) { bool pass = true; char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = package->getEncoder()->encode(greeting, iter, out); pass = (false == CharsetEncoder::isError(stat)); if (pass) { stat = package->getEncoder()->encode(greeting, iter, out); pass = (false == CharsetEncoder::isError(stat)); if (pass) { out.flip(); pass = (sizeof(expected) == out.limit()); for(size_t i = 0; i < out.limit() && pass; i++) { pass = (expected[i] == out.data()[i]); } pass = pass && (iter == greeting.end()); } } if (pass) { package->pass(); } else { package->fail(); } } return 0; } void thread1() { enum { THREAD_COUNT = 10, THREAD_REPS = 10000 }; Thread threads[THREAD_COUNT]; CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("ISO-8859-1"))); ThreadPackage* package = new ThreadPackage(enc, THREAD_REPS); { for(int i = 0; i < THREAD_COUNT; i++) { threads[i].run(thread1Action, package); } } // // give time for all threads to be launched so // we don't signal before everybody is waiting. Thread::sleep(100); package->signalAll(); for(int i = 0; i < THREAD_COUNT; i++) { threads[i].join(); } LOGUNIT_ASSERT_EQUAL((apr_uint32_t) 0, package->getFail()); LOGUNIT_ASSERT_EQUAL((apr_uint32_t) THREAD_COUNT * THREAD_REPS, package->getPass()); delete package; } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(CharsetEncoderTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/properties.h> #include <log4cxx/helpers/fileinputstream.h> #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(PropertiesTestCase) { LOGUNIT_TEST_SUITE(PropertiesTestCase); LOGUNIT_TEST(testLoad1); LOGUNIT_TEST_SUITE_END(); public: void testLoad1() { // // read patternLayout1.properties FileInputStreamPtr propFile = new FileInputStream(LOG4CXX_STR("input/patternLayout1.properties")); Properties properties; properties.load(propFile); LogString pattern(properties.getProperty(LOG4CXX_STR("log4j.appender.testAppender.layout.ConversionPattern"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("%-5p - %m%n"), pattern); } }; LOGUNIT_TEST_SUITE_REGISTRATION(PropertiesTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG4CXX_TEST #include <log4cxx/private/log4cxx_private.h> #if LOG4CXX_HAS_STD_LOCALE #include "localechanger.h" #include <stdexcept> using namespace log4cxx::helpers; /** * Construction attemtps to change default locale. * @param locale locale. */ LocaleChanger::LocaleChanger(const char* locale) { effective = false; try { std::locale newLocale(locale); initial = std::locale::global(newLocale); effective = true; } catch(std::runtime_error&) { } catch(std::exception&) { } } /** * Restores previous locale. */ LocaleChanger::~LocaleChanger() { if (effective) { std::locale::global(initial); } } #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/iso8601dateformat.h> #include "../logunit.h" #define LOG4CXX_TEST #include <log4cxx/private/log4cxx_private.h> #if LOG4CXX_HAS_STD_LOCALE #include <locale> #endif #include "../insertwide.h" #include <log4cxx/helpers/pool.h> #include <log4cxx/helpers/date.h> using namespace log4cxx; using namespace log4cxx::helpers; /** Unit test {@link ISO8601DateFormat}. */ LOGUNIT_CLASS(ISO8601DateFormatTestCase) { LOGUNIT_TEST_SUITE( ISO8601DateFormatTestCase ); LOGUNIT_TEST( test1 ); LOGUNIT_TEST( test2 ); LOGUNIT_TEST( test3 ); LOGUNIT_TEST( test4 ); LOGUNIT_TEST( test5 ); LOGUNIT_TEST( test6 ); LOGUNIT_TEST( test7 ); LOGUNIT_TEST_SUITE_END(); /** * Asserts that formatting the provided date results * in the expected string. * * @param date Date date * @param timeZone TimeZone timezone for conversion * @param expected String expected string */ void assertFormattedTime(log4cxx_time_t date, const TimeZonePtr& timeZone, const LogString& expected) { ISO8601DateFormat formatter; formatter.setTimeZone(timeZone); LogString actual; Pool p; formatter.format(actual, date, p); LOGUNIT_ASSERT_EQUAL(expected, actual); } public: /** * Convert 02 Jan 2004 00:00:00 GMT for GMT. */ void test1() { log4cxx_time_t jan2 = Date::getMicrosecondsPerDay() * 12419; assertFormattedTime(jan2, TimeZone::getGMT(), LOG4CXX_STR("2004-01-02 00:00:00,000")); } /** * Convert 03 Jan 2004 00:00:00 GMT for America/Chicago. */ void test2() { // // 03 Jan 2004 00:00 GMT // (asking for the same time at a different timezone // will ignore the change of timezone) log4cxx_time_t jan3 = Date::getMicrosecondsPerDay() * 12420; assertFormattedTime(jan3, TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")), LOG4CXX_STR("2004-01-02 18:00:00,000")); } /** * Convert 30 Jun 2004 00:00:00 GMT for GMT. */ void test3() { log4cxx_time_t jun30 = Date::getMicrosecondsPerDay() * 12599; assertFormattedTime(jun30, TimeZone::getGMT(), LOG4CXX_STR("2004-06-30 00:00:00,000")); } /** * Convert 1 Jul 2004 00:00:00 GMT for Chicago, daylight savings in effect. */ void test4() { log4cxx_time_t jul1 = Date::getMicrosecondsPerDay() * 12600; assertFormattedTime(jul1, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("2004-06-30 19:00:00,000")); } /** * Test multiple calls in close intervals. */ void test5() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls log4cxx_time_t ticks = Date::getMicrosecondsPerDay() * 12601; assertFormattedTime(ticks, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:00,000")); assertFormattedTime(ticks + 8000, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:00,008")); assertFormattedTime(ticks + 17000, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:00,017")); assertFormattedTime(ticks + 237000, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:00,237")); assertFormattedTime(ticks + 1415000, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:01,415")); } /** * Check that caching does not disregard timezone. * This test would fail for revision 1.4 of DateTimeDateFormat.java. */ void test6() { log4cxx_time_t jul3 = Date::getMicrosecondsPerDay() * 12602; assertFormattedTime(jul3, TimeZone::getGMT(), LOG4CXX_STR("2004-07-03 00:00:00,000")); assertFormattedTime(jul3, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("2004-07-02 19:00:00,000")); assertFormattedTime(jul3, TimeZone::getGMT(), LOG4CXX_STR("2004-07-03 00:00:00,000")); } /** * Checks that numberFormat is implemented. */ void test7() { LogString number; ISO8601DateFormat formatter; Pool p; formatter.numberFormat(number, 87, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), number); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ISO8601DateFormatTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _LOG4CXX_HELPERS_LOCALE_CHANGER_H #define _LOG4CXX_HELPERS_LOCALE_CHANGER_H #include <locale> namespace log4cxx { namespace helpers { /** * Utility class to change the locale for the duration of a test. * * * * */ class LocaleChanger { public: /** * Construction attemtps to change default locale. * @param locale locale. */ LocaleChanger(const char* locale); /** * Restores previous locale. */ ~LocaleChanger(); /** * Determines whether locale change was effective. * @return true if effective. */ inline bool isEffective() { return effective; } private: LocaleChanger(LocaleChanger&); LocaleChanger& operator=(LocaleChanger&); std::locale initial; bool effective; }; } } #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/transcoder.h> #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(TranscoderTestCase) { LOGUNIT_TEST_SUITE(TranscoderTestCase); LOGUNIT_TEST(decode1); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(decode2); #endif LOGUNIT_TEST(decode3); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(decode4); #endif LOGUNIT_TEST(decode7); LOGUNIT_TEST(decode8); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(encode1); #endif LOGUNIT_TEST(encode2); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(encode3); #endif LOGUNIT_TEST(encode4); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(encode5); #endif LOGUNIT_TEST(encode6); LOGUNIT_TEST(testDecodeUTF8_1); LOGUNIT_TEST(testDecodeUTF8_2); LOGUNIT_TEST(testDecodeUTF8_3); LOGUNIT_TEST(testDecodeUTF8_4); #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(udecode2); LOGUNIT_TEST(udecode4); LOGUNIT_TEST(uencode1); LOGUNIT_TEST(uencode3); LOGUNIT_TEST(uencode5); #endif LOGUNIT_TEST_SUITE_END(); public: void decode1() { const char* greeting = "Hello, World"; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(greeting, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\nHello, World"), decoded); } #if LOG4CXX_WCHAR_T_API void decode2() { const wchar_t* greeting = L"Hello, World"; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(greeting, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\nHello, World"), decoded); } #endif void decode3() { const char* nothing = ""; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(nothing, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\n"), decoded); } #if LOG4CXX_WCHAR_T_API void decode4() { const wchar_t* nothing = L""; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(nothing, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\n"), decoded); } #endif enum { BUFSIZE = 255 }; void decode7() { // // normal characters striding over a buffer boundary // std::string longMsg(BUFSIZE - 2, 'A'); longMsg.append("Hello"); LogString decoded; Transcoder::decode(longMsg, decoded); LOGUNIT_ASSERT_EQUAL((size_t) BUFSIZE + 3, decoded.length()); LOGUNIT_ASSERT_EQUAL(LogString(BUFSIZE -2, LOG4CXX_STR('A')), decoded.substr(0, BUFSIZE - 2)); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Hello"), decoded.substr(BUFSIZE -2 )); } void decode8() { std::string msg("Hello, World."); LogString actual; Transcoder::decode(msg, actual); LogString expected(LOG4CXX_STR("Hello, World.")); LOGUNIT_ASSERT_EQUAL(expected, actual); } #if LOG4CXX_WCHAR_T_API void encode1() { const LogString greeting(LOG4CXX_STR("Hello, World")); std::wstring encoded; Transcoder::encode(greeting, encoded); LOGUNIT_ASSERT_EQUAL((std::wstring) L"Hello, World", encoded); } #endif void encode2() { const LogString greeting(LOG4CXX_STR("Hello, World")); std::string encoded; Transcoder::encode(greeting, encoded); LOGUNIT_ASSERT_EQUAL((std::string) "Hello, World", encoded); } #if LOG4CXX_WCHAR_T_API void encode3() { LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A')); greeting.append(LOG4CXX_STR("Hello")); std::wstring encoded; Transcoder::encode(greeting, encoded); std::wstring manyAs(BUFSIZE - 3, L'A'); LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3)); LOGUNIT_ASSERT_EQUAL(std::wstring(L"Hello"), encoded.substr(BUFSIZE - 3)); } #endif void encode4() { LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A')); greeting.append(LOG4CXX_STR("Hello")); std::string encoded; Transcoder::encode(greeting, encoded); std::string manyAs(BUFSIZE - 3, 'A'); LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3)); LOGUNIT_ASSERT_EQUAL(std::string("Hello"), encoded.substr(BUFSIZE - 3)); } #if LOG4CXX_WCHAR_T_API void encode5() { // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const wchar_t greeting[] = { L'A', 0x0605, 0x0530, 0x984, 0x40E3, 0x400, 0 }; // // decode to LogString (UTF-16 or UTF-8) // LogString decoded; Transcoder::decode(greeting, decoded); // // decode to wstring // std::wstring encoded; Transcoder::encode(decoded, encoded); // // should be lossless // LOGUNIT_ASSERT_EQUAL((std::wstring) greeting, encoded); } #endif void encode6() { #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greeting[] = { L'A', 0x0605, 0x0530, 0x984, 0x40E3, 0x400, 0 }; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const char greeting[] = { 'A', (char) 0xD8, (char) 0x85, (char) 0xD4, (char) 0xB0, (char) 0xE0, (char) 0xCC, (char) 0x84, (char) 0xE8, (char) 0x87, (char) 0x83, (char) 0xD0, (char) 0x80, 0 }; #endif // // decode to LogString (UTF-16 or UTF-8) // LogString decoded; Transcoder::decode(greeting, decoded); // // decode to wstring // std::string encoded; // // likely 'A\u0605\u0530\u0984\u40E3\u0400' // Transcoder::encode(decoded, encoded); } void testDecodeUTF8_1() { std::string src("a"); LogString out; Transcoder::decodeUTF8(src, out); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("a")), out); } void testDecodeUTF8_2() { std::string src(1, 0x80); LogString out; Transcoder::decodeUTF8(src, out); LOGUNIT_ASSERT_EQUAL(LogString(1, Transcoder::LOSSCHAR), out); } void testDecodeUTF8_3() { std::string src("\xC2"); LogString out; Transcoder::decodeUTF8(src, out); LOGUNIT_ASSERT_EQUAL(LogString(1, Transcoder::LOSSCHAR), out); } void testDecodeUTF8_4() { std::string src("\xC2\xA9"); LogString out; Transcoder::decodeUTF8(src, out); LogString::const_iterator iter = out.begin(); unsigned int sv = Transcoder::decode(out, iter); LOGUNIT_ASSERT_EQUAL((unsigned int) 0xA9, sv); LOGUNIT_ASSERT_EQUAL(true, iter == out.end()); } #if LOG4CXX_UNICHAR_API void udecode2() { const UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(greeting, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\nHello, World"), decoded); } void udecode4() { const UniChar nothing[] = { 0 }; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(nothing, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\n"), decoded); } void uencode1() { const LogString greeting(LOG4CXX_STR("Hello, World")); std::basic_string<UniChar> encoded; Transcoder::encode(greeting, encoded); const UniChar expected[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; LOGUNIT_ASSERT_EQUAL(std::basic_string<UniChar>(expected), encoded); } void uencode3() { LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A')); greeting.append(LOG4CXX_STR("Hello")); std::basic_string<UniChar> encoded; Transcoder::encode(greeting, encoded); std::basic_string<UniChar> manyAs(BUFSIZE - 3, 'A'); LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3)); const UniChar hello[] = { 'H', 'e', 'l', 'l', 'o', 0 }; LOGUNIT_ASSERT_EQUAL(std::basic_string<UniChar>(hello), encoded.substr(BUFSIZE - 3)); } void uencode5() { // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const UniChar greeting[] = { L'A', 0x0605, 0x0530, 0x984, 0x40E3, 0x400, 0 }; // // decode to LogString (UTF-16 or UTF-8) // LogString decoded; Transcoder::decode(greeting, decoded); // // decode to basic_string<UniChar> // std::basic_string<UniChar> encoded; Transcoder::encode(decoded, encoded); // // should be lossless // LOGUNIT_ASSERT_EQUAL(std::basic_string<UniChar>(greeting), encoded); } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(TranscoderTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/cacheddateformat.h> #include "../logunit.h" #include <log4cxx/helpers/absolutetimedateformat.h> #include <log4cxx/helpers/relativetimedateformat.h> #include <log4cxx/helpers/pool.h> #include <locale> #include "../insertwide.h" #include <apr.h> #include <apr_time.h> #include "localechanger.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::pattern; #define LOCALE_US "C" #if defined(_WIN32) #define LOCALE_JP "Japanese_japan" #else #define LOCALE_JP "ja_JP" #endif //Define INT64_C for compilers that don't have it #if (!defined(INT64_C)) #define INT64_C(value) value ##LL #endif #define LOG4CXX_TEST 1 #include <log4cxx/private/log4cxx_private.h> /** Unit test {@link CachedDateFormat}. */ LOGUNIT_CLASS(CachedDateFormatTestCase) { LOGUNIT_TEST_SUITE( CachedDateFormatTestCase ); LOGUNIT_TEST( test1 ); LOGUNIT_TEST( test2 ); LOGUNIT_TEST( test3 ); LOGUNIT_TEST( test4 ); #if LOG4CXX_HAS_STD_LOCALE LOGUNIT_TEST( test5 ); #endif LOGUNIT_TEST( test6 ); LOGUNIT_TEST( test8 ); // Gump doesn't like this test // LOGUNIT_TEST( test9 ); LOGUNIT_TEST( test10 ); LOGUNIT_TEST( test11); LOGUNIT_TEST( test12 ); LOGUNIT_TEST( test13 ); LOGUNIT_TEST( test14 ); LOGUNIT_TEST( test15 ); LOGUNIT_TEST( test16 ); LOGUNIT_TEST( test17); LOGUNIT_TEST( test18); LOGUNIT_TEST( test19); LOGUNIT_TEST( test20); LOGUNIT_TEST( test21); LOGUNIT_TEST_SUITE_END(); #define MICROSECONDS_PER_DAY APR_INT64_C(86400000000) public: /** * Test multiple calls in close intervals. */ void test1() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls DateFormatPtr baseFormatter(new AbsoluteTimeDateFormat()); CachedDateFormat gmtFormat(baseFormatter, 1000000); gmtFormat.setTimeZone(TimeZone::getGMT()); apr_time_t jul1 = MICROSECONDS_PER_DAY * 12601L; Pool p; LogString actual; gmtFormat.format(actual, jul1, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul1 + 8000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,008"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul1 + 17000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,017"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul1 + 237000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,237"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul1 + 1415000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:01,415"), actual); actual.erase(actual.begin(), actual.end()); } /** * Check for interaction between caches. */ void test2() { apr_time_t jul2 = MICROSECONDS_PER_DAY * 12602; DateFormatPtr baseFormatter(new AbsoluteTimeDateFormat()); CachedDateFormat gmtFormat(baseFormatter, 1000000); gmtFormat.setTimeZone(TimeZone::getGMT()); DateFormatPtr chicagoBase(new AbsoluteTimeDateFormat()); CachedDateFormat chicagoFormat(chicagoBase, 1000000); chicagoFormat.setTimeZone(TimeZone::getTimeZone(LOG4CXX_STR("GMT-5"))); Pool p; LogString actual; gmtFormat.format(actual, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual); actual.erase(actual.begin(), actual.end()); chicagoFormat.format(actual, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("19:00:00,000"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual); } /** * Test multiple calls in close intervals prior to 1 Jan 1970. */ void test3() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls DateFormatPtr baseFormatter(new AbsoluteTimeDateFormat()); CachedDateFormat gmtFormat(baseFormatter, 1000000); gmtFormat.setTimeZone(TimeZone::getGMT()); apr_time_t ticks = MICROSECONDS_PER_DAY * -7; Pool p; LogString actual; gmtFormat.format(actual, ticks, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual); actual.erase(actual.begin(), actual.end()); // // APR's explode_time method does not properly calculate tm_usec // prior to 1 Jan 1970 on Unix gmtFormat.format(actual, ticks + 8000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,008"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, ticks + 17000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,017"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, ticks + 237000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,237"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, ticks + 1423000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:01,423"), actual); } void assertFormattedEquals( const DateFormatPtr& baseFormat, const CachedDateFormat& cachedFormat, apr_time_t date, Pool& p) { LogString expected; LogString actual; baseFormat->format(expected, date, p); cachedFormat.format(actual, date, p); LOGUNIT_ASSERT_EQUAL(expected, actual); } void test4() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls #if LOG4CXX_HAS_STD_LOCALE std::locale loco(LOCALE_US); std::locale* localeEN = &loco; #else std::locale* localeEN = NULL; #endif DateFormatPtr baseFormat( new SimpleDateFormat(LOG4CXX_STR("EEE, MMM dd, HH:mm:ss.SSS Z"), localeEN)); CachedDateFormat cachedFormat(baseFormat, 1000000); // // use a date in 2000 to attempt to confuse the millisecond locator apr_time_t ticks = MICROSECONDS_PER_DAY * 11141; Pool p; assertFormattedEquals(baseFormat, cachedFormat, ticks, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 8000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 17000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 237000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 1415000, p); } #if LOG4CXX_HAS_STD_LOCALE void test5() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls LocaleChanger localeChange(LOCALE_JP); if (localeChange.isEffective()) { DateFormatPtr baseFormat(new SimpleDateFormat( LOG4CXX_STR("EEE, MMM dd, HH:mm:ss.SSS Z"))); CachedDateFormat cachedFormat(baseFormat, 1000000); // // use a date in 2000 to attempt to confuse the millisecond locator apr_time_t ticks = MICROSECONDS_PER_DAY * 11141; Pool p; assertFormattedEquals(baseFormat, cachedFormat, ticks, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 8000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 17000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 237000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 1415000, p); } } #endif /** * Checks that numberFormat works as expected. */ void test6() { LogString numb; Pool p; AbsoluteTimeDateFormat formatter; formatter.numberFormat(numb, 87, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), numb); } /** * Set time zone on cached and check that it is effective. */ void test8() { DateFormatPtr baseFormat(new SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd HH:mm:ss,SSS"))); baseFormat->setTimeZone(TimeZone::getGMT()); CachedDateFormat cachedFormat(baseFormat, 1000000); apr_time_t jul4 = MICROSECONDS_PER_DAY * 12603; Pool p; LogString actual; cachedFormat.format(actual, jul4, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("2004-07-04 00:00:00,000"), actual); cachedFormat.setTimeZone(TimeZone::getTimeZone(LOG4CXX_STR("GMT-6"))); actual.erase(actual.begin(), actual.end()); cachedFormat.format(actual, jul4, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("2004-07-03 18:00:00,000"), actual); } /** * Test of caching when less than three millisecond digits are specified. */ void test9() { std::locale localeUS(LOCALE_US); DateFormatPtr baseFormat = new SimpleDateFormat( LOG4CXX_STR("yyyy-MMMM-dd HH:mm:ss,SS Z"), &localeUS); DateFormatPtr cachedFormat = new CachedDateFormat(baseFormat, 1000000); TimeZonePtr cet = TimeZone::getTimeZone(LOG4CXX_STR("GMT+1")); cachedFormat->setTimeZone(cet); apr_time_exp_t c; memset(&c, 0, sizeof(c)); c.tm_year = 104; c.tm_mon = 11; c.tm_mday = 12; c.tm_hour = 19; c.tm_sec = 37; c.tm_usec = 23000; apr_time_t dec12; apr_status_t stat = apr_time_exp_gmt_get(&dec12, &c); const apr_status_t statOK = 0; LOGUNIT_ASSERT_EQUAL(statOK, stat); Pool p; LogString s; cachedFormat->format(s, dec12, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("2004-December-12 20:00:37,23 +0100"), s); memset(&c, 0, sizeof(c)); c.tm_year = 104; c.tm_mon = 11; c.tm_mday = 31; c.tm_hour = 23; c.tm_sec = 13; c.tm_usec = 905000; apr_time_t jan1; stat = apr_time_exp_gmt_get(&jan1, &c); LOGUNIT_ASSERT_EQUAL(statOK, stat); s.erase(s.begin(), s.end()); cachedFormat->format(s, jan1, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("2005-January-01 00:00:13,905 +0100"), s); } /** * Test when millisecond position moves but length remains constant. */ void test10() { #if LOG4CXX_HAS_STD_LOCALE std::locale loco("C"); std::locale* localeUS = &loco; #else std::locale* localeUS = NULL; #endif DateFormatPtr baseFormat = new SimpleDateFormat( LOG4CXX_STR("MMMM SSS EEEEEE"), localeUS); DateFormatPtr cachedFormat = new CachedDateFormat(baseFormat, 1000000); TimeZonePtr cet = TimeZone::getTimeZone(LOG4CXX_STR("GMT+1")); cachedFormat->setTimeZone(cet); apr_time_exp_t c; memset(&c, 0, sizeof(c)); c.tm_year = 104; c.tm_mon = 9; c.tm_mday = 5; c.tm_hour = 21; c.tm_sec = 37; c.tm_usec = 23000; apr_time_t oct5; apr_status_t stat = apr_time_exp_gmt_get(&oct5, &c); const apr_status_t statOK = 0; LOGUNIT_ASSERT_EQUAL(statOK, stat); Pool p; LogString s; cachedFormat->format(s, oct5, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("October 023 Tuesday"), s); memset(&c, 0, sizeof(c)); c.tm_year = 104; c.tm_mon = 10; c.tm_mday = 1; c.tm_usec = 23000; apr_time_t nov1; stat = apr_time_exp_gmt_get(&nov1, &c); LOGUNIT_ASSERT_EQUAL(statOK, stat); s.erase(s.begin(), s.end()); cachedFormat->format(s, nov1, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("November 023 Monday"), s); nov1 += 961000; s.erase(s.begin(), s.end()); cachedFormat->format(s, nov1, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("November 984 Monday"), s); } /** * Test that tests if caching is skipped if only "SS" * is specified. */ void test11() { // // Earlier versions could be tricked by "SS0" patterns. // LogString badPattern(LOG4CXX_STR("ss,SS0")); DateFormatPtr simpleFormat = new SimpleDateFormat(badPattern); DateFormatPtr gmtFormat = new CachedDateFormat(simpleFormat, 1000000); gmtFormat->setTimeZone(TimeZone::getGMT()); // // The first request has to 100 ms after an ordinal second // to push the literal zero out of the pattern check apr_time_t ticks = MICROSECONDS_PER_DAY * 11142L; apr_time_t jul2 = ticks + 120000; Pool p; LogString s; gmtFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("00,1200"), s); jul2 = ticks + 87000; s.erase(s.begin(), s.end()); gmtFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("00,870"), s); } /** * Check pattern location for ISO8601 */ void test12() { DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd HH:mm:ss,SSS")); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int millisecondStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL(20, millisecondStart); } /** * Check pattern location for DATE */ void test13() { DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd")); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int millisecondStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::NO_MILLISECONDS, millisecondStart); } /** * Check pattern location for ABSOLUTE */ void test14() { DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,SSS")); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int millisecondStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL(9, millisecondStart); } /** * Check pattern location for single S */ void test15() { DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,S")); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int millisecondStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::UNRECOGNIZED_MILLISECONDS, millisecondStart); } /** * Check pattern location for single SS */ void test16() { DateFormatPtr df = new SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,SS")); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int millisecondStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::UNRECOGNIZED_MILLISECONDS, millisecondStart); } /** * Check caching when multiple SSS appear in pattern */ void test17() { apr_time_t jul2 = 12602L * MICROSECONDS_PER_DAY; LogString badPattern(LOG4CXX_STR("HH:mm:ss,SSS HH:mm:ss,SSS")); DateFormatPtr simpleFormat = new SimpleDateFormat(badPattern); simpleFormat->setTimeZone(TimeZone::getGMT()); DateFormatPtr cachedFormat = new CachedDateFormat(simpleFormat, 1000000); Pool p; LogString s; cachedFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000 00:00:00,000"), s); jul2 += 120000; s.erase(s.begin(), s.end()); simpleFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,120 00:00:00,120"), s); s.erase(s.begin(), s.end()); cachedFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,120 00:00:00,120"), s) ; int maxValid = CachedDateFormat::getMaximumCacheValidity(badPattern); LOGUNIT_ASSERT_EQUAL(1000, maxValid); } /** * Check that patterns not containing microseconds * are reported as being able to be cached for a full second. */ void test18() { int maxValid = CachedDateFormat::getMaximumCacheValidity( LOG4CXX_STR("yyyy-MM-dd")); LOGUNIT_ASSERT_EQUAL(1000000, maxValid); } /** * Check that patterns not containing 3 microseconds * are reported as being able to be cached for a full second. */ void test19() { int maxValid = CachedDateFormat::getMaximumCacheValidity( LOG4CXX_STR("yyyy-MM-dd SSS")); LOGUNIT_ASSERT_EQUAL(1000000, maxValid); } /** * Check that patterns not containing 2 S's * are reported as being able to be cached for only a millisecond. */ void test20() { int maxValid = CachedDateFormat::getMaximumCacheValidity( LOG4CXX_STR("yyyy-MM-dd SS")); LOGUNIT_ASSERT_EQUAL(1000, maxValid); } /** * Check that patterns not containing multi S groups * are reported as being able to be cached for only a millisecond. */ void test21() { int maxValid = CachedDateFormat::getMaximumCacheValidity( LOG4CXX_STR("yyyy-MM-dd SSS SSS")); LOGUNIT_ASSERT_EQUAL(1000, maxValid); } }; LOGUNIT_TEST_SUITE_REGISTRATION(CachedDateFormatTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/stringtokenizer.h> #include "../logunit.h" #include "../insertwide.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(StringTokenizerTestCase) { LOGUNIT_TEST_SUITE(StringTokenizerTestCase); LOGUNIT_TEST(testNextTokenEmptyString); LOGUNIT_TEST(testHasMoreTokensEmptyString); LOGUNIT_TEST(testNextTokenAllDelim); LOGUNIT_TEST(testHasMoreTokensAllDelim); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST_SUITE_END(); public: void testNextTokenEmptyString() { LogString src; LogString delim(LOG4CXX_STR(" ")); StringTokenizer tokenizer(src, delim); try { LogString token(tokenizer.nextToken()); } catch (NoSuchElementException &ex) { return; } LOGUNIT_ASSERT(false); } void testHasMoreTokensEmptyString() { LogString src; LogString delim(LOG4CXX_STR(" ")); StringTokenizer tokenizer(src, delim); LOGUNIT_ASSERT_EQUAL(false, tokenizer.hasMoreTokens()); } void testNextTokenAllDelim() { LogString src(LOG4CXX_STR("===")); LogString delim(LOG4CXX_STR("=")); StringTokenizer tokenizer(src, delim); try { LogString token(tokenizer.nextToken()); } catch (NoSuchElementException &ex) { return; } LOGUNIT_ASSERT(false); } void testHasMoreTokensAllDelim() { LogString src(LOG4CXX_STR("===")); LogString delim(LOG4CXX_STR("=")); StringTokenizer tokenizer(src, delim); LOGUNIT_ASSERT_EQUAL(false, tokenizer.hasMoreTokens()); } void testBody(const LogString& src, const LogString& delim) { StringTokenizer tokenizer(src, delim); LOGUNIT_ASSERT_EQUAL(true, tokenizer.hasMoreTokens()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("log4j"), tokenizer.nextToken()); LOGUNIT_ASSERT_EQUAL(true, tokenizer.hasMoreTokens()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("properties"), tokenizer.nextToken()); LOGUNIT_ASSERT_EQUAL(true, tokenizer.hasMoreTokens()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("txt"), tokenizer.nextToken()); LOGUNIT_ASSERT_EQUAL(false, tokenizer.hasMoreTokens()); try { LogString token(tokenizer.nextToken()); } catch (NoSuchElementException& ex) { return; } LOGUNIT_ASSERT(false); } void test1() { LogString src(LOG4CXX_STR("log4j.properties.txt")); LogString delim(LOG4CXX_STR(".")); testBody(src, delim); } void test2() { LogString src(LOG4CXX_STR(".log4j.properties.txt")); LogString delim(LOG4CXX_STR(".")); testBody(src, delim); } void test3() { LogString src(LOG4CXX_STR("log4j.properties.txt.")); LogString delim(LOG4CXX_STR(".")); testBody(src, delim); } void test4() { LogString src(LOG4CXX_STR("log4j..properties....txt")); LogString delim(LOG4CXX_STR(".")); testBody(src, delim); } void test5() { LogString src(LOG4CXX_STR("log4j properties,txt")); LogString delim(LOG4CXX_STR(" ,")); testBody(src, delim); } void test6() { LogString src(LOG4CXX_STR(" log4j properties,txt ")); LogString delim(LOG4CXX_STR(" ,")); testBody(src, delim); } }; LOGUNIT_TEST_SUITE_REGISTRATION(StringTokenizerTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/cyclicbuffer.h> #include "../logunit.h" #include <log4cxx/logmanager.h> #include <log4cxx/logger.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/spi/location/locationinfo.h> #include "../testchar.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; #define MAX 1000 LOGUNIT_CLASS(CyclicBufferTestCase) { LOGUNIT_TEST_SUITE(CyclicBufferTestCase); LOGUNIT_TEST(test0); LOGUNIT_TEST(test1); LOGUNIT_TEST(testResize); LOGUNIT_TEST_SUITE_END(); LoggerPtr logger; std::vector<LoggingEventPtr> e; public: void setUp() { e.reserve(1000); LoggingEventPtr event; for (int i = 0; i < MAX; i++) { event = new LoggingEvent(LOG4CXX_STR("x"), Level::getDebug(), LOG4CXX_STR("e"), log4cxx::spi::LocationInfo::getLocationUnavailable()); e.push_back(event); } } void tearDown() { LogManager::shutdown(); } void test0() { int size = 2; CyclicBuffer cb(size); LOGUNIT_ASSERT_EQUAL(size, cb.getMaxSize()); cb.add(e[0]); LOGUNIT_ASSERT_EQUAL(1, cb.length()); LOGUNIT_ASSERT_EQUAL(e[0], cb.get()); LOGUNIT_ASSERT_EQUAL(0, cb.length()); LOGUNIT_ASSERT(cb.get() == 0); LOGUNIT_ASSERT_EQUAL(0, cb.length()); CyclicBuffer cb2(size); cb2.add(e[0]); cb2.add(e[1]); LOGUNIT_ASSERT_EQUAL(2, cb2.length()); LOGUNIT_ASSERT_EQUAL(e[0], cb2.get()); LOGUNIT_ASSERT_EQUAL(1, cb2.length()); LOGUNIT_ASSERT_EQUAL(e[1], cb2.get()); LOGUNIT_ASSERT_EQUAL(0, cb2.length()); LOGUNIT_ASSERT(cb2.get() == 0); LOGUNIT_ASSERT_EQUAL(0, cb2.length()); } void test1() { for (int bufSize = 1; bufSize <= 128; bufSize *= 2) doTest1(bufSize); } void doTest1(int size) { //System.out.println("Doing test with size = "+size); CyclicBuffer cb(size); LOGUNIT_ASSERT_EQUAL(size, cb.getMaxSize()); int i; for (i = -(size + 10); i < (size + 10); i++) { LOGUNIT_ASSERT(cb.get(i) == 0); } for (i = 0; i < MAX; i++) { cb.add(e[i]); int limit = (i < (size - 1)) ? i : (size - 1); //System.out.println("\nLimit is " + limit + ", i="+i); for (int j = limit; j >= 0; j--) { //System.out.println("i= "+i+", j="+j); LOGUNIT_ASSERT_EQUAL(e[i - (limit - j)], cb.get(j)); } LOGUNIT_ASSERT(cb.get(-1) == 0); LOGUNIT_ASSERT(cb.get(limit + 1) == 0); } } void testResize() { for (int isize = 1; isize <= 128; isize *= 2) { doTestResize(isize, (isize / 2) + 1, (isize / 2) + 1); doTestResize(isize, (isize / 2) + 1, isize + 10); doTestResize(isize, isize + 10, (isize / 2) + 1); doTestResize(isize, isize + 10, isize + 10); } } void doTestResize(int initialSize, int numberOfAdds, int newSize) { //System.out.println("initialSize = "+initialSize+", numberOfAdds=" // +numberOfAdds+", newSize="+newSize); CyclicBuffer cb(initialSize); for (int i = 0; i < numberOfAdds; i++) { cb.add(e[i]); } cb.resize(newSize); int offset = numberOfAdds - initialSize; if (offset < 0) { offset = 0; } int len = (newSize < numberOfAdds) ? newSize : numberOfAdds; len = (len < initialSize) ? len : initialSize; //System.out.println("Len = "+len+", offset="+offset); for (int j = 0; j < len; j++) { LOGUNIT_ASSERT_EQUAL(e[offset + j], cb.get(j)); } } }; LOGUNIT_TEST_SUITE_REGISTRATION(CyclicBufferTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include <log4cxx/helpers/relativetimedateformat.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/helpers/stringhelper.h> #include "../insertwide.h" #include "../logunit.h" #include <log4cxx/helpers/date.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; /** Unit test {@link RelativeTimeDateFormat} class. */ LOGUNIT_CLASS(RelativeTimeDateFormatTestCase) { LOGUNIT_TEST_SUITE(RelativeTimeDateFormatTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST_SUITE_END(); public: /** * Convert 2 Jan 2004 */ void test1() { log4cxx_time_t jan2 = Date::getMicrosecondsPerDay() * 12419; log4cxx_time_t preStartTime = LoggingEvent::getStartTime(); RelativeTimeDateFormat formatter; Pool p; LogString actual; formatter.format(actual, jan2, p); log4cxx_time_t elapsed = log4cxx::helpers::StringHelper::toInt64(actual); LOGUNIT_ASSERT(preStartTime + elapsed*1000 > jan2 - 2000); LOGUNIT_ASSERT(preStartTime + elapsed*1000 < jan2 + 2000); } /** * Checks that numberFormat works as expected. */ void test2() { LogString numb; Pool p; RelativeTimeDateFormat formatter; formatter.numberFormat(numb, 87, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), numb); } /** * Checks that setting timezone doesn't throw an exception. */ void test3() { RelativeTimeDateFormat formatter; formatter.setTimeZone(TimeZone::getGMT()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(RelativeTimeDateFormatTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/helpers/properties.h> #include <log4cxx/helpers/system.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/pool.h> #include "../testchar.h" #include "../insertwide.h" #include "../logunit.h" #include <stdlib.h> #include <apr_pools.h> #include <apr_file_io.h> #include <apr_user.h> #include <apr_env.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; #define MAX 1000 LOGUNIT_CLASS(OptionConverterTestCase) { LOGUNIT_TEST_SUITE(OptionConverterTestCase); LOGUNIT_TEST(varSubstTest1); LOGUNIT_TEST(varSubstTest2); LOGUNIT_TEST(varSubstTest3); LOGUNIT_TEST(varSubstTest4); LOGUNIT_TEST(varSubstTest5); LOGUNIT_TEST(testTmpDir); #if APR_HAS_USER LOGUNIT_TEST(testUserHome); LOGUNIT_TEST(testUserName); #endif LOGUNIT_TEST(testUserDir); LOGUNIT_TEST_SUITE_END(); Properties props; Properties nullProperties; public: void setUp() { } void tearDown() { } /** * Checks that environment variables were properly set * before invoking tests. ::putenv not reliable. */ void envCheck() { Pool p; char* toto; apr_status_t stat = apr_env_get(&toto, "TOTO", p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL("wonderful", toto); char* key1; stat = apr_env_get(&key1, "key1", p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL("value1", key1); char* key2; stat = apr_env_get(&key2, "key2", p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL("value2", key2); } void varSubstTest1() { envCheck(); LogString r(OptionConverter::substVars(LOG4CXX_STR("hello world."), nullProperties)); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("hello world."), r); r = OptionConverter::substVars(LOG4CXX_STR("hello ${TOTO} world."), nullProperties); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("hello wonderful world."), r); } void varSubstTest2() { envCheck(); LogString r(OptionConverter::substVars(LOG4CXX_STR("Test2 ${key1} mid ${key2} end."), nullProperties)); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Test2 value1 mid value2 end."), r); } void varSubstTest3() { envCheck(); LogString r(OptionConverter::substVars( LOG4CXX_STR("Test3 ${unset} mid ${key1} end."), nullProperties)); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Test3 mid value1 end."), r); } void varSubstTest4() { LogString res; LogString val(LOG4CXX_STR("Test4 ${incomplete ")); try { res = OptionConverter::substVars(val, nullProperties); } catch(IllegalArgumentException& e) { std::string witness("\"Test4 ${incomplete \" has no closing brace. Opening brace at position 6."); LOGUNIT_ASSERT_EQUAL(witness, (std::string) e.what()); } } void varSubstTest5() { Properties props1; props1.setProperty(LOG4CXX_STR("p1"), LOG4CXX_STR("x1")); props1.setProperty(LOG4CXX_STR("p2"), LOG4CXX_STR("${p1}")); LogString res = OptionConverter::substVars(LOG4CXX_STR("${p2}"), props1); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("x1"), res); } void testTmpDir() { LogString actual(OptionConverter::substVars( LOG4CXX_STR("${java.io.tmpdir}"), nullProperties)); Pool p; const char* tmpdir = NULL; apr_status_t stat = apr_temp_dir_get(&tmpdir, p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LogString expected; Transcoder::decode(tmpdir, expected); LOGUNIT_ASSERT_EQUAL(expected, actual); } #if APR_HAS_USER void testUserHome() { LogString actual(OptionConverter::substVars( LOG4CXX_STR("${user.home}"), nullProperties)); Pool p; apr_uid_t userid; apr_gid_t groupid; apr_status_t stat = apr_uid_current(&userid, &groupid, p.getAPRPool()); if (stat == APR_SUCCESS) { char* username = NULL; stat = apr_uid_name_get(&username, userid, p.getAPRPool()); if (stat == APR_SUCCESS) { char* dirname = NULL; stat = apr_uid_homepath_get(&dirname, username, p.getAPRPool()); if (stat == APR_SUCCESS) { LogString expected; Transcoder::decode(dirname, expected); LOGUNIT_ASSERT_EQUAL(expected, actual); } } } } void testUserName() { LogString actual(OptionConverter::substVars( LOG4CXX_STR("${user.name}"), nullProperties)); Pool p; apr_uid_t userid; apr_gid_t groupid; apr_status_t stat = apr_uid_current(&userid, &groupid, p.getAPRPool()); if (stat == APR_SUCCESS) { char* username = NULL; stat = apr_uid_name_get(&username, userid, p.getAPRPool()); if (stat == APR_SUCCESS) { LogString expected; Transcoder::decode(username, expected); LOGUNIT_ASSERT_EQUAL(expected, actual); } } } #endif void testUserDir() { LogString actual(OptionConverter::substVars( LOG4CXX_STR("${user.dir}"), nullProperties)); Pool p; char* dirname = NULL; apr_status_t stat = apr_filepath_get(&dirname, APR_FILEPATH_NATIVE, p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LogString expected; Transcoder::decode(dirname, expected); LOGUNIT_ASSERT_EQUAL(expected, actual); } }; LOGUNIT_TEST_SUITE_REGISTRATION(OptionConverterTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define __STDC_CONSTANT_MACROS #include <log4cxx/logstring.h> #include <log4cxx/helpers/datetimedateformat.h> #include "../logunit.h" #include <log4cxx/helpers/pool.h> #include "../insertwide.h" #include <apr.h> #include <apr_time.h> #include <sstream> using namespace log4cxx; using namespace log4cxx::helpers; using namespace std; #define LOCALE_US "C" #if defined(_WIN32) #define LOCALE_FR "French_france" #else #define LOCALE_FR "fr_FR" #endif #define LOG4CXX_TEST 1 #include <log4cxx/private/log4cxx_private.h> #if LOG4CXX_HAS_STD_LOCALE #include <locale> #include "localechanger.h" #define MAKE_LOCALE(ptr, id) \ std::locale loco(id); \ std::locale* ptr = &loco; #else #define MAKE_LOCALE(ptr, id) \ std::locale* ptr = NULL; #endif /** Unit test {@link DateTimeDateFormat}. */ LOGUNIT_CLASS(DateTimeDateFormatTestCase) { LOGUNIT_TEST_SUITE( DateTimeDateFormatTestCase ); LOGUNIT_TEST( test1 ); LOGUNIT_TEST( test2 ); LOGUNIT_TEST( test3 ); LOGUNIT_TEST( test4 ); LOGUNIT_TEST( test5 ); LOGUNIT_TEST( test6 ); #if LOG4CXX_HAS_STD_LOCALE LOGUNIT_TEST( test7 ); LOGUNIT_TEST( test8 ); #endif LOGUNIT_TEST_SUITE_END(); private: #define MICROSECONDS_PER_DAY APR_INT64_C(86400000000) /** Asserts that formatting the provided date results in the expected string. @param date Date date @param timeZone TimeZone timezone for conversion @param expected String expected string */ void assertFormattedTime( apr_time_t date, const std::locale* locale, const TimeZonePtr& timeZone, const LogString& expected ) { DateTimeDateFormat formatter(locale); formatter.setTimeZone(timeZone); LogString actual; Pool p; formatter.format(actual, date, p); LOGUNIT_ASSERT_EQUAL( expected, actual ); } public: /** Convert 02 Jan 2004 00:00:00 GMT for GMT. */ void test1() { // // 02 Jan 2004 00:00 GMT // apr_time_t jan2 = MICROSECONDS_PER_DAY * 12419; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jan2, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jan 2004 00:00:00,000")); } /** Convert 03 Jan 2004 00:00:00 GMT for America/Chicago. */ void test2() { // // 03 Jan 2004 00:00 GMT apr_time_t jan3 = MICROSECONDS_PER_DAY * 12420; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jan3, localeUS, TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")), LOG4CXX_STR("02 Jan 2004 18:00:00,000")); } /** Convert 30 Jun 2004 00:00:00 GMT for GMT. */ void test3() { apr_time_t jun30 = MICROSECONDS_PER_DAY * 12599; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jun30, localeUS, TimeZone::getGMT(), LOG4CXX_STR("30 Jun 2004 00:00:00,000")); } /** Convert 29 Jun 2004 00:00:00 GMT for Chicago, daylight savings in effect. */ void test4() { apr_time_t jul1 = MICROSECONDS_PER_DAY * 12600; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jul1, localeUS, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("30 Jun 2004 19:00:00,000")); } /** Test multiple calls in close intervals. */ void test5() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls apr_time_t ticks = MICROSECONDS_PER_DAY * 12601; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( ticks, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:00,000")); assertFormattedTime( ticks + 8000, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:00,008")); assertFormattedTime( ticks + 17000, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:00,017")); assertFormattedTime( ticks + 237000, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:00,237")); assertFormattedTime( ticks + 1415000, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:01,415")); } /** Check that caching does not disregard timezone. This test would fail for revision 1.4 of DateTimeDateFormat.java. */ void test6() { apr_time_t jul3 = MICROSECONDS_PER_DAY * 12602; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jul3, localeUS, TimeZone::getGMT(), LOG4CXX_STR("03 Jul 2004 00:00:00,000")); assertFormattedTime( jul3, localeUS, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("02 Jul 2004 19:00:00,000")); assertFormattedTime( jul3, localeUS, TimeZone::getGMT(), LOG4CXX_STR("03 Jul 2004 00:00:00,000")); } #if LOG4CXX_HAS_STD_LOCALE LogString formatDate(const std::locale& locale, const tm& date, const LogString& fmt) { // // output the using STL // std::basic_ostringstream<logchar> buffer; #if defined(_USEFAC) _USEFAC(locale, std::time_put<logchar>) .put(buffer, buffer, &date, fmt.c_str(), fmt.c_str() + fmt.length()); #else #if defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE) const std::time_put<logchar>& facet = std::use_facet(locale, (std::time_put<logchar>*) 0); #else const std::time_put<logchar>& facet = std::use_facet<std::time_put<logchar> >(locale); #endif facet.put(buffer, buffer, buffer.fill(), &date, fmt.c_str(), fmt.c_str() + fmt.length()); #endif return buffer.str(); } /** Check that format is locale sensitive. */ void test7() { apr_time_t avr11 = MICROSECONDS_PER_DAY * 12519; LocaleChanger localeChange(LOCALE_FR); if (localeChange.isEffective()) { LogString formatted; Pool p; SimpleDateFormat formatter(LOG4CXX_STR("MMM")); formatter.format(formatted, avr11, p); std::locale localeFR(LOCALE_FR); struct tm avr11tm = { 0, 0, 0, 11, 03, 104 }; LogString expected(formatDate(localeFR, avr11tm, LOG4CXX_STR("%b"))); LOGUNIT_ASSERT_EQUAL(expected, formatted); } } /** Check that format is locale sensitive. */ void test8() { apr_time_t apr11 = MICROSECONDS_PER_DAY * 12519; LocaleChanger localeChange(LOCALE_US); if (localeChange.isEffective()) { LogString formatted; Pool p; SimpleDateFormat formatter(LOG4CXX_STR("MMM")); formatter.setTimeZone(TimeZone::getGMT()); formatter.format(formatted, apr11, p); std::locale localeUS(LOCALE_US); struct tm apr11tm = { 0, 0, 0, 11, 03, 104 }; LogString expected(formatDate(localeUS, apr11tm, LOG4CXX_STR("%b"))); LOGUNIT_ASSERT_EQUAL(expected, formatted); } } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(DateTimeDateFormatTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../logunit.h" #include <log4cxx/logstring.h> #include <log4cxx/helpers/absolutetimedateformat.h> #include "../insertwide.h" #include <apr.h> #include <apr_time.h> #include <log4cxx/helpers/pool.h> //Define INT64_C for compilers that don't have it #if (!defined(INT64_C)) #define INT64_C(value) value ## LL #endif using namespace log4cxx; using namespace log4cxx::helpers; /** Unit test {@link AbsoluteTimeDateFormat}. */ LOGUNIT_CLASS(AbsoluteTimeDateFormatTestCase) { LOGUNIT_TEST_SUITE(AbsoluteTimeDateFormatTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST(test7); LOGUNIT_TEST(test8); LOGUNIT_TEST_SUITE_END(); public: /** * Asserts that formatting the provided date results * in the expected string. * * @param date Date date * @param timeZone TimeZone timezone for conversion * @param expected String expected string */ private: void assertFormattedTime(apr_time_t date, const TimeZonePtr& timeZone, const LogString& expected) { AbsoluteTimeDateFormat formatter; formatter.setTimeZone(timeZone); LogString actual; Pool p; formatter.format(actual, date, p); LOGUNIT_ASSERT_EQUAL(expected, actual); } #define MICROSECONDS_PER_DAY APR_INT64_C(86400000000) public: /** * Convert 02 Jan 2004 00:00:00 GMT for GMT. */ void test1() { // // 02 Jan 2004 00:00 GMT // apr_time_t jan2 = MICROSECONDS_PER_DAY * 12419; assertFormattedTime(jan2, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); } /** * Convert 03 Jan 2004 00:00:00 GMT for America/Chicago. */ void test2() { // // 03 Jan 2004 00:00 GMT // (asking for the same time at a different timezone // will ignore the change of timezone) apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420; assertFormattedTime(jan2, TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")), LOG4CXX_STR("18:00:00,000")); } /** * Convert 29 Jun 2004 00:00:00 GMT for GMT. */ void test3() { apr_time_t jun29 = MICROSECONDS_PER_DAY * 12599; assertFormattedTime(jun29, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); } /** * Convert 29 Jun 2004 00:00:00 GMT for Chicago, daylight savings in effect. */ void test4() { apr_time_t jun30 = MICROSECONDS_PER_DAY * 12600; // // log4cxx doesn't support non-fixed timezones at this time // passing the fixed equivalent to Chicago's Daylight Savings Time // assertFormattedTime(jun30, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("19:00:00,000")); } /** * Test multiple calls in close intervals. */ void test5() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls apr_time_t ticks = MICROSECONDS_PER_DAY * 12601; assertFormattedTime(ticks, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); assertFormattedTime(ticks + 8000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,008")); assertFormattedTime(ticks + 17000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,017")); assertFormattedTime(ticks + 237000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,237")); assertFormattedTime(ticks + 1415000, TimeZone::getGMT(), LOG4CXX_STR("00:00:01,415")); } /** * Check that caching does not disregard timezone. * This test would fail for revision 1.4 of AbsoluteTimeDateFormat.java. */ void test6() { apr_time_t jul2 = MICROSECONDS_PER_DAY * 12602; assertFormattedTime(jul2, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); assertFormattedTime(jul2, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("19:00:00,000")); } /** * Test multiple calls in close intervals predating 1 Jan 1970. */ void test7() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls apr_time_t ticks = MICROSECONDS_PER_DAY * -7; assertFormattedTime(ticks, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); #if defined(_WIN32) // // These tests fail on Unix due to bug in APR's explode_time // // assertFormattedTime(ticks + 8000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,008")); // assertFormattedTime(ticks + 17000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,017")); // assertFormattedTime(ticks + 237000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,237")); // assertFormattedTime(ticks + 1415000, TimeZone::getGMT(), LOG4CXX_STR("00:00:01,415")); #endif } /** * Checks that numberFormat works as expected. */ void test8() { Pool p; LogString numb; AbsoluteTimeDateFormat formatter; formatter.numberFormat(numb, 87, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), numb); } }; LOGUNIT_TEST_SUITE_REGISTRATION(AbsoluteTimeDateFormatTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/rolling/rollingfileappender.h> #include "fileappendertestcase.h" using namespace log4cxx; using namespace log4cxx::helpers; /** Unit tests of log4cxx::RollingFileAppender */ class RollingFileAppenderTestCase : public FileAppenderAbstractTestCase { LOGUNIT_TEST_SUITE(RollingFileAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST_SUITE_END(); public: FileAppender* createFileAppender() const { return new log4cxx::rolling::RollingFileAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(RollingFileAppenderTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "appenderskeletontestcase.h" #include "logunit.h" #include <log4cxx/helpers/objectptr.h> #include <log4cxx/appenderskeleton.h> using namespace log4cxx; using namespace log4cxx::helpers; void AppenderSkeletonTestCase::testDefaultThreshold() { ObjectPtrT<AppenderSkeleton> appender(createAppenderSkeleton()); LevelPtr threshold(appender->getThreshold()); LOGUNIT_ASSERT_EQUAL(Level::getAll()->toInt(), threshold->toInt()); } void AppenderSkeletonTestCase::testSetOptionThreshold() { ObjectPtrT<AppenderSkeleton> appender(createAppenderSkeleton()); appender->setOption(LOG4CXX_STR("threshold"), LOG4CXX_STR("debug")); LevelPtr threshold(appender->getThreshold()); LOGUNIT_ASSERT_EQUAL(Level::getDebug()->toInt(), threshold->toInt()); }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "vectorappender.h" #include <log4cxx/helpers/thread.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(VectorAppender) void VectorAppender::append(const spi::LoggingEventPtr& event, Pool& /*p*/) { try { Thread::sleep(100); } catch (Exception&) { } vector.push_back(event); } void VectorAppender::close() { if (this->closed) { return; } this->closed = true; }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../logunit.h" #include <log4cxx/logger.h> #include <log4cxx/simplelayout.h> #include <log4cxx/fileappender.h> #include <log4cxx/level.h> #include <log4cxx/filter/levelmatchfilter.h> #include <log4cxx/filter/denyallfilter.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/spi/loggerrepository.h> #include "../util/compare.h" #include "../testchar.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::filter; LOGUNIT_CLASS(LevelMatchFilterTestCase) { LOGUNIT_TEST_SUITE(LevelMatchFilterTestCase); LOGUNIT_TEST(accept); LOGUNIT_TEST(deny); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); root->removeAllAppenders(); logger = Logger::getLogger(LOG4CXX_TEST_STR("test")); } void tearDown() { root->getLoggerRepository()->resetConfiguration(); } void accept() { // set up appender LayoutPtr layout = new SimpleLayout(); AppenderPtr appender = new FileAppender(layout, ACCEPT_FILE, false); // create LevelMatchFilter LevelMatchFilterPtr matchFilter = new LevelMatchFilter(); // attach match filter to appender appender->addFilter(matchFilter); // attach DenyAllFilter to end of filter chain to deny neutral // (non matching) messages spi::FilterPtr filter(new DenyAllFilter()); appender->addFilter(filter); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); LevelPtr levelArray[] = { Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() }; int length = sizeof(levelArray)/sizeof(levelArray[0]); Pool pool; for (int x = 0; x < length; x++) { // set the level to match matchFilter->setLevelToMatch(levelArray[x]->toString()); LogString sbuf(LOG4CXX_STR("pass ")); StringHelper::toString(x, pool, sbuf); sbuf.append(LOG4CXX_STR("; filter set to accept only ")); sbuf.append(levelArray[x]->toString()); sbuf.append(LOG4CXX_STR(" msgs")); common(sbuf); } LOGUNIT_ASSERT(Compare::compare(ACCEPT_FILE, ACCEPT_WITNESS)); } void deny() { // set up appender LayoutPtr layout = new SimpleLayout(); AppenderPtr appender = new FileAppender(layout, DENY_FILE, false); // create LevelMatchFilter, set to deny matches LevelMatchFilterPtr matchFilter = new LevelMatchFilter(); matchFilter->setAcceptOnMatch(false); // attach match filter to appender appender->addFilter(matchFilter); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); LevelPtr levelArray[] = { Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() }; int length = sizeof(levelArray)/sizeof(levelArray[0]); Pool pool; for (int x = 0; x < length; x++) { // set the level to match matchFilter->setLevelToMatch(levelArray[x]->toString()); LogString sbuf(LOG4CXX_STR("pass ")); StringHelper::toString(x, pool, sbuf); sbuf.append(LOG4CXX_STR("; filter set to deny only ")); sbuf.append(levelArray[x]->toString()); sbuf.append(LOG4CXX_STR(" msgs")); common(sbuf); } LOGUNIT_ASSERT(Compare::compare(DENY_FILE, DENY_WITNESS)); } void common(const LogString& msg) { logger->debug(msg); logger->info(msg); logger->warn(msg); logger->error(msg); logger->fatal(msg); } private: static const LogString ACCEPT_FILE; static const LogString ACCEPT_WITNESS; static const LogString DENY_FILE; static const LogString DENY_WITNESS; }; const LogString LevelMatchFilterTestCase::ACCEPT_FILE(LOG4CXX_STR("output/LevelMatchFilter_accept")); const LogString LevelMatchFilterTestCase::ACCEPT_WITNESS(LOG4CXX_STR("witness/LevelMatchFilter_accept")); const LogString LevelMatchFilterTestCase::DENY_FILE(LOG4CXX_STR("output/LevelMatchFilter_deny")); const LogString LevelMatchFilterTestCase::DENY_WITNESS(LOG4CXX_STR("witness/LevelMatchFilter_deny")); LOGUNIT_TEST_SUITE_REGISTRATION(LevelMatchFilterTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG4CXX_TEST 1 #include <log4cxx/private/log4cxx_private.h> #include <log4cxx/logger.h> #include <log4cxx/xml/domconfigurator.h> #include "../logunit.h" #include "../util/transformer.h" #include "../util/compare.h" #include "../util/controlfilter.h" #include "../util/threadfilter.h" #include "../util/linenumberfilter.h" #include <iostream> #include <log4cxx/file.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; #define TEST1_A_PAT "FALLBACK - test - Message [0-9]" #define TEST1_B_PAT "FALLBACK - root - Message [0-9]" #define TEST1_2_PAT \ "^[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\},[0-9]\\{3\\} " \ "\\[main]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]" LOGUNIT_CLASS(ErrorHandlerTestCase) { LOGUNIT_TEST_SUITE(ErrorHandlerTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; static const File TEMP; static const File FILTERED; public: void setUp() { root = Logger::getRootLogger(); logger = Logger::getLogger("test"); } void tearDown() { logger->getLoggerRepository()->resetConfiguration(); } void test1() { DOMConfigurator::configure("input/xml/fallback1.xml"); common(); ControlFilter cf; cf << TEST1_A_PAT << TEST1_B_PAT << TEST1_2_PAT; ThreadFilter threadFilter; LineNumberFilter lineNumberFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); filters.push_back(&lineNumberFilter); common(); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } const File witness("witness/fallback"); LOGUNIT_ASSERT(Compare::compare(FILTERED, witness)); } void common() { int i = -1; std::ostringstream os; os << "Message " << ++ i; LOG4CXX_DEBUG(logger, os.str()); LOG4CXX_DEBUG(root, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_INFO(logger, os.str()); LOG4CXX_INFO(root, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_WARN(logger, os.str()); LOG4CXX_WARN(root, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_ERROR(logger, os.str()); LOG4CXX_ERROR(root, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_FATAL(logger, os.str()); LOG4CXX_FATAL(root, os.str()); } }; //TODO: Not sure this test ever worked. 0.9.7 didn't call common // had nothing that attempted to dispatch any log events //LOGUNIT_TEST_SUITE_REGISTRATION(ErrorHandlerTestCase); const File ErrorHandlerTestCase::TEMP("output/temp"); const File ErrorHandlerTestCase::FILTERED("output/filtered");
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include <log4cxx/simplelayout.h> #include <log4cxx/fileappender.h> #include <log4cxx/level.h> #include <log4cxx/filter/levelrangefilter.h> #include "../util/compare.h" #include <log4cxx/helpers/pool.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/transcoder.h> #include "../testchar.h" #include "../logunit.h" #include <log4cxx/spi/loggerrepository.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::filter; LOGUNIT_CLASS(LevelRangeFilterTestCase) { LOGUNIT_TEST_SUITE(LevelRangeFilterTestCase); LOGUNIT_TEST(accept); LOGUNIT_TEST(neutral); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); root->removeAllAppenders(); logger = Logger::getLogger(LOG4CXX_TEST_STR("test")); } void tearDown() { root->getLoggerRepository()->resetConfiguration(); } void accept() { // set up appender LayoutPtr layout = new SimpleLayout(); AppenderPtr appender = new FileAppender(layout, ACCEPT_FILE, false); // create LevelMatchFilter LevelRangeFilterPtr rangeFilter = new LevelRangeFilter(); // set it to accept on a match rangeFilter->setAcceptOnMatch(true); // attach match filter to appender appender->addFilter(rangeFilter); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); int passCount = 0; LogString sbuf(LOG4CXX_STR("pass ")); Pool pool; StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; no min or max set")); common(sbuf); passCount++; // test with a min set rangeFilter->setLevelMin(Level::getWarn()); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; min set to WARN, max not set")); common(sbuf); passCount++; // create a clean filter appender->clearFilters(); rangeFilter = new LevelRangeFilter(); appender->addFilter(rangeFilter); //test with max set rangeFilter->setLevelMax(Level::getWarn()); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; min not set, max set to WARN")); common(sbuf); passCount++; LevelPtr levelArray[] = { Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() }; int length = sizeof(levelArray)/sizeof(levelArray[0]); for (int x = 0; x < length; x++) { // set the min level to match rangeFilter->setLevelMin(levelArray[x]); for (int y = length - 1; y >= 0; y--) { // set max level to match rangeFilter->setLevelMax(levelArray[y]); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; filter set to accept between ")); sbuf.append(levelArray[x]->toString()); sbuf.append(LOG4CXX_STR(" and ")); sbuf.append(levelArray[y]->toString()); sbuf.append(LOG4CXX_STR(" msgs")); common(sbuf); // increment passCount passCount++; } } LOGUNIT_ASSERT(Compare::compare(ACCEPT_FILE, ACCEPT_WITNESS)); } void neutral() { // set up appender LayoutPtr layout = new SimpleLayout(); AppenderPtr appender = new FileAppender(layout, NEUTRAL_FILE, false); // create LevelMatchFilter LevelRangeFilterPtr rangeFilter = new LevelRangeFilter(); // set it to accept on a match rangeFilter->setAcceptOnMatch(true); // attach match filter to appender appender->addFilter(rangeFilter); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); int passCount = 0; LogString sbuf(LOG4CXX_STR("pass ")); Pool pool; StringHelper::toString(passCount, pool, sbuf); // test with no min or max set sbuf.append(LOG4CXX_STR("; no min or max set")); common(sbuf); passCount++; // test with a min set rangeFilter->setLevelMin(Level::getWarn()); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; min set to WARN, max not set")); common(sbuf); passCount++; // create a clean filter appender->clearFilters(); rangeFilter = new LevelRangeFilter(); appender->addFilter(rangeFilter); //test with max set rangeFilter->setLevelMax(Level::getWarn()); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; min not set, max set to WARN")); common(sbuf); passCount++; LevelPtr levelArray[] = { Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() }; int length = sizeof(levelArray)/sizeof(levelArray[0]); for (int x = 0; x < length; x++) { // set the min level to match rangeFilter->setLevelMin(levelArray[x]); for (int y = length - 1; y >= 0; y--) { // set max level to match rangeFilter->setLevelMax(levelArray[y]); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; filter set to accept between ")); sbuf.append(levelArray[x]->toString()); sbuf.append(LOG4CXX_STR(" and ")); sbuf.append(levelArray[y]->toString()); sbuf.append(LOG4CXX_STR(" msgs")); common(sbuf); // increment passCount passCount++; } } LOGUNIT_ASSERT(Compare::compare(NEUTRAL_FILE, NEUTRAL_WITNESS)); } void common(const LogString& msg) { logger->debug(msg); logger->info(msg); logger->warn(msg); logger->error(msg); logger->fatal(msg); } private: static const LogString ACCEPT_FILE; static const LogString ACCEPT_WITNESS; static const LogString NEUTRAL_FILE; static const LogString NEUTRAL_WITNESS; }; const LogString LevelRangeFilterTestCase::ACCEPT_FILE(LOG4CXX_STR("output/LevelRangeFilter_accept")); const LogString LevelRangeFilterTestCase::ACCEPT_WITNESS(LOG4CXX_STR("witness/LevelRangeFilter_accept")); const LogString LevelRangeFilterTestCase::NEUTRAL_FILE(LOG4CXX_STR("output/LevelRangeFilter_neutral")); const LogString LevelRangeFilterTestCase::NEUTRAL_WITNESS(LOG4CXX_STR("witness/LevelRangeFilter_neutral")); LOGUNIT_TEST_SUITE_REGISTRATION(LevelRangeFilterTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fileappendertestcase.h" #include <log4cxx/helpers/objectptr.h> #include <log4cxx/fileappender.h> #include "insertwide.h" using namespace log4cxx; using namespace log4cxx::helpers; WriterAppender* FileAppenderAbstractTestCase::createWriterAppender() const { return createFileAppender(); } /** Unit tests of log4cxx::FileAppender */ class FileAppenderTestCase : public FileAppenderAbstractTestCase { LOGUNIT_TEST_SUITE(FileAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); // tests defined here LOGUNIT_TEST(testSetDoubleBackslashes); LOGUNIT_TEST(testStripDuplicateBackslashes); LOGUNIT_TEST_SUITE_END(); public: FileAppender* createFileAppender() const { return new log4cxx::FileAppender(); } void testSetDoubleBackslashes() { FileAppender appender; appender.setOption(LOG4CXX_STR("FILE"), LOG4CXX_STR("output\\\\temp")); const File& file = appender.getFile(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("output\\temp"), file.getPath()); } /** * Tests that double backslashes in filespecs are stripped * on calls to setOption. * */ void testStripDoubleBackslashes() { FileAppender appender; appender.setOption(LOG4CXX_STR("FILE"), LOG4CXX_STR("output\\\\temp")); const File& file = appender.getFile(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("output\\temp"), file.getPath()); } /** * Tests stripDuplicateBackslashes * * */ void testStripDuplicateBackslashes() { LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo\\bar\\foo"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\foo\\bar\\foo"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo\\bar\\foo\\"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\foo\\\\bar\\\\foo\\\\"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo\\bar\\foo\\"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\foo\\bar\\foo\\"))); // // UNC's should either start with two backslashes and contain additional singles // or four back slashes and addition doubles LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\\\foo\\bar\\foo"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\\\\\foo\\\\bar\\\\foo"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\\\foo\\bar\\foo"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\foo\\bar\\foo"))); // // it it starts with doubles but has no other path component // then it is a file path LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo.log"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\foo.log"))); // // it it starts with quads but has no other path component // then it is a UNC LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\\\foo.log"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\\\\\foo.log"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(FileAppenderTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include <log4cxx/fileappender.h> #include <log4cxx/appenderskeleton.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/logmanager.h> #include <log4cxx/level.h> #include <log4cxx/hierarchy.h> #include <log4cxx/spi/rootlogger.h> #include <log4cxx/helpers/propertyresourcebundle.h> #include "insertwide.h" #include "testchar.h" #include "logunit.h" #include <log4cxx/helpers/locale.h> #include "vectorappender.h" using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; class CountingAppender; typedef helpers::ObjectPtrT<CountingAppender> CountingAppenderPtr; class CountingAppender : public AppenderSkeleton { public: int counter; CountingAppender() : counter(0) {} void close() {} void append(const spi::LoggingEventPtr& /*event*/, Pool& /*p*/) { counter++; } bool requiresLayout() const { return true; } }; LOGUNIT_CLASS(LoggerTestCase) { LOGUNIT_TEST_SUITE(LoggerTestCase); LOGUNIT_TEST(testAppender1); LOGUNIT_TEST(testAppender2); LOGUNIT_TEST(testAdditivity1); LOGUNIT_TEST(testAdditivity2); LOGUNIT_TEST(testAdditivity3); LOGUNIT_TEST(testDisable1); // LOGUNIT_TEST(testRB1); // LOGUNIT_TEST(testRB2); //TODO restore // LOGUNIT_TEST(testRB3); LOGUNIT_TEST(testExists); LOGUNIT_TEST(testHierarchy1); LOGUNIT_TEST(testTrace); LOGUNIT_TEST(testIsTraceEnabled); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { BasicConfigurator::resetConfiguration(); a1 = 0; a2 = 0; logger = 0; } /** Add an appender and see if it can be retrieved. */ void testAppender1() { logger = Logger::getLogger(LOG4CXX_TEST_STR("test")); a1 = new FileAppender(); a1->setName(LOG4CXX_STR("testAppender1")); logger->addAppender(a1); AppenderList list = logger->getAllAppenders(); AppenderPtr aHat = list.front(); LOGUNIT_ASSERT_EQUAL(a1, aHat); } /** Add an appender X, Y, remove X and check if Y is the only remaining appender. */ void testAppender2() { a1 = new FileAppender(); a1->setName(LOG4CXX_STR("testAppender2.1")); a2 = new FileAppender(); a2->setName(LOG4CXX_STR("testAppender2.2")); logger = Logger::getLogger(LOG4CXX_TEST_STR("test")); logger->addAppender(a1); logger->addAppender(a2); logger->removeAppender((LogString) LOG4CXX_STR("testAppender2.1")); AppenderList list = logger->getAllAppenders(); AppenderPtr aHat = list.front(); LOGUNIT_ASSERT_EQUAL(a2, aHat); LOGUNIT_ASSERT(list.size() == 1); } /** Test if LoggerPtr a.b inherits its appender from a. */ void testAdditivity1() { LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a")); LoggerPtr ab = Logger::getLogger(LOG4CXX_TEST_STR("a.b")); CountingAppenderPtr ca = new CountingAppender(); a->addAppender(ca); LOGUNIT_ASSERT_EQUAL(ca->counter, 0); ab->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 1); ab->info(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 2); ab->warn(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 3); ab->error(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 4); } /** Test multiple additivity. */ void testAdditivity2() { LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a")); LoggerPtr ab = Logger::getLogger(LOG4CXX_TEST_STR("a.b")); LoggerPtr abc = Logger::getLogger(LOG4CXX_TEST_STR("a.b.c")); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); CountingAppenderPtr ca1 = new CountingAppender(); CountingAppenderPtr ca2 = new CountingAppender(); a->addAppender(ca1); abc->addAppender(ca2); LOGUNIT_ASSERT_EQUAL(ca1->counter, 0); LOGUNIT_ASSERT_EQUAL(ca2->counter, 0); ab->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca1->counter, 1); LOGUNIT_ASSERT_EQUAL(ca2->counter, 0); abc->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca1->counter, 2); LOGUNIT_ASSERT_EQUAL(ca2->counter, 1); x->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca1->counter, 2); LOGUNIT_ASSERT_EQUAL(ca2->counter, 1); } /** Test additivity flag. */ void testAdditivity3() { LoggerPtr root = Logger::getRootLogger(); LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a")); LoggerPtr ab = Logger::getLogger(LOG4CXX_TEST_STR("a.b")); LoggerPtr abc = Logger::getLogger(LOG4CXX_TEST_STR("a.b.c")); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); CountingAppenderPtr caRoot = new CountingAppender(); CountingAppenderPtr caA = new CountingAppender(); CountingAppenderPtr caABC = new CountingAppender(); root->addAppender(caRoot); a->addAppender(caA); abc->addAppender(caABC); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0); LOGUNIT_ASSERT_EQUAL(caA->counter, 0); LOGUNIT_ASSERT_EQUAL(caABC->counter, 0); ab->setAdditivity(false); a->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); LOGUNIT_ASSERT_EQUAL(caA->counter, 1); LOGUNIT_ASSERT_EQUAL(caABC->counter, 0); ab->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); LOGUNIT_ASSERT_EQUAL(caA->counter, 1); LOGUNIT_ASSERT_EQUAL(caABC->counter, 0); abc->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); LOGUNIT_ASSERT_EQUAL(caA->counter, 1); LOGUNIT_ASSERT_EQUAL(caABC->counter, 1); } void testDisable1() { CountingAppenderPtr caRoot = new CountingAppender(); LoggerPtr root = Logger::getRootLogger(); root->addAppender(caRoot); LoggerRepositoryPtr h = LogManager::getLoggerRepository(); //h.disableDebug(); h->setThreshold(Level::getInfo()); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 2); root->warn(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3); //h.disableInfo(); h->setThreshold(Level::getWarn()); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 4); root->error(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 5); root->log(Level::getError(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); //h.disableAll(); h->setThreshold(Level::getOff()); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->error(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getFatal(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getFatal(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); //h.disable(Level::getFatalLevel()); h->setThreshold(Level::getOff()); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->error(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getFatal(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); } ResourceBundlePtr getBundle(const LogString& lang, const LogString& region) { Locale l(lang, region); ResourceBundlePtr bundle( PropertyResourceBundle::getBundle(LOG4CXX_STR("L7D"),l)); LOGUNIT_ASSERT(bundle != 0); return bundle; } void testRB1() { ResourceBundlePtr rbUS(getBundle(LOG4CXX_STR("en"), LOG4CXX_STR("US"))); ResourceBundlePtr rbFR(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("FR"))); ResourceBundlePtr rbCH(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("CH"))); LoggerPtr root = Logger::getRootLogger(); root->setResourceBundle(rbUS); ResourceBundlePtr t = root->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); LoggerPtr x_y = Logger::getLogger(LOG4CXX_TEST_STR("x.y")); LoggerPtr x_y_z = Logger::getLogger(LOG4CXX_TEST_STR("x.y.z")); t = x->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y_z->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); } void testRB2() { LoggerPtr root = Logger::getRootLogger(); ResourceBundlePtr rbUS(getBundle(LOG4CXX_STR("en"), LOG4CXX_STR("US"))); ResourceBundlePtr rbFR(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("FR"))); ResourceBundlePtr rbCH(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("CH"))); root->setResourceBundle(rbUS); ResourceBundlePtr t = root->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); LoggerPtr x_y = Logger::getLogger(LOG4CXX_TEST_STR("x.y")); LoggerPtr x_y_z = Logger::getLogger(LOG4CXX_TEST_STR("x.y.z")); x_y->setResourceBundle(rbFR); t = x->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y->getResourceBundle(); LOGUNIT_ASSERT(t == rbFR); t = x_y_z->getResourceBundle(); LOGUNIT_ASSERT(t == rbFR); } void testRB3() { ResourceBundlePtr rbUS(getBundle(LOG4CXX_STR("en"), LOG4CXX_STR("US"))); ResourceBundlePtr rbFR(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("FR"))); ResourceBundlePtr rbCH(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("CH"))); LoggerPtr root = Logger::getRootLogger(); root->setResourceBundle(rbUS); ResourceBundlePtr t = root->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); LoggerPtr x_y = Logger::getLogger(LOG4CXX_TEST_STR("x.y")); LoggerPtr x_y_z = Logger::getLogger(LOG4CXX_TEST_STR("x.y.z")); x_y->setResourceBundle(rbFR); x_y_z->setResourceBundle(rbCH); t = x->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y->getResourceBundle(); LOGUNIT_ASSERT(t == rbFR); t = x_y_z->getResourceBundle(); LOGUNIT_ASSERT(t == rbCH); } void testExists() { LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a")); LoggerPtr a_b = Logger::getLogger(LOG4CXX_TEST_STR("a.b")); LoggerPtr a_b_c = Logger::getLogger(LOG4CXX_TEST_STR("a.b.c")); LoggerPtr t; t = LogManager::exists(LOG4CXX_TEST_STR("xx")); LOGUNIT_ASSERT(t == 0); t = LogManager::exists(LOG4CXX_TEST_STR("a")); LOGUNIT_ASSERT_EQUAL(a, t); t = LogManager::exists(LOG4CXX_TEST_STR("a.b")); LOGUNIT_ASSERT_EQUAL(a_b, t); t = LogManager::exists(LOG4CXX_TEST_STR("a.b.c")); LOGUNIT_ASSERT_EQUAL(a_b_c, t); } void testHierarchy1() { LoggerRepositoryPtr h = new Hierarchy(); LoggerPtr root(h->getRootLogger()); root->setLevel(Level::getError()); LoggerPtr a0 = h->getLogger(LOG4CXX_STR("a")); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("a"), a0->getName()); LOGUNIT_ASSERT(a0->getLevel() == 0); LOGUNIT_ASSERT(Level::getError() == a0->getEffectiveLevel()); LoggerPtr a11 = h->getLogger(LOG4CXX_STR("a")); LOGUNIT_ASSERT_EQUAL(a0, a11); } void compileTestForLOGCXX202() const { // // prior to fix, these line would compile. // (*logger).info("Hello, World."); ((Logger*) logger)->info("Hello, World."); // // this one would not. // logger->info("Hello, World."); } /** * Tests logger.trace(Object). * */ void testTrace() { VectorAppenderPtr appender = new VectorAppender(); LoggerPtr root = Logger::getRootLogger(); root->addAppender(appender); root->setLevel(Level::getInfo()); LoggerPtr tracer = Logger::getLogger("com.example.Tracer"); tracer->setLevel(Level::getTrace()); LOG4CXX_TRACE(tracer, "Message 1"); LOG4CXX_TRACE(root, "Discarded Message"); LOG4CXX_TRACE(root, "Discarded Message"); std::vector<LoggingEventPtr> msgs(appender->vector); LOGUNIT_ASSERT_EQUAL((size_t) 1, msgs.size()); LoggingEventPtr event = msgs[0]; LOGUNIT_ASSERT_EQUAL((int) Level::TRACE_INT, event->getLevel()->toInt()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("Message 1")), event->getMessage()); } /** * Tests isTraceEnabled. * */ void testIsTraceEnabled() { VectorAppenderPtr appender = new VectorAppender(); LoggerPtr root = Logger::getRootLogger(); root->addAppender(appender); root->setLevel(Level::getInfo()); LoggerPtr tracer = Logger::getLogger("com.example.Tracer"); tracer->setLevel(Level::getTrace()); LOGUNIT_ASSERT_EQUAL(true, tracer->isTraceEnabled()); LOGUNIT_ASSERT_EQUAL(false, root->isTraceEnabled()); } protected: static LogString MSG; LoggerPtr logger; AppenderPtr a1; AppenderPtr a2; }; LogString LoggerTestCase::MSG(LOG4CXX_STR("M")); LOGUNIT_TEST_SUITE_REGISTRATION(LoggerTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ostream> #include <iomanip> #include "vectorappender.h" #include <log4cxx/logmanager.h> #include <log4cxx/simplelayout.h> #include <log4cxx/spi/loggingevent.h> #include "insertwide.h" #include "logunit.h" #include <log4cxx/stream.h> #if LOG4CXX_CFSTRING_API #include <CoreFoundation/CFString.h> #endif using namespace log4cxx; using namespace log4cxx::helpers; using namespace std; class ExceptionOnInsert { public: ExceptionOnInsert() { } }; // // define an insertion operation that will throw an // exception to test that evaluation was short // circuited // template<class Elem, class Tr> ::std::basic_ostream<Elem, Tr>& operator<<( ::std::basic_ostream<Elem, Tr>&, const ExceptionOnInsert&) { throw std::exception(); } /** Unit tests for the optional stream-like interface for log4cxx */ LOGUNIT_CLASS(StreamTestCase) { LOGUNIT_TEST_SUITE(StreamTestCase); LOGUNIT_TEST(testSimple); LOGUNIT_TEST(testMultiple); LOGUNIT_TEST(testShortCircuit); LOGUNIT_TEST_EXCEPTION(testInsertException, std::exception); LOGUNIT_TEST(testScientific); LOGUNIT_TEST(testPrecision); LOGUNIT_TEST(testWidth); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(testWide); LOGUNIT_TEST(testWideAppend); LOGUNIT_TEST(testWideWidth); #endif LOGUNIT_TEST(testBaseFlags); LOGUNIT_TEST(testBasePrecisionAndWidth); LOGUNIT_TEST(testLogStreamSimple); LOGUNIT_TEST(testLogStreamMultiple); LOGUNIT_TEST(testLogStreamShortCircuit); LOGUNIT_TEST_EXCEPTION(testLogStreamInsertException, std::exception); LOGUNIT_TEST(testLogStreamScientific); LOGUNIT_TEST(testLogStreamPrecision); LOGUNIT_TEST(testLogStreamWidth); LOGUNIT_TEST(testLogStreamDelegate); LOGUNIT_TEST(testLogStreamFormattingPersists); LOGUNIT_TEST(testSetWidthInsert); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(testWLogStreamSimple); LOGUNIT_TEST(testWLogStreamMultiple); LOGUNIT_TEST(testWLogStreamShortCircuit); LOGUNIT_TEST_EXCEPTION(testWLogStreamInsertException, std::exception); LOGUNIT_TEST(testWLogStreamScientific); LOGUNIT_TEST(testWLogStreamPrecision); LOGUNIT_TEST(testWLogStreamWidth); LOGUNIT_TEST(testWLogStreamDelegate); LOGUNIT_TEST(testWLogStreamFormattingPersists); LOGUNIT_TEST(testWSetWidthInsert); #endif #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(testUniChar); LOGUNIT_TEST(testUniCharAppend); // LOGUNIT_TEST(testUniCharWidth); LOGUNIT_TEST(testULogStreamSimple); LOGUNIT_TEST(testULogStreamMultiple); LOGUNIT_TEST(testULogStreamShortCircuit); LOGUNIT_TEST_EXCEPTION(testULogStreamInsertException, std::exception); // LOGUNIT_TEST(testULogStreamScientific); // LOGUNIT_TEST(testULogStreamPrecision); // LOGUNIT_TEST(testULogStreamWidth); LOGUNIT_TEST(testULogStreamDelegate); // LOGUNIT_TEST(testULogStreamFormattingPersists); // LOGUNIT_TEST(testUSetWidthInsert); #endif #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(testCFString); LOGUNIT_TEST(testCFStringAppend); LOGUNIT_TEST(testULogStreamCFString); LOGUNIT_TEST(testULogStreamCFString2); #endif LOGUNIT_TEST_SUITE_END(); VectorAppenderPtr vectorAppender; public: void setUp() { LoggerPtr root(Logger::getRootLogger()); LayoutPtr layout(new SimpleLayout()); vectorAppender = new VectorAppender(); root->addAppender(vectorAppender); } void tearDown() { LogManager::shutdown(); } void testSimple() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, "This is a test"); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testMultiple() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, "This is a test" << ": Details to follow"); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testShortCircuit() { LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit")); logger->setLevel(Level::getInfo()); ExceptionOnInsert someObj; LOG4CXX_DEBUG(logger, someObj); LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size()); } void testInsertException() { LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException")); ExceptionOnInsert someObj; LOG4CXX_INFO(logger, someObj); } void testScientific() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, std::scientific << 0.000001115); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos || msg.find(LOG4CXX_STR("E-")) != LogString::npos); } void testPrecision() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, std::setprecision(4) << 1.000001); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos); } void testWidth() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, '[' << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill('_') << 10.0 << ']'); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void testBaseFlags() { logstream base1(Logger::getRootLogger(), Level::getInfo()); logstream base2(Logger::getRootLogger(), Level::getInfo()); base1 << std::boolalpha; base2 << std::noboolalpha; std::ostringstream os1a, os1b, os2a, os2b; os1a << std::boolalpha; int fillchar; if (base1.set_stream_state(os1b, fillchar)) { os1b.fill(fillchar); } LOGUNIT_ASSERT_EQUAL(os1a.flags(), os1b.flags()); os2a << std::noboolalpha; if (base2.set_stream_state(os2b, fillchar)) { os2b.fill(fillchar); } LOGUNIT_ASSERT_EQUAL(os2a.flags(), os2b.flags()); } void testBasePrecisionAndWidth() { logstream base(Logger::getRootLogger(), Level::getInfo()); base.precision(2); base.width(5); std::ostringstream os1, os2; os1.precision(2); os1.width(5); os1 << 3.1415926; int fillchar; if (base.set_stream_state(os2, fillchar)) { os2.fill(fillchar); } os2 << 3.1415926; string expected(os1.str()); string actual(os2.str()); LOGUNIT_ASSERT_EQUAL(expected, actual); } void testLogStreamSimple() { logstream root(Logger::getRootLogger(), Level::getInfo()); root << "This is a test" << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testLogStreamMultiple() { logstream root(Logger::getRootLogger(), Level::getInfo()); root << "This is a test" << ": Details to follow" << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testLogStreamShortCircuit() { LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit")); logger->setLevel(Level::getInfo()); logstream os(logger, Level::getDebug()); ExceptionOnInsert someObj; os << someObj << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size()); } void testLogStreamInsertException() { LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException")); ExceptionOnInsert someObj; logstream os(logger, Level::getInfo()); os << someObj << LOG4CXX_ENDMSG; } void testLogStreamScientific() { LoggerPtr root(Logger::getRootLogger()); logstream os(root, Level::getInfo()); os << std::scientific << 0.000001115 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos || msg.find(LOG4CXX_STR("E-")) != LogString::npos); } void testLogStreamPrecision() { LoggerPtr root(Logger::getRootLogger()); logstream os(root, Level::getInfo()); os << std::setprecision(4) << 1.000001 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos); } void testLogStreamWidth() { LoggerPtr root(Logger::getRootLogger()); logstream os(root, Level::getInfo()); os << '[' << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill('_') << 10.0 << ']' << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void report(std::ostream& os) { os << "This just in: \n"; os << "Use logstream in places that expect a std::ostream.\n"; } void testLogStreamDelegate() { logstream root(Logger::getRootLogger(), Level::getInfo()); report(root); root << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testLogStreamFormattingPersists() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); logstream os(root, Level::getDebug()); os << std::hex << 20 << LOG4CXX_ENDMSG; os << Level::getInfo() << 16 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("10")), msg); } void testSetWidthInsert() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); logstream os(root, Level::getInfo()); os << std::setw(5); LOGUNIT_ASSERT_EQUAL(5, os.width()); } #if LOG4CXX_WCHAR_T_API void testWide() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, L"This is a test"); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWideAppend() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, L"This is a test" << L": Details to follow"); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWideWidth() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, L'[' << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill(L'_') << 10.0 << L"]"); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void testWLogStreamSimple() { wlogstream root(Logger::getRootLogger(), Level::getInfo()); root << L"This is a test" << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWLogStreamMultiple() { wlogstream root(Logger::getRootLogger(), Level::getInfo()); root << L"This is a test" << L": Details to follow" << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWLogStreamShortCircuit() { LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit")); logger->setLevel(Level::getInfo()); wlogstream os(logger, Level::getDebug()); ExceptionOnInsert someObj; os << someObj << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size()); } void testWLogStreamInsertException() { LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException")); ExceptionOnInsert someObj; wlogstream os(logger, Level::getInfo()); os << someObj << LOG4CXX_ENDMSG; } void testWLogStreamScientific() { LoggerPtr root(Logger::getRootLogger()); wlogstream os(root, Level::getInfo()); os << std::scientific << 0.000001115 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos || msg.find(LOG4CXX_STR("E-")) != LogString::npos); } void testWLogStreamPrecision() { LoggerPtr root(Logger::getRootLogger()); wlogstream os(root, Level::getInfo()); os << std::setprecision(4) << 1.000001 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos); } void testWLogStreamWidth() { LoggerPtr root(Logger::getRootLogger()); wlogstream os(root, Level::getInfo()); os << L"[" << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill(L'_') << 10.0 << L"]" << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void wreport(std::basic_ostream<wchar_t>& os) { os << L"This just in: \n"; os << L"Use logstream in places that expect a std::ostream.\n"; } void testWLogStreamDelegate() { wlogstream root(Logger::getRootLogger(), Level::getInfo()); wreport(root); root << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWLogStreamFormattingPersists() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); wlogstream os(root, Level::getDebug()); os << std::hex << 20 << LOG4CXX_ENDMSG; os << Level::getInfo() << 16 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("10")), msg); } void testWSetWidthInsert() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); wlogstream os(root, Level::getInfo()); os << std::setw(5); LOGUNIT_ASSERT_EQUAL(5, os.width()); } #endif #if LOG4CXX_UNICHAR_API void testUniChar() { LoggerPtr root(Logger::getRootLogger()); const log4cxx::UniChar msg[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 }; LOG4CXX_INFO(root, msg); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testUniCharAppend() { LoggerPtr root(Logger::getRootLogger()); const log4cxx::UniChar msg1[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 }; const log4cxx::UniChar msg2[] = { ':', ' ', 'D', 'e', 't', 'a', 'i', 'l', 's', ' ', 't', 'o', ' ', 'f', 'o', 'l', 'l', 'o', 'w', 0 }; LOG4CXX_INFO(root, msg1 << msg2); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testUniCharWidth() { LoggerPtr root(Logger::getRootLogger()); const log4cxx::UniChar openBracket[] = { '[', 0 }; const log4cxx::UniChar closeBracket[] = { ']', 0 }; LOG4CXX_INFO(root, openBracket << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill((log4cxx::UniChar) '_') << 10.0 << closeBracket); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void testULogStreamSimple() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); const log4cxx::UniChar msg[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 }; root << msg << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testULogStreamMultiple() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); const log4cxx::UniChar msg1[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 }; const log4cxx::UniChar msg2[] = { ':', ' ', 'D', 'e', 't', 'a', 'i', 'l', 's', ' ', 't', 'o', ' ', 'f', 'o', 'l', 'l', 'o', 'w', 0 }; root << msg1 << msg2 << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testULogStreamShortCircuit() { LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit")); logger->setLevel(Level::getInfo()); ulogstream os(logger, Level::getDebug()); ExceptionOnInsert someObj; os << someObj << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size()); } void testULogStreamInsertException() { LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException")); ExceptionOnInsert someObj; ulogstream os(logger, Level::getInfo()); os << someObj << LOG4CXX_ENDMSG; } void testULogStreamScientific() { LoggerPtr root(Logger::getRootLogger()); ulogstream os(root, Level::getInfo()); os << std::scientific << 0.000001115 << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos || msg.find(LOG4CXX_STR("E-")) != LogString::npos); } void testULogStreamPrecision() { LoggerPtr root(Logger::getRootLogger()); ulogstream os(root, Level::getInfo()); os << std::setprecision(4) << 1.000001 << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos); } void testULogStreamWidth() { LoggerPtr root(Logger::getRootLogger()); ulogstream os(root, Level::getInfo()); const log4cxx::UniChar openBracket[] = { '[', 0 }; const log4cxx::UniChar closeBracket[] = { ']', 0 }; os << openBracket << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill((log4cxx::UniChar) '_') << 10.0 << closeBracket << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void ureport(std::basic_ostream<log4cxx::UniChar>& os) { const log4cxx::UniChar msg1[] = { 'T', 'h', 'i', 's', ' ', 'j', 'u', 's', 't', ' ' , 'i', 'n', ':', ' ' , '\n', 0 }; const log4cxx::UniChar msg2[] = { 'U', 's', 'e', ' ', 'l', 'o', 'g', 's', 't', 'r', 'e', 'a', 'm', '\n', 0 }; os << msg1; os << msg2; } void testULogStreamDelegate() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); ureport(root); root << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testULogStreamFormattingPersists() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); ulogstream os(root, Level::getDebug()); os << std::hex << 20 << LOG4CXX_ENDMSG; os << Level::getInfo() << 16 << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("10")), msg); } void testUSetWidthInsert() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); ulogstream os(root, Level::getInfo()); os << std::setw(5); LOGUNIT_ASSERT_EQUAL(5, os.width()); } #endif #if LOG4CXX_CFSTRING_API void testCFString() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, CFSTR("This is a test")); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testCFStringAppend() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, CFSTR("This is a test") << CFSTR(": Details to follow")); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testULogStreamCFString() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); root << CFSTR("This is a test") << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testULogStreamCFString2() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); root << CFSTR("This is a test") << CFSTR(": Details to follow") << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(StreamTestCase); #if !LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE // // The following code tests compilation errors // around bug LOGCXX-150 and is not intended to be executed. // Skipped for VC6 since it can't handle having the // templated operator<< in class scope.s namespace foo { class Bar { void fn(); }; std::ostream &operator<<(std::ostream &o, Bar const &b) { return o << "Bar"; } } using namespace foo; namespace { log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("foo")); log4cxx::logstream lout(logger, log4cxx::Level::getDebug()); } void Bar::fn() { lout << "hi" << LOG4CXX_ENDMSG; } #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "logunit.h" #include <log4cxx/logger.h> #include <log4cxx/simplelayout.h> #include <log4cxx/ttcclayout.h> #include <log4cxx/fileappender.h> #include <log4cxx/helpers/absolutetimedateformat.h> #include "util/compare.h" #include "util/transformer.h" #include "util/linenumberfilter.h" #include "util/controlfilter.h" #include "util/absolutedateandtimefilter.h" #include "util/threadfilter.h" #include <log4cxx/file.h> #include <iostream> #include <log4cxx/helpers/pool.h> #include <apr_strings.h> #include "testchar.h" #include <log4cxx/spi/loggerrepository.h> #include <log4cxx/helpers/stringhelper.h> #include <apr_strings.h> using namespace log4cxx; using namespace log4cxx::helpers; #define TTCC_PAT \ ABSOLUTE_DATE_AND_TIME_PAT \ " \\[0x[0-9A-F]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]\\{1,2\\}" #define TTCC2_PAT \ ABSOLUTE_DATE_AND_TIME_PAT \ " \\[0x[0-9A-F]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - " \ "Messages should bear numbers 0 through 23\\." LOGUNIT_CLASS(MinimumTestCase) { LOGUNIT_TEST_SUITE(MinimumTestCase); LOGUNIT_TEST(simple); LOGUNIT_TEST(ttcc); LOGUNIT_TEST_SUITE_END(); public: void setUp() { root = Logger::getRootLogger(); root->removeAllAppenders(); } void tearDown() { root->getLoggerRepository()->resetConfiguration(); } void simple() { LayoutPtr layout = new SimpleLayout(); AppenderPtr appender = new FileAppender(layout, LOG4CXX_STR("output/simple"), false); root->addAppender(appender); common(); LOGUNIT_ASSERT(Compare::compare(LOG4CXX_FILE("output/simple"), LOG4CXX_FILE("witness/simple"))); } void ttcc() { LayoutPtr layout = new TTCCLayout(LOG4CXX_STR("DATE")); AppenderPtr appender = new FileAppender(layout, LOG4CXX_STR("output/ttcc"), false); root->addAppender(appender); common(); ControlFilter filter1; filter1 << TTCC_PAT << TTCC2_PAT; AbsoluteDateAndTimeFilter filter2; ThreadFilter filter3; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { const File output("output/ttcc"); Transformer::transform(output, FILTERED, filters); } catch(std::exception& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } const File witness("witness/ttcc"); LOGUNIT_ASSERT(Compare::compare(FILTERED, witness)); } std::string createMessage(int i, Pool& pool) { std::string msg("Message "); msg.append(pool.itoa(i)); return msg; } void common() { int i = 0; // In the lines below, the logger names are chosen as an aid in // remembering their level values. In general, the logger names // have no bearing to level values. LoggerPtr ERRlogger = Logger::getLogger(LOG4CXX_TEST_STR("ERR")); ERRlogger->setLevel(Level::getError()); LoggerPtr INF = Logger::getLogger(LOG4CXX_TEST_STR("INF")); INF->setLevel(Level::getInfo()); LoggerPtr INF_ERR = Logger::getLogger(LOG4CXX_TEST_STR("INF.ERR")); INF_ERR->setLevel(Level::getError()); LoggerPtr DEB = Logger::getLogger(LOG4CXX_TEST_STR("DEB")); DEB->setLevel(Level::getDebug()); // Note: categories with undefined level LoggerPtr INF_UNDEF = Logger::getLogger(LOG4CXX_TEST_STR("INF.UNDEF")); LoggerPtr INF_ERR_UNDEF = Logger::getLogger(LOG4CXX_TEST_STR("INF.ERR.UNDEF")); LoggerPtr UNDEF = Logger::getLogger(LOG4CXX_TEST_STR("UNDEF")); std::string msg("Message "); Pool pool; // These should all log.---------------------------- LOG4CXX_FATAL(ERRlogger, createMessage(i, pool)); i++; //0 LOG4CXX_ERROR(ERRlogger, createMessage(i, pool)); i++; LOG4CXX_FATAL(INF, createMessage(i, pool)); i++; // 2 LOG4CXX_ERROR(INF, createMessage(i, pool)); i++; LOG4CXX_WARN(INF, createMessage(i, pool)); i++; LOG4CXX_INFO(INF, createMessage(i, pool)); i++; LOG4CXX_FATAL(INF_UNDEF, createMessage(i, pool)); i++; //6 LOG4CXX_ERROR(INF_UNDEF, createMessage(i, pool)); i++; LOG4CXX_WARN(INF_UNDEF, createMessage(i, pool)); i++; LOG4CXX_INFO(INF_UNDEF, createMessage(i, pool)); i++; LOG4CXX_FATAL(INF_ERR, createMessage(i, pool)); i++; // 10 LOG4CXX_ERROR(INF_ERR, createMessage(i, pool)); i++; LOG4CXX_FATAL(INF_ERR_UNDEF, createMessage(i, pool)); i++; LOG4CXX_ERROR(INF_ERR_UNDEF, createMessage(i, pool)); i++; LOG4CXX_FATAL(DEB, createMessage(i, pool)); i++; //14 LOG4CXX_ERROR(DEB, createMessage(i, pool)); i++; LOG4CXX_WARN(DEB, createMessage(i, pool)); i++; LOG4CXX_INFO(DEB, createMessage(i, pool)); i++; LOG4CXX_DEBUG(DEB, createMessage(i, pool)); i++; // defaultLevel=DEBUG LOG4CXX_FATAL(UNDEF, createMessage(i, pool)); i++; // 19 LOG4CXX_ERROR(UNDEF, createMessage(i, pool)); i++; LOG4CXX_WARN(UNDEF, createMessage(i, pool)); i++; LOG4CXX_INFO(UNDEF, createMessage(i, pool)); i++; LOG4CXX_DEBUG(UNDEF, createMessage(i, pool)); i++; // ------------------------------------------------- // The following should not log LOG4CXX_WARN(ERRlogger, createMessage(i, pool)); i++; LOG4CXX_INFO(ERRlogger, createMessage(i, pool)); i++; LOG4CXX_DEBUG(ERRlogger, createMessage(i, pool)); i++; LOG4CXX_DEBUG(INF, createMessage(i, pool)); i++; LOG4CXX_DEBUG(INF_UNDEF, createMessage(i, pool)); i++; LOG4CXX_WARN(INF_ERR, createMessage(i, pool)); i++; LOG4CXX_INFO(INF_ERR, createMessage(i, pool)); i++; LOG4CXX_DEBUG(INF_ERR, createMessage(i, pool)); i++; LOG4CXX_WARN(INF_ERR_UNDEF, createMessage(i, pool)); i++; LOG4CXX_INFO(INF_ERR_UNDEF, createMessage(i, pool)); i++; LOG4CXX_DEBUG(INF_ERR_UNDEF, createMessage(i, pool)); i++; // ------------------------------------------------- LOG4CXX_INFO(INF, LOG4CXX_TEST_STR("Messages should bear numbers 0 through 23.")); } LoggerPtr root; LoggerPtr logger; private: static const File FILTERED; }; const File MinimumTestCase::FILTERED("output/filtered"); LOGUNIT_TEST_SUITE_REGISTRATION(MinimumTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG4CXX_TEST 1 #include <log4cxx/private/log4cxx_private.h> #include "../logunit.h" #include "xlogger.h" #include <log4cxx/xml/domconfigurator.h> #include "../util/transformer.h" #include "../util/compare.h" #include <log4cxx/file.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; #define LOG4CXX_TEST_STR(x) L##x /** Tests handling of custom loggers. */ LOGUNIT_CLASS(XLoggerTestCase) { LOGUNIT_TEST_SUITE(XLoggerTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST_SUITE_END(); XLoggerPtr logger; public: void setUp() { logger = XLogger::getLogger( LOG4CXX_STR("org.apache.log4j.customLogger.XLoggerTestCase")); } void tearDown() { logger->getLoggerRepository()->resetConfiguration(); } void test1() { common("1"); } void test2() { common("2"); } void common(const char* number) { std::string fn("input/xml/customLogger"); fn.append(number); fn.append(".xml"); DOMConfigurator::configure(fn); int i = 0; LOG4CXX_LOG(logger, log4cxx::XLevel::getTrace(), "Message " << i); i++; LOG4CXX_DEBUG(logger, "Message " << i); i++; LOG4CXX_WARN(logger, "Message " << i); i++; LOG4CXX_ERROR(logger, "Message " << i); i++; LOG4CXX_FATAL(logger, "Message " << i); i++; LOG4CXX_DEBUG(logger, "Message " << i); const File OUTPUT("output/temp"); std::string witness("witness/customLogger."); witness.append(number); const File WITNESS(witness); LOGUNIT_ASSERT(Compare::compare(OUTPUT, WITNESS)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(XLoggerTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include "../xml/xlevel.h" #include <log4cxx/spi/loggerfactory.h> namespace log4cxx { namespace spi { namespace location { class LocationInfo; } } // Any sub-class of Logger must also have its own implementation of // LoggerFactory. class XFactory : public virtual spi::LoggerFactory, public virtual helpers::ObjectImpl { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(XFactory) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(XFactory) LOG4CXX_CAST_ENTRY(spi::LoggerFactory) END_LOG4CXX_CAST_MAP() XFactory(); virtual LoggerPtr makeNewLoggerInstance( log4cxx::helpers::Pool& pool, const LogString& name) const; }; typedef helpers::ObjectPtrT<XFactory> XFactoryPtr; /** A simple example showing Logger sub-classing. It shows the minimum steps necessary to implement one's {@link LoggerFactory}. Note that sub-classes follow the hierarchy even if its loggers belong to different classes. */ class XLogger : public Logger { // It's enough to instantiate a factory once and for all. static XFactoryPtr factory; LogString suffix; public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(XLogger) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(XLogger) LOG4CXX_CAST_ENTRY_CHAIN(Logger) END_LOG4CXX_CAST_MAP() /** Just calls the parent constuctor. */ XLogger(log4cxx::helpers::Pool& pool, const LogString& name1) : Logger(pool, name1) {} /** Nothing to activate. */ void activateOptions() {} /** We introduce a new printing method in order to support {@link XLevel#LETHAL}. */ void lethal(const LogString& message, const log4cxx::spi::LocationInfo& location); /** We introduce a new printing method in order to support {@link XLevel#LETHAL}. */ void lethal(const LogString& message); static LoggerPtr getLogger(const LogString& name); static LoggerPtr getLogger(const helpers::Class& clazz); LogString getSuffix() const { return suffix; } void setSuffix(const LogString& suffix1) { this->suffix = suffix1; } /** We introduce a new printing method that takes the TRACE level. */ void trace(const LogString& message, const log4cxx::spi::LocationInfo& location); /** We introduce a new printing method that takes the TRACE level. */ void trace(const LogString& message); }; typedef helpers::ObjectPtrT<XLogger> XLoggerPtr; }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #include "xlogger.h" #include <log4cxx/level.h> #include <log4cxx/logmanager.h> #include <log4cxx/spi/location/locationinfo.h> #include <log4cxx/spi/loggerrepository.h> using namespace log4cxx; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(XLogger) IMPLEMENT_LOG4CXX_OBJECT(XFactory) XFactoryPtr XLogger::factory = new XFactory(); void XLogger::lethal(const LogString& message, const LocationInfo& locationInfo) { if (repository->isDisabled(XLevel::LETHAL_INT)) { return; } if (XLevel::getLethal()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getLethal(), message, locationInfo); } } void XLogger::lethal(const LogString& message) { if (repository->isDisabled(XLevel::LETHAL_INT)) { return; } if (XLevel::getLethal()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getLethal(), message, LocationInfo::getLocationUnavailable()); } } LoggerPtr XLogger::getLogger(const LogString& name) { return LogManager::getLogger(name, factory); } LoggerPtr XLogger::getLogger(const helpers::Class& clazz) { return XLogger::getLogger(clazz.getName()); } void XLogger::trace(const LogString& message, const LocationInfo& locationInfo) { if (repository->isDisabled(XLevel::TRACE_INT)) { return; } if (XLevel::getTrace()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getTrace(), message, locationInfo); } } void XLogger::trace(const LogString& message) { if (repository->isDisabled(XLevel::TRACE_INT)) { return; } if (XLevel::getTrace()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getTrace(), message, LocationInfo::getLocationUnavailable()); } } XFactory::XFactory() { } LoggerPtr XFactory::makeNewLoggerInstance(log4cxx::helpers::Pool& pool, const LogString& name) const { return new XLogger(pool, name); }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/db/odbcappender.h> #include "../appenderskeletontestcase.h" #include "../logunit.h" #define LOG4CXX_TEST 1 #include <log4cxx/private/log4cxx_private.h> #ifdef LOG4CXX_HAVE_ODBC using namespace log4cxx; using namespace log4cxx::helpers; /** Unit tests of log4cxx::SocketAppender */ class ODBCAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(ODBCAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::db::ODBCAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ODBCAppenderTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "writerappendertestcase.h" #include <log4cxx/helpers/objectptr.h> #include <log4cxx/writerappender.h> using namespace log4cxx; using namespace log4cxx::helpers; AppenderSkeleton* WriterAppenderTestCase::createAppenderSkeleton() const { return createWriterAppender(); }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/helpers/propertyresourcebundle.h> #include <log4cxx/helpers/locale.h> #include "util/compare.h" #include <vector> #include <sstream> #include "testchar.h" #include "logunit.h" #include <log4cxx/spi/loggerrepository.h> typedef std::basic_ostringstream<testchar> StringBuffer; using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(L7dTestCase) { LOGUNIT_TEST_SUITE(L7dTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; ResourceBundlePtr bundles[3]; public: void setUp() { Locale localeUS(LOG4CXX_STR("en"), LOG4CXX_STR("US")); bundles[0] = ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeUS); LOGUNIT_ASSERT(bundles[0] != 0); Locale localeFR(LOG4CXX_STR("fr"), LOG4CXX_STR("FR")); bundles[1] = ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeFR); LOGUNIT_ASSERT(bundles[1] != 0); Locale localeCH(LOG4CXX_STR("fr"), LOG4CXX_STR("CH")); bundles[2] = ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeCH); LOGUNIT_ASSERT(bundles[2] != 0); root = Logger::getRootLogger(); } void tearDown() { root->getLoggerRepository()->resetConfiguration(); } void test1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/l7d1.properties")); log4cxx::helpers::Pool pool; for (int i = 0; i < 3; i++) { root->setResourceBundle(bundles[i]); LOG4CXX_L7DLOG(root, Level::getDebug(), LOG4CXX_TEST_STR("bogus1")); LOG4CXX_L7DLOG(root, Level::getInfo(), LOG4CXX_TEST_STR("test")); LOG4CXX_L7DLOG(root, Level::getWarn(), LOG4CXX_TEST_STR("hello_world")); StringBuffer os; os << (i + 1); LOG4CXX_L7DLOG2(root, Level::getDebug(), LOG4CXX_TEST_STR("msg1"), os.str().c_str(), LOG4CXX_TEST_STR("log4j")); LOG4CXX_L7DLOG2(root, Level::getError(), LOG4CXX_TEST_STR("bogusMsg"), os.str().c_str(), LOG4CXX_TEST_STR("log4j")); LOG4CXX_L7DLOG2(root, Level::getError(), LOG4CXX_TEST_STR("msg1"), os.str().c_str(), LOG4CXX_TEST_STR("log4j")); LOG4CXX_L7DLOG(root, Level::getInfo(), LOG4CXX_TEST_STR("bogus2")); } LOGUNIT_ASSERT(Compare::compare(LOG4CXX_FILE("output/temp"), LOG4CXX_FILE("witness/l7d.1"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(L7dTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/file.h> #include "logunit.h" #include "insertwide.h" #include <log4cxx/helpers/pool.h> #include <apr_errno.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/fileinputstream.h> #include <log4cxx/helpers/outputstreamwriter.h> #include <log4cxx/helpers/fileoutputstream.h> #include <log4cxx/helpers/inputstreamreader.h> #include <log4cxx/helpers/fileinputstream.h> #if LOG4CXX_CFSTRING_API #include <CoreFoundation/CFString.h> #endif using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(FileTestCase) { LOGUNIT_TEST_SUITE(FileTestCase); LOGUNIT_TEST(defaultConstructor); LOGUNIT_TEST(defaultExists); LOGUNIT_TEST(defaultRead); LOGUNIT_TEST(propertyRead); LOGUNIT_TEST(propertyExists); LOGUNIT_TEST(fileWrite1); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(wcharConstructor); #endif #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(unicharConstructor); #endif #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(cfstringConstructor); #endif LOGUNIT_TEST(copyConstructor); LOGUNIT_TEST(assignment); LOGUNIT_TEST(deleteBackslashedFileName); LOGUNIT_TEST_SUITE_END(); public: void defaultConstructor() { File defFile; LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR(""), defFile.getPath()); } void defaultExists() { File defFile; Pool pool; bool exists = defFile.exists(pool); LOGUNIT_ASSERT_EQUAL(false, exists); } // check default constructor. read() throws an exception // if no file name was given. void defaultRead() { File defFile; Pool pool; try { InputStreamPtr defInput = new FileInputStream(defFile); InputStreamReaderPtr inputReader = new InputStreamReader(defInput); LogString contents(inputReader->read(pool)); LOGUNIT_ASSERT(false); } catch(IOException &ex) { } } #if LOG4CXX_WCHAR_T_API void wcharConstructor() { File propFile(L"input/patternLayout1.properties"); Pool pool; bool exists = propFile.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } #endif #if LOG4CXX_UNICHAR_API void unicharConstructor() { const log4cxx::UniChar filename[] = { 'i', 'n', 'p', 'u', 't', '/', 'p', 'a', 't', 't', 'e', 'r', 'n', 'L', 'a', 'y', 'o', 'u', 't', '1', '.', 'p', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's', 0 }; File propFile(filename); Pool pool; bool exists = propFile.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } #endif #if LOG4CXX_CFSTRING_API void cfstringConstructor() { File propFile(CFSTR("input/patternLayout.properties")); Pool pool; bool exists = propFile.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } #endif void copyConstructor() { File propFile("input/patternLayout1.properties"); File copy(propFile); Pool pool; bool exists = copy.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } void assignment() { File propFile("input/patternLayout1.properties"); File copy = propFile; Pool pool; bool exists = copy.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } void propertyRead() { File propFile("input/patternLayout1.properties"); Pool pool; InputStreamPtr propStream = new FileInputStream(propFile); InputStreamReaderPtr propReader = new InputStreamReader(propStream); LogString props(propReader->read(pool)); LogString line1(LOG4CXX_STR("# Licensed to the Apache Software Foundation (ASF) under one or more")); LOGUNIT_ASSERT_EQUAL(line1, props.substr(0, line1.length())); } void propertyExists() { File propFile("input/patternLayout1.properties"); Pool pool; bool exists = propFile.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } void fileWrite1() { OutputStreamPtr fos = new FileOutputStream(LOG4CXX_STR("output/fileWrite1.txt")); OutputStreamWriterPtr osw = new OutputStreamWriter(fos); Pool pool; LogString greeting(LOG4CXX_STR("Hello, World")); greeting.append(LOG4CXX_EOL); osw->write(greeting, pool); InputStreamPtr is = new FileInputStream(LOG4CXX_STR("output/fileWrite1.txt")); InputStreamReaderPtr isr = new InputStreamReader(is); LogString reply = isr->read(pool); LOGUNIT_ASSERT_EQUAL(greeting, reply); } /** * Tests conversion of backslash containing file names. * Would cause infinite loop due to bug LOGCXX-105. */ void deleteBackslashedFileName() { File file("output\\bogus.txt"); Pool pool; /*bool deleted = */file.deleteFile(pool); } }; LOGUNIT_TEST_SUITE_REGISTRATION(FileTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include "logunit.h" // // If there is no support for wchar_t logging then // there is not a consistent way to get the test characters logged // #if LOG4CXX_WCHAR_T_API #include <log4cxx/patternlayout.h> #include <log4cxx/fileappender.h> #include <log4cxx/level.h> #include "util/binarycompare.h" #include <log4cxx/file.h> #include <log4cxx/helpers/pool.h> using namespace log4cxx; using namespace log4cxx::util; using namespace log4cxx::helpers; /** * Tests support for encoding specification. * * */ LOGUNIT_CLASS(EncodingTest) { LOGUNIT_TEST_SUITE(EncodingTest); LOGUNIT_TEST(testASCII); LOGUNIT_TEST(testLatin1); LOGUNIT_TEST(testUtf8); LOGUNIT_TEST(testUtf16); LOGUNIT_TEST(testUtf16LE); LOGUNIT_TEST(testUtf16BE); LOGUNIT_TEST_SUITE_END(); public: /** * Resets configuration after each test. */ void tearDown() { Logger::getRootLogger()->getLoggerRepository()->resetConfiguration(); } /** * Test us-ascii encoding. */ void testASCII() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/ascii.log"), LOG4CXX_STR("US-ASCII")); common(root); BinaryCompare::compare("output/ascii.log", "witness/encoding/ascii.log"); } /** * Test iso-8859-1 encoding. */ void testLatin1() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/latin1.log"), LOG4CXX_STR("iso-8859-1")); common(root); BinaryCompare::compare("output/latin1.log", "witness/encoding/latin1.log"); } /** * Test utf-8 encoding. */ void testUtf8() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/UTF-8.log"), LOG4CXX_STR("UTF-8")); common(root); BinaryCompare::compare("output/UTF-8.log", "witness/encoding/UTF-8.log"); } /** * Test utf-16 encoding. */ void testUtf16() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/UTF-16.log"), LOG4CXX_STR("UTF-16")); common(root); BinaryCompare::compare("output/UTF-16.log", "witness/encoding/UTF-16.log"); } /** * Test utf-16be encoding. */ void testUtf16BE() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/UTF-16BE.log"), LOG4CXX_STR("UTF-16BE")); common(root); BinaryCompare::compare("output/UTF-16BE.log", "witness/encoding/UTF-16BE.log"); } /** * Test utf16-le encoding. */ void testUtf16LE() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/UTF-16LE.log"), LOG4CXX_STR("UTF-16LE")); common(root); BinaryCompare::compare("output/UTF-16LE.log", "witness/encoding/UTF-16LE.log"); } /** * Configure logging. * @param logger logger * @param filename logging file name * @param encoding encoding */ private: void configure(LoggerPtr& logger, const LogString& filename, const LogString& encoding) { PatternLayoutPtr layout(new PatternLayout()); layout->setConversionPattern(LOG4CXX_STR("%p - %m\n")); Pool p; layout->activateOptions(p); FileAppenderPtr appender(new FileAppender()); appender->setFile(filename); appender->setEncoding(encoding); appender->setAppend(false); appender->setLayout(layout); appender->activateOptions(p); logger->addAppender(appender); logger->setLevel(Level::getInfo()); } /** * Common logging requests. * @param logger logger */ void common(LoggerPtr& logger) { logger->info("Hello, World"); // pi can be encoded in iso-8859-1 const wchar_t pi[] = { 0x00B9, 0 }; logger->info(pi); // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const wchar_t greeting[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 }; logger->info(greeting); } }; LOGUNIT_TEST_SUITE_REGISTRATION(EncodingTest); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/pattern/filedatepatternconverter.h> #include <log4cxx/pattern/integerpatternconverter.h> #include <log4cxx/pattern/patternparser.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/helpers/date.h> #include <log4cxx/helpers/integer.h> #include "../util/compare.h" #include "../logunit.h" #include "../insertwide.h" #include <apr_time.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::pattern; /** * Tests for FileNamePattern. * * * * */ LOGUNIT_CLASS(FileNamePatternTestCase) { LOGUNIT_TEST_SUITE(FileNamePatternTestCase); LOGUNIT_TEST(testFormatInteger1); LOGUNIT_TEST(testFormatInteger2); LOGUNIT_TEST(testFormatInteger3); LOGUNIT_TEST(testFormatInteger4); LOGUNIT_TEST(testFormatInteger5); LOGUNIT_TEST(testFormatInteger6); LOGUNIT_TEST(testFormatInteger7); LOGUNIT_TEST(testFormatInteger8); LOGUNIT_TEST(testFormatInteger9); LOGUNIT_TEST(testFormatInteger10); LOGUNIT_TEST(testFormatInteger11); LOGUNIT_TEST(testFormatDate1); // // TODO: Problem with timezone offset // LOGUNIT_TEST(testFormatDate2); // LOGUNIT_TEST(testFormatDate3); LOGUNIT_TEST(testFormatDate4); LOGUNIT_TEST(testFormatDate5); LOGUNIT_TEST_SUITE_END(); public: LogString format(const LogString& pattern, const ObjectPtr& obj) { std::vector<PatternConverterPtr> converters; std::vector<FormattingInfoPtr> fields; PatternMap rules; rules.insert(PatternMap::value_type(LOG4CXX_STR("d"), (PatternConstructor) FileDatePatternConverter::newInstance)); rules.insert(PatternMap::value_type(LOG4CXX_STR("i"), (PatternConstructor) IntegerPatternConverter::newInstance)); PatternParser::parse(pattern, converters, fields, rules); LogString result; Pool pool; std::vector<FormattingInfoPtr>::const_iterator fieldIter = fields.begin(); for(std::vector<PatternConverterPtr>::const_iterator converterIter = converters.begin(); converterIter != converters.end(); converterIter++, fieldIter++) { LogString::size_type i = result.length(); (*converterIter)->format(obj, result, pool); (*fieldIter)->format(i, result); } return result; } void assertDatePattern(const LogString& pattern, int year, int month, int day, int hour, int min, const LogString& expected) { apr_time_exp_t tm; memset(&tm, 0, sizeof(tm)); tm.tm_min = min; tm.tm_hour = hour; tm.tm_mday = day; tm.tm_mon = month; tm.tm_year = year - 1900; apr_time_t n; /*apr_status_t stat = */apr_time_exp_get(&n, &tm); ObjectPtr obj(new Date(n)); LOGUNIT_ASSERT_EQUAL(expected, format(pattern, obj)); } void assertIntegerPattern(const LogString& pattern, int value, const LogString& expected) { ObjectPtr obj(new Integer(value)); LOGUNIT_ASSERT_EQUAL(expected, format(pattern, obj)); } void testFormatInteger1() { assertIntegerPattern(LOG4CXX_STR("t"), 3, LOG4CXX_STR("t")); } void testFormatInteger2() { assertIntegerPattern(LOG4CXX_STR("foo"), 3, LOG4CXX_STR("foo")); } void testFormatInteger3() { assertIntegerPattern(LOG4CXX_STR("foo%"), 3, LOG4CXX_STR("foo%")); } void testFormatInteger4() { assertIntegerPattern(LOG4CXX_STR("%ifoo"), 3, LOG4CXX_STR("3foo")); } void testFormatInteger5() { assertIntegerPattern(LOG4CXX_STR("foo%ixixo"), 3, LOG4CXX_STR("foo3xixo")); } void testFormatInteger6() { assertIntegerPattern(LOG4CXX_STR("foo%i.log"), 3, LOG4CXX_STR("foo3.log")); } void testFormatInteger7() { assertIntegerPattern(LOG4CXX_STR("foo.%i.log"), 3, LOG4CXX_STR("foo.3.log")); } void testFormatInteger8() { assertIntegerPattern(LOG4CXX_STR("%ifoo%"), 3, LOG4CXX_STR("3foo%")); } void testFormatInteger9() { assertIntegerPattern(LOG4CXX_STR("%ifoo%%"), 3, LOG4CXX_STR("3foo%")); } void testFormatInteger10() { assertIntegerPattern(LOG4CXX_STR("%%foo"), 3, LOG4CXX_STR("%foo")); } void testFormatInteger11() { assertIntegerPattern(LOG4CXX_STR("foo%ibar%i"), 3, LOG4CXX_STR("foo3bar3")); } void testFormatDate1() { assertDatePattern(LOG4CXX_STR("foo%d{yyyy.MM.dd}"), 2003, 4, 20, 17, 55, LOG4CXX_STR("foo2003.05.20")); } void testFormatDate2() { assertDatePattern(LOG4CXX_STR("foo%d{yyyy.MM.dd HH:mm}"), 2003, 4, 20, 17, 55, LOG4CXX_STR("foo2003.05.20 17:55")); } void testFormatDate3() { assertDatePattern(LOG4CXX_STR("%d{yyyy.MM.dd HH:mm} foo"), 2003, 4, 20, 17, 55, LOG4CXX_STR("2003.05.20 17:55 foo")); } void testFormatDate4() { assertDatePattern(LOG4CXX_STR("foo%dyyyy.MM.dd}"), 2003, 4, 20, 17, 55, LOG4CXX_STR("foo2003-05-20yyyy.MM.dd}")); } void testFormatDate5() { assertDatePattern(LOG4CXX_STR("foo%d{yyyy.MM.dd"), 2003, 4, 20, 17, 55, LOG4CXX_STR("foo2003-05-20{yyyy.MM.dd")); } }; // // See bug LOGCXX-204 // #if !defined(_MSC_VER) || _MSC_VER > 1200 LOGUNIT_TEST_SUITE_REGISTRATION(FileNamePatternTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../util/compare.h" #include "../insertwide.h" #include "../logunit.h" #include <apr_time.h> #include <log4cxx/logmanager.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/patternlayout.h> #include <log4cxx/rolling/fixedwindowrollingpolicy.h> #include <log4cxx/rolling/sizebasedtriggeringpolicy.h> #include <log4cxx/filter/levelrangefilter.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/consoleappender.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/fileoutputstream.h> using namespace log4cxx; using namespace log4cxx::xml; using namespace log4cxx::filter; using namespace log4cxx::helpers; using namespace log4cxx::rolling; /** * Tests of explicit manual rolling of RollingFileAppenders. * * * */ LOGUNIT_CLASS(ManualRollingTest) { LOGUNIT_TEST_SUITE(ManualRollingTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); // TODO: Compression not yet implemented // LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { logger = Logger::getLogger("org.apache.log4j.rolling.ManualRollingTest"); root = Logger::getRootLogger(); } void tearDown() { LogManager::shutdown(); } void common(RollingFileAppenderPtr& rfa, Pool& pool, LoggerPtr& logger1) { char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', 'N', 0 }; // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { msg[8] = '0' + i; } else if (i < 100) { int digit = i % 10; if (digit == 0) { rfa->rollover(pool); } msg[7] = '0' + i / 10; msg[8] = '0' + digit; } LOG4CXX_DEBUG(logger1, msg); } } /** * Tests that the lack of an explicit active file will use the * low index as the active file. * */ void test1() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy(); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/manual-test1.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->activateOptions(p); root->addAppender(rfa); common(rfa, p, logger); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test1.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test1.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test1.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test1.0"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test1.1"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test1.2"), File("witness/rolling/sbr-test2.1"))); } /** * Test basic rolling functionality with explicit setting of FileAppender.file. */ void test2() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/manual-test2.log")); Pool p; rfa->activateOptions(p); root->addAppender(rfa); common(rfa, p, logger); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test2.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test2.log.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test2.log.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test2.log"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test2.log.1"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test2.log.2"), File("witness/rolling/sbr-test2.1"))); } /** * Same as testBasic but also with GZ compression. */ void test3() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr fwrp = new FixedWindowRollingPolicy(); fwrp->setMinIndex(0); rfa->setFile(LOG4CXX_STR("output/manual-test3.log")); fwrp->setFileNamePattern(LOG4CXX_STR("output/sbr-test3.%i.gz")); Pool p; fwrp->activateOptions(p); rfa->setRollingPolicy(fwrp); rfa->activateOptions(p); root->addAppender(rfa); common(rfa, p, logger); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test3.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test3.0.gz").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test3.1.gz").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test3.log"), File("witness/rolling/sbr-test3.log"))); LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.0.gz").length(p), File("output/manual-test3.0.gz").length(p)); LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.1.gz").length(p), File("output/manual-test3.1.gz").length(p)); } /** * Test basic rolling functionality with bogus path in file name pattern. */ void test4() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/manual-test4.log")); FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy(); swrp->setMinIndex(0); // // test4 directory should not exists. Should cause all rollover attempts to fail. // swrp->setFileNamePattern(LOG4CXX_STR("output/test4/manual-test4.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->activateOptions(p); root->addAppender(rfa); common(rfa, p, logger); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test4.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test4.log"), File("witness/rolling/sbr-test4.log"))); } /** * Checking handling of rename failures due to other access * to the indexed files. */ void test5() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/manual-test5.log")); FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy(); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/manual-test5.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->activateOptions(p); root->addAppender(rfa); // // put stray file about locked file FileOutputStream os1(LOG4CXX_STR("output/manual-test5.1"), false); os1.close(p); FileOutputStream os0(LOG4CXX_STR("output/manual-test5.0"), false); common(rfa, p, logger); os0.close(p); if (File("output/manual-test5.3").exists(p)) { // // looks like platform where open files can be renamed // LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.3").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.log"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.0"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.1"), File("witness/rolling/sbr-test2.1"))); } else { // // rollover attempts should all fail // so initial log file should have all log content // open file should be unaffected // stray file should have only been moved one slot. LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.log"), File("witness/rolling/sbr-test4.log"))); } } }; LOGUNIT_TEST_SUITE_REGISTRATION(ManualRollingTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../util/compare.h" #include "../insertwide.h" #include "../logunit.h" #include <apr_time.h> #include <log4cxx/logmanager.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/patternlayout.h> #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/rolling/fixedwindowrollingpolicy.h> #include <log4cxx/rolling/filterbasedtriggeringpolicy.h> #include <log4cxx/filter/levelrangefilter.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/dailyrollingfileappender.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::xml; using namespace log4cxx::filter; using namespace log4cxx::helpers; /** * Tests the emulation of org.apache.log4j.DailyRollingFileAppender * * * */ LOGUNIT_CLASS(ObsoleteDailyRollingFileAppenderTest) { LOGUNIT_TEST_SUITE(ObsoleteDailyRollingFileAppenderTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST_SUITE_END(); public: void tearDown() { LogManager::shutdown(); } /** * Test basic rolling functionality. */ void test1() { PropertyConfigurator::configure(File("input/rolling/obsoleteDRFA1.properties")); int preCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test1.log.")); LoggerPtr logger(Logger::getLogger("org.apache.log4j.ObsoleteDailyRollingFileAppenderTest")); char msg[11]; strcpy(msg, "Hello---??"); for (int i = 0; i < 25; i++) { apr_sleep(100000); msg[8] = (char) ('0' + (i / 10)); msg[9] = (char) ('0' + (i % 10)); LOG4CXX_DEBUG(logger, msg); } int postCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test1.log.")); LOGUNIT_ASSERT_EQUAL(true, postCount > preCount); } /** * Test basic rolling functionality. * @deprecated Class under test is deprecated. */ void test2() { PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m%n"))); log4cxx::DailyRollingFileAppenderPtr rfa(new log4cxx::DailyRollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setLayout(layout); rfa->setAppend(false); rfa->setFile(LOG4CXX_STR("output/obsoleteDRFA-test2.log")); rfa->setDatePattern(LOG4CXX_STR("'.'yyyy-MM-dd-HH_mm_ss")); Pool p; rfa->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(rfa); LoggerPtr logger(Logger::getLogger("org.apache.log4j.ObsoleteDailyRollingAppenderTest")); int preCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test2.log.")); char msg[11]; strcpy(msg, "Hello---??"); for (int i = 0; i < 25; i++) { apr_sleep(100000); msg[8] = (char) ('0' + i / 10); msg[9] = (char) ('0' + i % 10); LOG4CXX_DEBUG(logger, msg); } int postCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test2.log.")); LOGUNIT_ASSERT_EQUAL(true, postCount > preCount); } private: static int getFileCount(const char* dir, const LogString& initial) { Pool p; std::vector<LogString> files(File(dir).list(p)); int count = 0; for (size_t i = 0; i < files.size(); i++) { if (StringHelper::startsWith(files[i], initial)) { count++; } } return count; } }; LOGUNIT_TEST_SUITE_REGISTRATION(ObsoleteDailyRollingFileAppenderTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/logger.h> #include <log4cxx/consoleappender.h> #include <log4cxx/logmanager.h> #include <log4cxx/patternlayout.h> #include <log4cxx/rolling/timebasedrollingpolicy.h> #include <log4cxx/helpers/simpledateformat.h> #include <iostream> #include <log4cxx/helpers/stringhelper.h> #include "../util/compare.h" #include "../logunit.h" #include <apr_strings.h> #ifndef INT64_C #define INT64_C(x) x ## LL #endif #include <apr_time.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::rolling; /** * A rather exhaustive set of tests. Tests include leaving the ActiveFileName * argument blank, or setting it, with and without compression, and tests * with or without stopping/restarting the RollingFileAppender. * * The regression tests log a few times using a RollingFileAppender. Then, * they predict the names of the files which sould be generated and compare * them with witness files. * * <pre> Compression ActiveFileName Stop/Restart Test1 NO BLANK NO Test2 NO BLANK YES Test3 YES BLANK NO Test4 NO SET YES Test5 NO SET NO Test6 YES SET NO * </pre> * */ LOGUNIT_CLASS(TimeBasedRollingTest) { LOGUNIT_TEST_SUITE(TimeBasedRollingTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST_SUITE_END(); static LoggerPtr logger; public: void setUp() { LoggerPtr root(Logger::getRootLogger()); root->addAppender( new ConsoleAppender(new PatternLayout( LOG4CXX_STR("%d{ABSOLUTE} [%t] %level %c{2}#%M:%L - %m%n")))); } void tearDown() { LogManager::shutdown(); } /** * Test rolling without compression, activeFileName left blank, no stop/start */ void test1() { PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%c{1} - %m%n"))); RollingFileAppenderPtr rfa(new RollingFileAppender()); rfa->setLayout(layout); LogString datePattern(LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss")); TimeBasedRollingPolicyPtr tbrp(new TimeBasedRollingPolicy()); tbrp->setFileNamePattern(LOG4CXX_STR("output/test1-%d{yyyy-MM-dd_HH_mm_ss}")); Pool p; tbrp->activateOptions(p); rfa->setRollingPolicy(tbrp); rfa->activateOptions(p); logger->addAppender(rfa); SimpleDateFormat sdf(datePattern); LogString filenames[4]; Pool pool; apr_time_t now = apr_time_now(); { for (int i = 0; i < 4; i++) { filenames[i] = LOG4CXX_STR("output/test1-"); sdf.format(filenames[i], now, p); now += APR_USEC_PER_SEC; } } std::cout << "Waiting until next second and 100 millis."; delayUntilNextSecond(100); std::cout << "Done waiting."; { for (int i = 0; i < 5; i++) { std::string message("Hello---"); message.append(pool.itoa(i)); LOG4CXX_DEBUG(logger, message); apr_sleep(APR_USEC_PER_SEC/2); } } for (int i = 0; i < 4; i++) { LogString witness(LOG4CXX_STR("witness/rolling/tbr-test1.")); StringHelper::toString(i, pool, witness); LOGUNIT_ASSERT(Compare::compare(filenames[i], File(witness))); } } /** * No compression, with stop/restart, activeFileName left blank */ void test2() { LogString datePattern(LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss")); PatternLayoutPtr layout1(new PatternLayout(LOG4CXX_STR("%c{1} - %m%n"))); RollingFileAppenderPtr rfa1(new RollingFileAppender()); rfa1->setLayout(layout1); TimeBasedRollingPolicyPtr tbrp1(new TimeBasedRollingPolicy()); tbrp1->setFileNamePattern(LOG4CXX_STR("output/test2-%d{yyyy-MM-dd_HH_mm_ss}")); Pool pool; tbrp1->activateOptions(pool); rfa1->setRollingPolicy(tbrp1); rfa1->activateOptions(pool); logger->addAppender(rfa1); SimpleDateFormat sdf(datePattern); LogString filenames[4]; apr_time_t now = apr_time_now(); { for (int i = 0; i < 4; i++) { filenames[i] = LOG4CXX_STR("output/test2-"); sdf.format(filenames[i], now, pool); now += APR_USEC_PER_SEC; } } delayUntilNextSecond(100); { for (int i = 0; i <= 2; i++) { std::string message("Hello---"); message.append(pool.itoa(i)); LOG4CXX_DEBUG(logger, message); apr_sleep(APR_USEC_PER_SEC/2); } } logger->removeAppender(rfa1); rfa1->close(); PatternLayoutPtr layout2(new PatternLayout(LOG4CXX_STR("%c{1} - %m%n"))); RollingFileAppenderPtr rfa2 = new RollingFileAppender(); rfa2->setLayout(layout2); TimeBasedRollingPolicyPtr tbrp2 = new TimeBasedRollingPolicy(); tbrp2->setFileNamePattern(LOG4CXX_STR("output/test2-%d{yyyy-MM-dd_HH_mm_ss}")); tbrp2->activateOptions(pool); rfa2->setRollingPolicy(tbrp2); rfa2->activateOptions(pool); logger->addAppender(rfa2); { for (int i = 3; i <= 4; i++) { std::string message("Hello---"); message.append(pool.itoa(i)); LOG4CXX_DEBUG(logger, message); apr_sleep(APR_USEC_PER_SEC/2); } } for (int i = 0; i < 4; i++) { LogString witness(LOG4CXX_STR("witness/rolling/tbr-test2.")); StringHelper::toString(i, pool, witness); LOGUNIT_ASSERT(Compare::compare(filenames[i], File(witness))); } } /** * With compression, activeFileName left blank, no stop/restart */ void test3() { Pool p; PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setAppend(false); rfa->setLayout(layout); LogString datePattern = LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss"); TimeBasedRollingPolicyPtr tbrp = new TimeBasedRollingPolicy(); tbrp->setFileNamePattern(LogString(LOG4CXX_STR("output/test3-%d{")) + datePattern + LogString(LOG4CXX_STR("}.gz"))); tbrp->activateOptions(p); rfa->setRollingPolicy(tbrp); rfa->activateOptions(p); logger->addAppender(rfa); DateFormatPtr sdf = new SimpleDateFormat(datePattern); LogString filenames[4]; apr_time_t now = apr_time_now(); { for (int i = 0; i < 4; i++) { filenames[i] = LOG4CXX_STR("output/test3-"); sdf->format(filenames[i], now, p); filenames[i].append(LOG4CXX_STR(".gz")); now += APR_USEC_PER_SEC; } } filenames[3].resize(filenames[3].size() - 3); delayUntilNextSecond(100); { for (int i = 0; i < 5; i++) { std::string message("Hello---"); message.append(p.itoa(i)); LOG4CXX_DEBUG(logger, message); apr_sleep(APR_USEC_PER_SEC/2); } } LOGUNIT_ASSERT_EQUAL(true, File(filenames[0]).exists(p)); LOGUNIT_ASSERT_EQUAL(true, File(filenames[1]).exists(p)); LOGUNIT_ASSERT_EQUAL(true, File(filenames[2]).exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File(filenames[3]), File(LOG4CXX_STR("witness/rolling/tbr-test3.3")))); } /** * Without compression, activeFileName set, with stop/restart */ void test4() { LogString datePattern = LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss"); PatternLayoutPtr layout1 = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n")); RollingFileAppenderPtr rfa1 = new RollingFileAppender(); rfa1->setLayout(layout1); Pool pool; TimeBasedRollingPolicyPtr tbrp1 = new TimeBasedRollingPolicy(); rfa1->setFile(LOG4CXX_STR("output/test4.log")); tbrp1->setFileNamePattern(LOG4CXX_STR("output/test4-%d{yyyy-MM-dd_HH_mm_ss}")); tbrp1->activateOptions(pool); rfa1->setRollingPolicy(tbrp1); rfa1->activateOptions(pool); logger->addAppender(rfa1); SimpleDateFormat sdf(datePattern); LogString filenames[4]; apr_time_t now = apr_time_now(); { for (int i = 0; i < 3; i++) { filenames[i] = LOG4CXX_STR("output/test4-"); sdf.format(filenames[i], now, pool); now += APR_USEC_PER_SEC; } } filenames[3] = LOG4CXX_STR("output/test4.log"); std::cout << "Waiting until next second and 100 millis."; delayUntilNextSecond(100); std::cout << "Done waiting."; { for (int i = 0; i <= 2; i++) { std::string message("Hello---"); message.append(pool.itoa(i)); LOG4CXX_DEBUG(logger, message); apr_sleep(APR_USEC_PER_SEC/2); } } logger->removeAppender(rfa1); rfa1->close(); PatternLayoutPtr layout2 = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n")); RollingFileAppenderPtr rfa2 = new RollingFileAppender(); rfa2->setLayout(layout2); TimeBasedRollingPolicyPtr tbrp2 = new TimeBasedRollingPolicy(); tbrp2->setFileNamePattern(LOG4CXX_STR("output/test4-%d{yyyy-MM-dd_HH_mm_ss}")); rfa2->setFile(LOG4CXX_STR("output/test4.log")); tbrp2->activateOptions(pool); rfa2->setRollingPolicy(tbrp2); rfa2->activateOptions(pool); logger->addAppender(rfa2); { for (int i = 3; i <= 4; i++) { std::string message("Hello---"); message.append(pool.itoa(i)); LOG4CXX_DEBUG(logger, message); apr_sleep(APR_USEC_PER_SEC/2); } } for (int i = 0; i < 4; i++) { LogString witness(LOG4CXX_STR("witness/rolling/tbr-test4.")); StringHelper::toString(i, pool, witness); LOGUNIT_ASSERT(Compare::compare(filenames[i], File(witness))); } } /** * No compression, activeFileName set, without stop/restart */ void test5() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setLayout(layout); LogString datePattern(LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss")); TimeBasedRollingPolicyPtr tbrp = new TimeBasedRollingPolicy(); tbrp->setFileNamePattern(LOG4CXX_STR("output/test5-%d{yyyy-MM-dd_HH_mm_ss}")); rfa->setFile(LOG4CXX_STR("output/test5.log")); Pool pool; tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); SimpleDateFormat sdf(datePattern); LogString filenames[4]; apr_time_t now = apr_time_now(); { for (int i = 0; i < 3; i++) { filenames[i] = LOG4CXX_STR("output/test5-"); sdf.format(filenames[i], now, pool); now += APR_USEC_PER_SEC; } } filenames[3] = LOG4CXX_STR("output/test5.log"); std::cout << "Waiting until next second and 100 millis."; delayUntilNextSecond(100); std::cout << "Done waiting."; { for (int i = 0; i < 5; i++) { std::string message("Hello---"); message.append(pool.itoa(i)); LOG4CXX_DEBUG(logger, message); apr_sleep(APR_USEC_PER_SEC/2); } } for (int i = 0; i < 4; i++) { LogString witness(LOG4CXX_STR("witness/rolling/tbr-test5.")); StringHelper::toString(i, pool, witness); LOGUNIT_ASSERT(Compare::compare(filenames[i], File(witness))); } } /** * With compression, activeFileName set, no stop/restart, */ void test6() { Pool p; PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%c{1} - %m%n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setAppend(false); rfa->setLayout(layout); LogString datePattern = LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss"); TimeBasedRollingPolicyPtr tbrp = new TimeBasedRollingPolicy(); tbrp->setFileNamePattern(LogString(LOG4CXX_STR("output/test6-%d{")) + datePattern + LogString(LOG4CXX_STR("}.gz"))); rfa->setFile(LOG4CXX_STR("output/test6.log")); tbrp->activateOptions(p); rfa->setRollingPolicy(tbrp); rfa->activateOptions(p); logger->addAppender(rfa); DateFormatPtr sdf = new SimpleDateFormat(datePattern); LogString filenames[4]; apr_time_t now = apr_time_now(); { for (int i = 0; i < 3; i++) { filenames[i] = LOG4CXX_STR("output/test6-"); sdf->format(filenames[i], now, p); filenames[i].append(LOG4CXX_STR(".gz")); now += APR_USEC_PER_SEC; } } filenames[3] = LOG4CXX_STR("output/test6.log"); delayUntilNextSecond(100); { for (int i = 0; i < 5; i++) { std::string message("Hello---"); message.append(p.itoa(i)); LOG4CXX_DEBUG(logger, message); apr_sleep(APR_USEC_PER_SEC/2); } } LOGUNIT_ASSERT_EQUAL(true, File(filenames[0]).exists(p)); LOGUNIT_ASSERT_EQUAL(true, File(filenames[1]).exists(p)); LOGUNIT_ASSERT_EQUAL(true, File(filenames[2]).exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File(filenames[3]), File(LOG4CXX_STR("witness/rolling/tbr-test6.3")))); } void delayUntilNextSecond(int millis) { apr_time_t now = apr_time_now(); apr_time_t next = ((now / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC + millis * 1000L; apr_sleep(next - now); } void delayUntilNextMinute(int seconds) { apr_time_t now = apr_time_now(); apr_time_t next = ((now / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC + seconds * 1000000L; apr_sleep(next - now); } }; LoggerPtr TimeBasedRollingTest::logger(Logger::getLogger("org.apache.log4j.TimeBasedRollingTest")); LOGUNIT_TEST_SUITE_REGISTRATION(TimeBasedRollingTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../util/compare.h" #include "../logunit.h" #include "../insertwide.h" #include <log4cxx/logmanager.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/patternlayout.h> #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/rolling/fixedwindowrollingpolicy.h> #include <log4cxx/rolling/filterbasedtriggeringpolicy.h> #include <log4cxx/filter/levelrangefilter.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/logger.h> using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::xml; using namespace log4cxx::filter; using namespace log4cxx::helpers; /** * * Tests of rolling file appender with a filter based triggering policy. * * * * */ LOGUNIT_CLASS(FilterBasedRollingTest) { LOGUNIT_TEST_SUITE(FilterBasedRollingTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST_SUITE_END(); public: void tearDown() { LogManager::getLoggerRepository()->resetConfiguration(); } /** * Test basic rolling functionality using configuration file. */ void test1() { DOMConfigurator::configure( "./input/rolling/filter1.xml" /*, LogManager::getLoggerRepository() */); common(LOG4CXX_STR("output/filterBased-test1")); } /** * Test basic rolling functionality using explicit configuration. * @remarks Test fails when run immediately after test1. */ void test2() { LayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setLayout(layout); FixedWindowRollingPolicyPtr swrp(new FixedWindowRollingPolicy()); FilterBasedTriggeringPolicyPtr fbtp(new FilterBasedTriggeringPolicy()); LevelRangeFilterPtr rf(new LevelRangeFilter()); rf->setLevelMin(Level::getInfo()); fbtp->addFilter(rf); Pool p; fbtp->activateOptions(p); swrp->setMinIndex(0); rfa->setFile(LOG4CXX_STR("output/filterBased-test2.log")); rfa->setAppend(false); swrp->setFileNamePattern(LOG4CXX_STR("output/filterBased-test2.%i")); swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(fbtp); rfa->activateOptions(p); Logger::getRootLogger()->addAppender(rfa); Logger::getRootLogger()->setLevel(Level::getDebug()); common(LOG4CXX_STR("output/filterBased-test2")); } private: /** * Common aspects of test1 and test2 */ void common(const LogString& baseName) { LoggerPtr logger(Logger::getLogger("org.apache.log4j.rolling.FilterBasedRollingTest")); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { char msg[10]; #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strcpy_s(msg, sizeof msg, "Hello---?"); #else strcpy(msg, "Hello---?"); #endif if (i < 10) { msg[8] = (char) ('0' + i); LOG4CXX_DEBUG(logger, msg); } else if (i < 100) { msg[7] = (char) ('0' + (i / 10)); msg[8] = (char) ('0' + (i % 10)); if ((i % 10) == 0) { LOG4CXX_WARN(logger, msg); } else { LOG4CXX_DEBUG(logger, msg); } } } // // test was constructed to mimic SizeBasedRollingTest.test2 // LOGUNIT_ASSERT_EQUAL(true, Compare::compare(baseName + LOG4CXX_STR(".log"), LogString(LOG4CXX_STR("witness/rolling/sbr-test2.log")))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(baseName + LOG4CXX_STR(".0"), LogString(LOG4CXX_STR("witness/rolling/sbr-test2.0")))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(baseName + LOG4CXX_STR(".1"), LogString(LOG4CXX_STR("witness/rolling/sbr-test2.1")))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(FilterBasedRollingTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../util/compare.h" #include "../insertwide.h" #include "../logunit.h" #include <apr_time.h> #include <log4cxx/logmanager.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/patternlayout.h> #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/rolling/fixedwindowrollingpolicy.h> #include <log4cxx/rolling/filterbasedtriggeringpolicy.h> #include <log4cxx/filter/levelrangefilter.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/rollingfileappender.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::xml; using namespace log4cxx::filter; using namespace log4cxx::helpers; /** * Tests the emulation of org.apache.log4j.RollingFileAppender * * * */ LOGUNIT_CLASS(ObsoleteRollingFileAppenderTest) { LOGUNIT_TEST_SUITE(ObsoleteRollingFileAppenderTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(testIsOptionHandler); LOGUNIT_TEST(testClassForName); LOGUNIT_TEST_SUITE_END(); public: void tearDown() { LogManager::shutdown(); } /** * Test basic rolling functionality. */ void test1() { PropertyConfigurator::configure(File("input/rolling/obsoleteRFA1.properties")); char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', '?', 0}; LoggerPtr logger(Logger::getLogger("org.apache.logj4.ObsoleteRollingFileAppenderTest")); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { apr_sleep(100000); if (i < 10) { msg[8] = (char) ('0' + i); LOG4CXX_DEBUG(logger, msg); } else if (i < 100) { msg[7] = (char) ('0' + i / 10); msg[8] = (char) ('0' + i % 10); LOG4CXX_DEBUG(logger, msg); } } Pool p; LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test1.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test1.log.1").exists(p)); } /** * Test basic rolling functionality. * @deprecated Class under test is deprecated. */ void test2() { PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m\n"))); log4cxx::RollingFileAppenderPtr rfa( new log4cxx::RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setLayout(layout); rfa->setOption(LOG4CXX_STR("append"), LOG4CXX_STR("false")); rfa->setMaximumFileSize(100); rfa->setFile(LOG4CXX_STR("output/obsoleteRFA-test2.log")); Pool p; rfa->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(rfa); char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', '?', 0}; LoggerPtr logger(Logger::getLogger("org.apache.logj4.ObsoleteRollingFileAppenderTest")); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { apr_sleep(100000); if (i < 10) { msg[8] = (char) ('0' + i); LOG4CXX_DEBUG(logger, msg); } else if (i < 100) { msg[7] = (char) ('0' + i / 10); msg[8] = (char) ('0' + i % 10); LOG4CXX_DEBUG(logger, msg); } } LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test2.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test2.log.1").exists(p)); } /** * Tests if class is declared to support the OptionHandler interface. * See LOGCXX-136. */ void testIsOptionHandler() { RollingFileAppenderPtr rfa(new RollingFileAppender()); LOGUNIT_ASSERT_EQUAL(true, rfa->instanceof(log4cxx::spi::OptionHandler::getStaticClass())); } void testClassForName() { LogString className(LOG4CXX_STR("org.apache.log4j.RollingFileAppender")); const Class& myclass = Class::forName(className); LOGUNIT_ASSERT_EQUAL(className, LogString(myclass.getName())); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ObsoleteRollingFileAppenderTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../util/compare.h" #include "../insertwide.h" #include "../logunit.h" #include <apr_time.h> #include <log4cxx/logmanager.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/patternlayout.h> #include <log4cxx/rolling/fixedwindowrollingpolicy.h> #include <log4cxx/rolling/sizebasedtriggeringpolicy.h> #include <log4cxx/filter/levelrangefilter.h> #include <log4cxx/helpers/pool.h> #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/rolling/rollingfileappender.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/consoleappender.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/fileoutputstream.h> using namespace log4cxx; using namespace log4cxx::xml; using namespace log4cxx::filter; using namespace log4cxx::helpers; using namespace log4cxx::rolling; /** * * Do not forget to call activateOptions when configuring programatically. * * * */ LOGUNIT_CLASS(SizeBasedRollingTest) { LOGUNIT_TEST_SUITE(SizeBasedRollingTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%d %level %c -%m%n"))); AppenderPtr ca(new ConsoleAppender(layout)); ca->setName(LOG4CXX_STR("CONSOLE")); root = Logger::getRootLogger(); root->addAppender(ca); logger = Logger::getLogger("org.apache.log4j.rolling.SizeBasedRollingTest"); } void tearDown() { LogManager::shutdown(); } void common(LoggerPtr& logger1, int /*sleep*/) { char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', 'N', 0 }; // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { msg[8] = '0' + i; } else if (i < 100) { msg[7] = '0' + i / 10; msg[8] = '0' + i % 10; } LOG4CXX_DEBUG(logger1, msg); } } /** * Tests that the lack of an explicit active file will use the * low index as the active file. * */ void test1() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy(); sbtp->setMaxFileSize(100); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/sizeBased-test1.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 0); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test1.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test1.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test1.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test1.0"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test1.1"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test1.2"), File("witness/rolling/sbr-test2.1"))); } /** * Test basic rolling functionality with explicit setting of FileAppender.file. */ void test2() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/sizeBased-test2.log")); FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy(); sbtp->setMaxFileSize(100); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/sizeBased-test2.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 0); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test2.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test2.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test2.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test2.log"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test2.0"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test2.1"), File("witness/rolling/sbr-test2.1"))); } /** * Same as testBasic but also with GZ compression. */ void test3() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr fwrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy(); sbtp->setMaxFileSize(100); fwrp->setMinIndex(0); rfa->setFile(LOG4CXX_STR("output/sbr-test3.log")); fwrp->setFileNamePattern(LOG4CXX_STR("output/sbr-test3.%i.gz")); Pool p; fwrp->activateOptions(p); rfa->setRollingPolicy(fwrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 100); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test3.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test3.0.gz").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test3.1.gz").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sbr-test3.log"), File("witness/rolling/sbr-test3.log"))); LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.0.gz").length(p), File("output/sbr-test3.0.gz").length(p)); LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.1.gz").length(p), File("output/sbr-test3.1.gz").length(p)); } /** * Test basic rolling functionality with bogus path in file name pattern. */ void test4() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/sizeBased-test4.log")); FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy(); sbtp->setMaxFileSize(100); swrp->setMinIndex(0); // // test4 directory should not exists. Should cause all rollover attempts to fail. // swrp->setFileNamePattern(LOG4CXX_STR("output/test4/sizeBased-test4.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 0); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test4.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test4.log"), File("witness/rolling/sbr-test4.log"))); } /** * Checking handling of rename failures due to other access * to the indexed files. */ void test5() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/sizeBased-test5.log")); FixedWindowRollingPolicyPtr swrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy(); sbtp->setMaxFileSize(100); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/sizeBased-test5.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); // // put stray file about locked file FileOutputStream os1(LOG4CXX_STR("output/sizeBased-test5.1"), false); os1.close(p); FileOutputStream os0(LOG4CXX_STR("output/sizeBased-test5.0"), false); common(logger, 0); os0.close(p); if (File("output/sizeBased-test5.3").exists(p)) { // // looks like platform where open files can be renamed // LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.3").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.log"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.0"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.1"), File("witness/rolling/sbr-test2.1"))); } else { // // rollover attempts should all fail // so initial log file should have all log content // open file should be unaffected // stray file should have only been moved one slot. LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.log"), File("witness/rolling/sbr-test4.log"))); } } /** * Same as testBasic but also with GZ compression. */ void test6() { PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m\n")); RollingFileAppenderPtr rfa = new RollingFileAppender(); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr fwrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicyPtr sbtp = new SizeBasedTriggeringPolicy(); sbtp->setMaxFileSize(100); fwrp->setMinIndex(0); rfa->setFile(LOG4CXX_STR("output/sbr-test6.log")); fwrp->setFileNamePattern(LOG4CXX_STR("output/sbr-test6.%i.zip")); Pool p; fwrp->activateOptions(p); rfa->setRollingPolicy(fwrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 100); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test6.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test6.0.zip").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test6.1.zip").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sbr-test6.log"), File("witness/rolling/sbr-test3.log"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SizeBasedRollingTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/properties.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/logmanager.h> #include "vectorappender.h" #include "logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(PropertyConfiguratorTest) { LOGUNIT_TEST_SUITE(PropertyConfiguratorTest); LOGUNIT_TEST(testInherited); LOGUNIT_TEST(testNull); LOGUNIT_TEST(testAppenderThreshold); LOGUNIT_TEST_SUITE_END(); public: void testInherited() { Properties props; props.put(LOG4CXX_STR("log4j.rootLogger"),LOG4CXX_STR("DEBUG,VECTOR1")); props.put(LOG4CXX_STR("log4j.logger.org.apache.log4j.PropertyConfiguratorTest"), LOG4CXX_STR("inherited,VECTOR2")); props.put(LOG4CXX_STR("log4j.appender.VECTOR1"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); props.put(LOG4CXX_STR("log4j.appender.VECTOR2"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); PropertyConfigurator::configure(props); LoggerPtr logger = Logger::getLogger("org.apache.log4j.PropertyConfiguratorTest"); LOGUNIT_ASSERT_EQUAL((int) Level::DEBUG_INT, logger->getEffectiveLevel()->toInt()); Logger::getRootLogger()->setLevel(Level::getError()); LOGUNIT_ASSERT_EQUAL((int) Level::ERROR_INT, logger->getEffectiveLevel()->toInt()); LogManager::resetConfiguration(); } void testNull() { Properties props; props.put(LOG4CXX_STR("log4j.rootLogger"),LOG4CXX_STR("DEBUG,VECTOR1")); props.put(LOG4CXX_STR("log4j.logger.org.apache.log4j.PropertyConfiguratorTest"), LOG4CXX_STR("NuLL,VECTOR2")); props.put(LOG4CXX_STR("log4j.appender.VECTOR1"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); props.put(LOG4CXX_STR("log4j.appender.VECTOR2"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); PropertyConfigurator::configure(props); LoggerPtr logger = Logger::getLogger("org.apache.log4j.PropertyConfiguratorTest"); LOGUNIT_ASSERT_EQUAL((int) Level::DEBUG_INT, logger->getEffectiveLevel()->toInt()); Logger::getRootLogger()->setLevel(Level::getError()); LOGUNIT_ASSERT_EQUAL((int) Level::ERROR_INT, logger->getEffectiveLevel()->toInt()); LogManager::resetConfiguration(); } void testAppenderThreshold() { Properties props; props.put(LOG4CXX_STR("log4j.rootLogger"), LOG4CXX_STR("ALL,VECTOR1")); props.put(LOG4CXX_STR("log4j.appender.VECTOR1"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); props.put(LOG4CXX_STR("log4j.appender.VECTOR1.threshold"), LOG4CXX_STR("WARN")); PropertyConfigurator::configure(props); LoggerPtr root(Logger::getRootLogger()); VectorAppenderPtr appender(root->getAppender(LOG4CXX_STR("VECTOR1"))); LOGUNIT_ASSERT_EQUAL((int) Level::WARN_INT, appender->getThreshold()->toInt()); LOG4CXX_INFO(root, "Info message"); LOG4CXX_WARN(root, "Warn message"); LOG4CXX_WARN(root, "Error message"); LOGUNIT_ASSERT_EQUAL((size_t) 2, appender->vector.size()); LogManager::resetConfiguration(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(PropertyConfiguratorTest);
C++
/* Copyright 2000-2004 Ryan Bloom * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Portions of this file were taken from testall.c in the APR test suite, * written by members of the Apache Software Foundation. */ #include "abts.h" #include "abts_tests.h" #include "testutil.h" #define ABTS_STAT_SIZE 6 static char status[ABTS_STAT_SIZE] = {'|', '/', '-', '|', '\\', '-'}; static int curr_char; static int verbose = 0; static int exclude = 0; static int quiet = 0; static int list_tests = 0; const char **testlist = NULL; // defined in logunit.cpp abts_suite* abts_run_suites(abts_suite*); static int find_test_name(const char *testname) { int i; for (i = 0; testlist[i] != NULL; i++) { if (!strcmp(testlist[i], testname)) { return 1; } } return 0; } /* Determine if the test should be run at all */ static int should_test_run(const char *testname) { int found = 0; if (list_tests == 1) { return 0; } if (testlist == NULL) { return 1; } found = find_test_name(testname); if ((found && !exclude) || (!found && exclude)) { return 1; } return 0; } static void reset_status(void) { curr_char = 0; } static void update_status(void) { if (!quiet) { curr_char = (curr_char + 1) % ABTS_STAT_SIZE; fprintf(stdout, "\b%c", status[curr_char]); fflush(stdout); } } static void end_suite(abts_suite *suite) { if (suite != NULL) { sub_suite *last = suite->tail; if (!quiet) { fprintf(stdout, "\b"); fflush(stdout); } if (last->failed == 0) { fprintf(stdout, "SUCCESS\n"); fflush(stdout); } else { fprintf(stdout, "FAILED %d of %d\n", last->failed, last->num_test); fflush(stdout); } } } abts_suite *abts_add_suite(abts_suite *suite, const char *suite_name_full) { sub_suite *subsuite; const char *p; const char *suite_name; curr_char = 0; /* Only end the suite if we actually ran it */ if (suite && suite->tail &&!suite->tail->not_run) { end_suite(suite); } subsuite = (sub_suite*) malloc(sizeof(*subsuite)); subsuite->num_test = 0; subsuite->failed = 0; subsuite->next = NULL; /* suite_name_full may be an absolute path depending on __FILE__ * expansion */ suite_name = strrchr(suite_name_full, '/'); if (suite_name) { suite_name++; } else { suite_name = suite_name_full; } p = strrchr(suite_name, '.'); if (p) { subsuite->name = (const char*) memcpy(calloc(p - suite_name + 1, 1), suite_name, p - suite_name); } else { subsuite->name = suite_name; } if (list_tests) { fprintf(stdout, "%s\n", subsuite->name); } subsuite->not_run = 0; if (suite == NULL) { suite = (abts_suite*) malloc(sizeof(*suite)); suite->head = subsuite; suite->tail = subsuite; } else { suite->tail->next = subsuite; suite->tail = subsuite; } if (!should_test_run(subsuite->name)) { subsuite->not_run = 1; return suite; } reset_status(); fprintf(stdout, "%-20s: ", subsuite->name); update_status(); fflush(stdout); return suite; } void abts_run_test(abts_suite *ts, test_func f, void *value) { abts_case tc; sub_suite *ss; if (!should_test_run(ts->tail->name)) { return; } ss = ts->tail; tc.failed = 0; tc.suite = ss; ss->num_test++; update_status(); f(&tc, value); if (tc.failed) { ss->failed++; } } static int report(abts_suite *suite) { int count = 0; sub_suite *dptr; if (suite && suite->tail &&!suite->tail->not_run) { end_suite(suite); } for (dptr = suite->head; dptr; dptr = dptr->next) { count += dptr->failed; } if (list_tests) { return 0; } if (count == 0) { printf("All tests passed.\n"); return 0; } dptr = suite->head; fprintf(stdout, "%-15s\t\tTotal\tFail\tFailed %%\n", "Failed Tests"); fprintf(stdout, "===================================================\n"); while (dptr != NULL) { if (dptr->failed != 0) { float percent = ((float)dptr->failed / (float)dptr->num_test); fprintf(stdout, "%-15s\t\t%5d\t%4d\t%6.2f%%\n", dptr->name, dptr->num_test, dptr->failed, percent * 100); } dptr = dptr->next; } return 1; } void abts_log_message(const char *fmt, ...) { va_list args; update_status(); if (verbose) { va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fprintf(stderr, "\n"); fflush(stderr); } } void abts_int_equal(abts_case *tc, const int expected, const int actual, int lineno) { update_status(); if (tc->failed) return; if (expected == actual) return; tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%d>, but saw <%d>\n", lineno, expected, actual); fflush(stderr); } } void abts_int_nequal(abts_case *tc, const int expected, const int actual, int lineno) { update_status(); if (tc->failed) return; if (expected != actual) return; tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%d>, but saw <%d>\n", lineno, expected, actual); fflush(stderr); } } void abts_size_equal(abts_case *tc, size_t expected, size_t actual, int lineno) { update_status(); if (tc->failed) return; if (expected == actual) return; tc->failed = TRUE; if (verbose) { /* Note that the comparison is type-exact, reporting must be a best-fit */ fprintf(stderr, "Line %d: expected %lu, but saw %lu\n", lineno, (unsigned long)expected, (unsigned long)actual); fflush(stderr); } } void abts_str_equal(abts_case *tc, const char *expected, const char *actual, int lineno) { update_status(); if (tc->failed) return; if (!expected && !actual) return; if (expected && actual) if (!strcmp(expected, actual)) return; tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%s>, but saw <%s>\n", lineno, expected, actual); fflush(stderr); } } void abts_str_nequal(abts_case *tc, const char *expected, const char *actual, size_t n, int lineno) { update_status(); if (tc->failed) return; if (!strncmp(expected, actual, n)) return; tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%s>, but saw <%s>\n", lineno, expected, actual); fflush(stderr); } } void abts_ptr_notnull(abts_case *tc, const void *ptr, int lineno) { update_status(); if (tc->failed) return; if (ptr != NULL) return; tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: Expected NULL, but saw <%p>\n", lineno, ptr); fflush(stderr); } } void abts_ptr_equal(abts_case *tc, const void *expected, const void *actual, int lineno) { update_status(); if (tc->failed) return; if (expected == actual) return; tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%p>, but saw <%p>\n", lineno, expected, actual); fflush(stderr); } } void abts_fail(abts_case *tc, const char *message, int lineno) { update_status(); if (tc->failed) return; tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: %s\n", lineno, message); fflush(stderr); } } void abts_assert(abts_case *tc, const char *message, int condition, int lineno) { update_status(); if (tc->failed) return; if (condition) return; tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: %s\n", lineno, message); fflush(stderr); } } void abts_true(abts_case *tc, int condition, int lineno) { update_status(); if (tc->failed) return; if (condition) return; tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: Condition is false, but expected true\n", lineno); fflush(stderr); } } void abts_not_impl(abts_case *tc, const char *message, int lineno) { update_status(); tc->suite->not_impl++; if (verbose) { fprintf(stderr, "Line %d: %s\n", lineno, message); fflush(stderr); } } int main(int argc, const char *const argv[]) { int i; int rv; int list_provided = 0; abts_suite *suite = NULL; initialize(); #if defined(_MSC_VER) quiet = 1; #else quiet = !isatty(STDOUT_FILENO); #endif for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-v")) { verbose = 1; continue; } if (!strcmp(argv[i], "-x")) { exclude = 1; continue; } if (!strcmp(argv[i], "-l")) { list_tests = 1; continue; } if (!strcmp(argv[i], "-q")) { quiet = 1; continue; } if (argv[i][0] == '-') { fprintf(stderr, "Invalid option: `%s'\n", argv[i]); exit(1); } list_provided = 1; } if (list_provided) { /* Waste a little space here, because it is easier than counting the * number of tests listed. Besides it is at most three char *. */ testlist = (const char**) calloc(argc + 1, sizeof(char *)); for (i = 1; i < argc; i++) { testlist[i - 1] = argv[i]; } } suite = abts_run_suites(suite); if (suite == 0) { fputs("No tests selected\n", stderr); } else { rv = report(suite); // // clean up suite // sub_suite* next; for(sub_suite* head = suite->head; head != NULL; head = next) { next = head->next; free((void*) head->name); free(head); } free(suite); } return rv; }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/pool.h> #include <log4cxx/fileappender.h> #include <log4cxx/patternlayout.h> #include "logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; /** * * FileAppender tests. */ LOGUNIT_CLASS(FileAppenderTest) { LOGUNIT_TEST_SUITE(FileAppenderTest); LOGUNIT_TEST(testDirectoryCreation); LOGUNIT_TEST(testgetSetThreshold); LOGUNIT_TEST(testIsAsSevereAsThreshold); LOGUNIT_TEST_SUITE_END(); public: /** * Tests that any necessary directories are attempted to * be created if they don't exist. See bug 9150. * */ void testDirectoryCreation() { File newFile(LOG4CXX_STR("output/newdir/temp.log")); Pool p; newFile.deleteFile(p); File newDir(LOG4CXX_STR("output/newdir")); newDir.deleteFile(p); FileAppenderPtr wa(new FileAppender()); wa->setFile(LOG4CXX_STR("output/newdir/temp.log")); wa->setLayout(new PatternLayout(LOG4CXX_STR("%m%n"))); wa->activateOptions(p); LOGUNIT_ASSERT(File(LOG4CXX_STR("output/newdir/temp.log")).exists(p)); } /** * Tests getThreshold and setThreshold. */ void testgetSetThreshold() { FileAppenderPtr appender = new FileAppender(); LevelPtr debug = Level::getDebug(); // // different from log4j where threshold is null. // LOGUNIT_ASSERT_EQUAL(Level::getAll(), appender->getThreshold()); appender->setThreshold(debug); LOGUNIT_ASSERT_EQUAL(debug, appender->getThreshold()); } /** * Tests isAsSevereAsThreshold. */ void testIsAsSevereAsThreshold() { FileAppenderPtr appender = new FileAppender(); LevelPtr debug = Level::getDebug(); LOGUNIT_ASSERT(appender->isAsSevereAsThreshold(debug)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(FileAppenderTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_WIN32) && !defined(_WIN32_WCE) #include <log4cxx/nt/nteventlogappender.h> #include "../appenderskeletontestcase.h" #include "windows.h" #include <log4cxx/logger.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/patternlayout.h> #include "../insertwide.h" #include "../logunit.h" #include <log4cxx/helpers/date.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::nt; using namespace log4cxx::spi; /** Unit tests of log4cxx::nt::NTEventLogAppender */ class NTEventLogAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(NTEventLogAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testHelloWorld); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::nt::NTEventLogAppender(); } void testHelloWorld() { DWORD expectedId = 1; HANDLE hEventLog = ::OpenEventLogW(NULL, L"log4cxx_test"); if (hEventLog != NULL) { BOOL stat = GetNumberOfEventLogRecords(hEventLog, &expectedId); DWORD oldest; if(stat) stat = GetOldestEventLogRecord(hEventLog, &oldest); CloseEventLog(hEventLog); LOGUNIT_ASSERT(stat); expectedId += oldest; } Pool p; Date now; DWORD expectedTime = now.getTime() / Date::getMicrosecondsPerSecond(); { NTEventLogAppenderPtr appender(new NTEventLogAppender()); appender->setSource(LOG4CXX_STR("log4cxx_test")); LayoutPtr layout(new PatternLayout(LOG4CXX_STR("%c - %m%n"))); appender->setLayout(layout); appender->activateOptions(p); LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); appender->doAppend(event, p); } hEventLog = ::OpenEventLogW(NULL, L"log4cxx_test"); LOGUNIT_ASSERT(hEventLog != NULL); DWORD actualId; BOOL stat = GetNumberOfEventLogRecords(hEventLog, &actualId); DWORD oldest; if (stat) stat = GetOldestEventLogRecord(hEventLog, &oldest); actualId += oldest; actualId--; CloseEventLog(hEventLog); LOGUNIT_ASSERT(stat); LOGUNIT_ASSERT_EQUAL(expectedId, actualId); } }; LOGUNIT_TEST_SUITE_REGISTRATION(NTEventLogAppenderTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/mdc.h> #include <log4cxx/patternlayout.h> #include <log4cxx/fileappender.h> #include "util/compare.h" #include "util/transformer.h" #include "util/absolutedateandtimefilter.h" #include "util/iso8601filter.h" #include "util/absolutetimefilter.h" #include "util/relativetimefilter.h" #include "util/controlfilter.h" #include "util/threadfilter.h" #include "util/linenumberfilter.h" #include "util/filenamefilter.h" #include <iostream> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/pool.h> #include <apr_strings.h> #include <log4cxx/helpers/pool.h> #include "testchar.h" #include "logunit.h" #include <log4cxx/spi/loggerrepository.h> #include <log4cxx/helpers/stringhelper.h> #define REGEX_STR(x) x #define PAT0 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]\\{1,2\\}") #define PAT1 ISO8601_PAT REGEX_STR(" ") PAT0 #define PAT2 ABSOLUTE_DATE_AND_TIME_PAT REGEX_STR(" ") PAT0 #define PAT3 ABSOLUTE_TIME_PAT REGEX_STR(" ") PAT0 #define PAT4 RELATIVE_TIME_PAT REGEX_STR(" ") PAT0 #define PAT5 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* : Message [0-9]\\{1,2\\}") #define PAT6 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) .*patternlayouttest.cpp\\([0-9]\\{1,4\\}\\): Message [0-9]\\{1,3\\}") #define PAT11a REGEX_STR("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[[0-9A-FXx]*]\\ log4j.PatternLayoutTest: Message [0-9]\\{1,2\\}") #define PAT11b REGEX_STR("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[[0-9A-FXx]*]\\ root: Message [0-9]\\{1,2\\}") #define PAT12 REGEX_STR("^\\[[0-9A-FXx]*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) ")\ REGEX_STR(".*patternlayouttest.cpp([0-9]\\{1,4\\}): ")\ REGEX_STR("Message [0-9]\\{1,2\\}") #define PAT_MDC_1 REGEX_STR("") using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(PatternLayoutTest) { LOGUNIT_TEST_SUITE(PatternLayoutTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST(test7); LOGUNIT_TEST(test8); LOGUNIT_TEST(test9); LOGUNIT_TEST(test10); LOGUNIT_TEST(test11); LOGUNIT_TEST(test12); LOGUNIT_TEST(testMDC1); LOGUNIT_TEST(testMDC2); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); MDC::clear(); logger = Logger::getLogger(LOG4CXX_TEST_STR("java.org.apache.log4j.PatternLayoutTest")); } void tearDown() { MDC::clear(); root->getLoggerRepository()->resetConfiguration(); } void test1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout1.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.1"))); } void test2() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout2.properties")); common(); ControlFilter filter1; filter1 << PAT1; ISO8601Filter filter2; ThreadFilter filter3; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.2"))); } void test3() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout3.properties")); common(); ControlFilter filter1; filter1 << PAT1; ISO8601Filter filter2; ThreadFilter filter3; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.3"))); } // Output format: // 06 avr. 2002 18:30:58,937 [12345] DEBUG atternLayoutTest - Message 0 void test4() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout4.properties")); common(); ControlFilter filter1; filter1 << PAT2; AbsoluteDateAndTimeFilter filter2; ThreadFilter filter3; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.4"))); } void test5() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout5.properties")); common(); ControlFilter filter1; filter1 << PAT2; AbsoluteDateAndTimeFilter filter2; ThreadFilter filter3; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.5"))); } void test6() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout6.properties")); common(); ControlFilter filter1; filter1 << PAT3; AbsoluteTimeFilter filter2; ThreadFilter filter3; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.6"))); } void test7() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout7.properties")); common(); ControlFilter filter1; filter1 << PAT3; AbsoluteTimeFilter filter2; ThreadFilter filter3; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.7"))); } void test8() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout8.properties")); common(); ControlFilter filter1; filter1 << PAT4; // // combo of relative time and thread identifier // (the \\\\1 preserve a leading space) Filter filter2(".*]", "[main]"); std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.8"))); } void test9() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout9.properties")); common(); ControlFilter filter1; filter1 << PAT5; ThreadFilter filter2; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.9"))); } void test10() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout10.properties")); common(); ControlFilter filter1; filter1 << PAT6; ThreadFilter filter2; LineNumberFilter filter3; FilenameFilter filenameFilter(__FILE__, "patternlayouttest.cpp"); std::vector<Filter *> filters; filters.push_back(&filenameFilter); filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.10"))); } void test11() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout11.properties")); common(); ControlFilter filter1; filter1 << PAT11a << PAT11b; ThreadFilter filter2; std::vector<Filter *> filters; filters.push_back(&filter1); filters.push_back(&filter2); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.11"))); } void test12() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout12.properties")); common(); ControlFilter filter1; filter1 << PAT12; ThreadFilter filter2; LineNumberFilter filter3; FilenameFilter filenameFilter(__FILE__, "patternlayouttest.cpp"); std::vector<Filter *> filters; filters.push_back(&filenameFilter); filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.12"))); } void testMDC1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout.mdc.1.properties")); MDC::put(LOG4CXX_TEST_STR("key1"), LOG4CXX_TEST_STR("va11")); MDC::put(LOG4CXX_TEST_STR("key2"), LOG4CXX_TEST_STR("va12")); logger->debug(LOG4CXX_TEST_STR("Hello World")); MDC::clear(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.mdc.1"))); } void testMDC2() { LogString OUTPUT_FILE = LOG4CXX_STR("output/patternLayout.mdc.2"); File WITNESS_FILE = LOG4CXX_FILE("witness/patternLayout.mdc.2"); LogString mdcMsgPattern1 = LOG4CXX_STR("%m : %X%n"); LogString mdcMsgPattern2 = LOG4CXX_STR("%m : %X{key1}%n"); LogString mdcMsgPattern3 = LOG4CXX_STR("%m : %X{key2}%n"); LogString mdcMsgPattern4 = LOG4CXX_STR("%m : %X{key3}%n"); LogString mdcMsgPattern5 = LOG4CXX_STR("%m : %X{key1},%X{key2},%X{key3}%n"); // set up appender PatternLayoutPtr layout = new PatternLayout(LOG4CXX_STR("%m%n")); AppenderPtr appender = new FileAppender(layout, OUTPUT_FILE, false); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); // output starting message root->debug(LOG4CXX_TEST_STR("starting mdc pattern test")); layout->setConversionPattern(mdcMsgPattern1); log4cxx::helpers::Pool pool; layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, no key specified in pattern")); layout->setConversionPattern(mdcMsgPattern2); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, key1 in pattern")); layout->setConversionPattern(mdcMsgPattern3); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, key2 in pattern")); layout->setConversionPattern(mdcMsgPattern4); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, key3 in pattern")); layout->setConversionPattern(mdcMsgPattern5); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, key1, key2, and key3 in pattern")); MDC::put(LOG4CXX_TEST_STR("key1"), LOG4CXX_TEST_STR("value1")); MDC::put(LOG4CXX_TEST_STR("key2"), LOG4CXX_TEST_STR("value2")); layout->setConversionPattern(mdcMsgPattern1); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, no key specified in pattern")); layout->setConversionPattern(mdcMsgPattern2); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, key1 in pattern")); layout->setConversionPattern(mdcMsgPattern3); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, key2 in pattern")); layout->setConversionPattern(mdcMsgPattern4); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, key3 in pattern")); layout->setConversionPattern(mdcMsgPattern5); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, key1, key2, and key3 in pattern")); MDC::remove(LOG4CXX_TEST_STR("key1")); MDC::remove(LOG4CXX_TEST_STR("key2")); layout->setConversionPattern(LOG4CXX_STR("%m%n")); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("finished mdc pattern test")); LOGUNIT_ASSERT(Compare::compare(OUTPUT_FILE, WITNESS_FILE)); } std::string createMessage(Pool& pool, int i) { std::string msg("Message "); msg.append(pool.itoa(i)); return msg; } void common() { int i = -1; Pool pool; LOG4CXX_DEBUG(logger, createMessage(pool, ++i)); LOG4CXX_DEBUG(root, createMessage(pool, i)); LOG4CXX_INFO(logger, createMessage(pool, ++i)); LOG4CXX_INFO(root, createMessage(pool, i)); LOG4CXX_WARN(logger, createMessage(pool, ++i)); LOG4CXX_WARN(root, createMessage(pool, i)); LOG4CXX_ERROR(logger, createMessage(pool, ++i)); LOG4CXX_ERROR(root, createMessage(pool, i)); LOG4CXX_FATAL(logger, createMessage(pool, ++i)); LOG4CXX_FATAL(root, createMessage(pool, i)); } private: static const LogString FILTERED; static const LogString TEMP; }; const LogString PatternLayoutTest::TEMP(LOG4CXX_STR("output/temp")); const LogString PatternLayoutTest::FILTERED(LOG4CXX_STR("output/filtered")); LOGUNIT_TEST_SUITE_REGISTRATION(PatternLayoutTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG4CXX_TEST 1 #include <log4cxx/private/log4cxx_private.h> #include "../logunit.h" #include <log4cxx/logger.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/consoleappender.h> #include <log4cxx/patternlayout.h> #include <log4cxx/file.h> #include "../util/compare.h" #include "xlevel.h" #include "../testchar.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; LOGUNIT_CLASS(CustomLevelTestCase) { LOGUNIT_TEST_SUITE(CustomLevelTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; static const File TEMP; public: void setUp() { root = Logger::getRootLogger(); logger = Logger::getLogger(LOG4CXX_TEST_STR("xml.CustomLevelTestCase")); } void tearDown() { root->getLoggerRepository()->resetConfiguration(); LoggerPtr logger1 = Logger::getLogger(LOG4CXX_TEST_STR("LOG4J")); logger1->setAdditivity(false); logger1->addAppender( new ConsoleAppender(new PatternLayout(LOG4CXX_STR("log4j: %-22c{2} - %m%n")))); } void test1() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel1.xml")); common(); const File witness("witness/customLevel.1"); LOGUNIT_ASSERT(Compare::compare(TEMP, witness)); } void test2() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel2.xml")); common(); const File witness("witness/customLevel.2"); LOGUNIT_ASSERT(Compare::compare(TEMP, witness)); } void test3() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel3.xml")); common(); const File witness("witness/customLevel.3"); LOGUNIT_ASSERT(Compare::compare(TEMP, witness)); } void test4() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel4.xml")); common(); const File witness("witness/customLevel.4"); LOGUNIT_ASSERT(Compare::compare(TEMP, witness)); } void common() { int i = 0; std::ostringstream os; os << "Message " << ++i; LOG4CXX_DEBUG(logger, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_INFO(logger, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_WARN(logger, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_ERROR(logger, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_LOG(logger, XLevel::getTrace(), os.str()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(CustomLevelTestCase); const File CustomLevelTestCase::TEMP("output/temp");
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../logunit.h" #include <log4cxx/logger.h> #include <log4cxx/xml/xmllayout.h> #include <log4cxx/fileappender.h> #include <log4cxx/mdc.h> #include "../util/transformer.h" #include "../util/compare.h" #include "../util/xmltimestampfilter.h" #include "../util/xmllineattributefilter.h" #include "../util/xmlthreadfilter.h" #include "../util/filenamefilter.h" #include <iostream> #include <log4cxx/helpers/stringhelper.h> #include "../testchar.h" #include <log4cxx/spi/loggerrepository.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; #if defined(__LOG4CXX_FUNC__) #undef __LOG4CXX_FUNC__ #define __LOG4CXX_FUNC__ "X::X()" #else #error __LOG4CXX_FUNC__ expected to be defined #endif class X { public: X() { LoggerPtr logger = Logger::getLogger(LOG4CXX_TEST_STR("org.apache.log4j.xml.XMLLayoutTestCase$X")); LOG4CXX_INFO(logger, LOG4CXX_TEST_STR("in X() constructor")); } }; LOGUNIT_CLASS(XMLLayoutTestCase) { LOGUNIT_TEST_SUITE(XMLLayoutTestCase); LOGUNIT_TEST(basic); LOGUNIT_TEST(locationInfo); LOGUNIT_TEST(testCDATA); LOGUNIT_TEST(testNull); LOGUNIT_TEST(testMDC); LOGUNIT_TEST(testMDCEscaped); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); root->setLevel(Level::getTrace()); logger = Logger::getLogger(LOG4CXX_TEST_STR("org.apache.log4j.xml.XMLLayoutTestCase")); logger->setLevel(Level::getTrace()); } void tearDown() { logger->getLoggerRepository()->resetConfiguration(); } void basic() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.1")); const File filteredFile("output/filtered.xmlLayout.1"); XMLLayoutPtr xmlLayout = new XMLLayout(); AppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); common(); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; std::vector<Filter *> filters; filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); try { Transformer::transform(tempFileName, filteredFile, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.1"))); } void locationInfo() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.2")); const File filteredFile("output/filtered.xmlLayout.2"); XMLLayoutPtr xmlLayout = new XMLLayout(); xmlLayout->setLocationInfo(true); root->addAppender(new FileAppender(xmlLayout, tempFileName, false)); common(); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; FilenameFilter xmlFilenameFilter(__FILE__, "XMLLayoutTestCase.java"); Filter line2XX("[23][0-9][0-9]", "X"); Filter line5X("5[0-9]", "X"); std::vector<Filter *> filters; filters.push_back(&xmlFilenameFilter); filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); filters.push_back(&line2XX); filters.push_back(&line5X); try { Transformer::transform(tempFileName, filteredFile, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.2"))); } #undef __LOG4CXX_FUNC__ #define __LOG4CXX_FUNC__ "void XMLLayoutTestCase::testCDATA()" void testCDATA() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.3")); const File filteredFile("output/filtered.xmlLayout.3"); XMLLayoutPtr xmlLayout = new XMLLayout(); xmlLayout->setLocationInfo(true); FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); LOG4CXX_TRACE(logger, LOG4CXX_TEST_STR("Message with embedded <![CDATA[<hello>hi</hello>]]>.")); LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("Message with embedded <![CDATA[<hello>hi</hello>]]>.")); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; FilenameFilter xmlFilenameFilter(__FILE__, "XMLLayoutTestCase.java"); Filter line1xx("1[0-9][0-9]", "X"); std::vector<Filter *> filters; filters.push_back(&xmlFilenameFilter); filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); filters.push_back(&line1xx); try { Transformer::transform(tempFileName, filteredFile, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.3"))); } void testNull() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.null")); const File filteredFile("output/filtered.xmlLayout.null"); XMLLayoutPtr xmlLayout = new XMLLayout(); FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("hi")); LOG4CXX_DEBUG(logger, (char*) 0); LOG4CXX_DEBUG(logger, "hi"); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; std::vector<Filter *> filters; filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); try { Transformer::transform(tempFileName, filteredFile, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.null"))); } void testMDC() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.mdc.1")); const File filteredFile("output/filtered.xmlLayout.mdc.1"); XMLLayoutPtr xmlLayout = new XMLLayout(); xmlLayout->setProperties(true); FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); MDC::clear(); MDC::put(LOG4CXX_TEST_STR("key1"), LOG4CXX_TEST_STR("val1")); MDC::put(LOG4CXX_TEST_STR("key2"), LOG4CXX_TEST_STR("val2")); LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("Hello")); MDC::clear(); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; std::vector<Filter *> filters; filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); try { Transformer::transform(tempFileName, filteredFile, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.mdc.1"))); } // not incuded in the tests for the moment ! void testMDCEscaped() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.mdc.2")); const File filteredFile("output/filtered.xmlLayout.mdc.2"); XMLLayoutPtr xmlLayout = new XMLLayout(); xmlLayout->setProperties(true); FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); MDC::clear(); MDC::put(LOG4CXX_TEST_STR("blahAttribute"), LOG4CXX_TEST_STR("<blah value='blah'>")); MDC::put(LOG4CXX_TEST_STR("<blahKey value='blah'/>"), LOG4CXX_TEST_STR("blahValue")); LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("Hello")); MDC::clear(); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; std::vector<Filter *> filters; filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); try { Transformer::transform(tempFileName, filteredFile, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.mdc.2"))); } #undef __LOG4CXX_FUNC__ #define __LOG4CXX_FUNC__ "void XMLLayoutTestCase::common()" void common() { int i = 0; X x; std::string msg("Message "); LOG4CXX_TRACE(logger, msg << i); LOG4CXX_TRACE(root, msg << i); i++; LOG4CXX_DEBUG(logger, msg << i); LOG4CXX_DEBUG(root, msg << i); i++; LOG4CXX_INFO(logger, msg << i); LOG4CXX_INFO(root, msg << i); i++; LOG4CXX_WARN(logger, msg << i); LOG4CXX_WARN(root, msg << i); i++; LOG4CXX_ERROR(logger, msg << i); LOG4CXX_ERROR(root, msg << i); i++; LOG4CXX_FATAL(logger, msg << i); LOG4CXX_FATAL(root, msg << i); i++; LOG4CXX_DEBUG(logger, "Message " << i); LOG4CXX_DEBUG(root, "Message " << i); i++; LOG4CXX_ERROR(logger, "Message " << i); LOG4CXX_ERROR(root, "Message " << i); } }; LOGUNIT_TEST_SUITE_REGISTRATION(XMLLayoutTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../logunit.h" #include <log4cxx/logger.h> #include <log4cxx/xml/xmllayout.h> #include <log4cxx/fileappender.h> #include <log4cxx/mdc.h> #include "../util/transformer.h" #include "../util/compare.h" #include "../util/xmltimestampfilter.h" #include "../util/xmllineattributefilter.h" #include "../util/xmlthreadfilter.h" #include "../util/filenamefilter.h" #include <iostream> #include <log4cxx/helpers/stringhelper.h> #include "../testchar.h" #include <log4cxx/spi/loggerrepository.h> #include <apr_xml.h> #include <log4cxx/ndc.h> #include <log4cxx/mdc.h> #include "../xml/xlevel.h" #include <log4cxx/helpers/bytebuffer.h> #include <log4cxx/helpers/transcoder.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; using namespace log4cxx::spi; #if defined(__LOG4CXX_FUNC__) #undef __LOG4CXX_FUNC__ #define __LOG4CXX_FUNC__ "X::X()" #else #error __LOG4CXX_FUNC__ expected to be defined #endif /** * Test for XMLLayout. * */ LOGUNIT_CLASS(XMLLayoutTest) { LOGUNIT_TEST_SUITE(XMLLayoutTest); LOGUNIT_TEST(testGetContentType); LOGUNIT_TEST(testIgnoresThrowable); LOGUNIT_TEST(testGetHeader); LOGUNIT_TEST(testGetFooter); LOGUNIT_TEST(testFormat); LOGUNIT_TEST(testFormatWithNDC); LOGUNIT_TEST(testGetSetLocationInfo); LOGUNIT_TEST(testActivateOptions); LOGUNIT_TEST(testProblemCharacters); LOGUNIT_TEST(testNDCWithCDATA); LOGUNIT_TEST_SUITE_END(); public: /** * Clear MDC and NDC before test. */ void setUp() { NDC::clear(); MDC::clear(); } /** * Clear MDC and NDC after test. */ void tearDown() { setUp(); } public: /** * Tests getContentType. */ void testGetContentType() { LogString expected(LOG4CXX_STR("text/plain")); LogString actual(XMLLayout().getContentType()); LOGUNIT_ASSERT(expected == actual); } /** * Tests ignoresThrowable. */ void testIgnoresThrowable() { LOGUNIT_ASSERT_EQUAL(false, XMLLayout().ignoresThrowable()); } /** * Tests getHeader. */ void testGetHeader() { Pool p; LogString header; XMLLayout().appendHeader(header, p); LOGUNIT_ASSERT_EQUAL((size_t) 0, header.size()); } /** * Tests getFooter. */ void testGetFooter() { Pool p; LogString footer; XMLLayout().appendFooter(footer, p); LOGUNIT_ASSERT_EQUAL((size_t) 0, footer.size()); } private: /** * Parses the string as the body of an XML document and returns the document element. * @param source source string. * @return document element. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ static apr_xml_elem* parse(const LogString& source, Pool& p) { char backing[3000]; ByteBuffer buf(backing, sizeof(backing)); CharsetEncoderPtr encoder(CharsetEncoder::getUTF8Encoder()); LogString header(LOG4CXX_STR("<log4j:eventSet xmlns:log4j='http://jakarta.apache.org/log4j/'>")); LogString::const_iterator iter(header.begin()); encoder->encode(header, iter, buf); LOGUNIT_ASSERT(iter == header.end()); iter = source.begin(); encoder->encode(source, iter, buf); LOGUNIT_ASSERT(iter == source.end()); LogString footer(LOG4CXX_STR("</log4j:eventSet>")); iter = footer.begin(); encoder->encode(footer, iter, buf); buf.flip(); apr_pool_t* apr_pool = p.getAPRPool(); apr_xml_parser* parser = apr_xml_parser_create(apr_pool); LOGUNIT_ASSERT(parser != 0); apr_status_t stat = apr_xml_parser_feed(parser, buf.data(), buf.remaining()); LOGUNIT_ASSERT(stat == APR_SUCCESS); apr_xml_doc* doc = 0; stat = apr_xml_parser_done(parser, &doc); LOGUNIT_ASSERT(doc != 0); apr_xml_elem* eventSet = doc->root; LOGUNIT_ASSERT(eventSet != 0); apr_xml_elem* event = eventSet->first_child; LOGUNIT_ASSERT(event != 0); return event; } std::string getAttribute(apr_xml_elem* elem, const char* attrName) { for(apr_xml_attr* attr = elem->attr; attr != NULL; attr = attr->next) { if (strcmp(attr->name, attrName) == 0) { return attr->value; } } return ""; } std::string getText(apr_xml_elem* elem) { std::string dMessage; for(apr_text* t = elem->first_cdata.first; t != NULL; t = t->next) { dMessage.append(t->text); } return dMessage; } /** * Checks a log4j:event element against expectations. * @param element element, may not be null. * @param event event, may not be null. */ void checkEventElement( apr_xml_elem* element, LoggingEventPtr& event) { std::string tagName("event"); LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name); LOG4CXX_ENCODE_CHAR(cLoggerName, event->getLoggerName()); LOGUNIT_ASSERT_EQUAL(cLoggerName, getAttribute(element, "logger")); LOG4CXX_ENCODE_CHAR(cLevelName, event->getLevel()->toString()); LOGUNIT_ASSERT_EQUAL(cLevelName, getAttribute(element, "level")); } /** * Checks a log4j:message element against expectations. * @param element element, may not be null. * @param message expected message. */ void checkMessageElement( apr_xml_elem* element, std::string message) { std::string tagName = "message"; LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name); LOGUNIT_ASSERT_EQUAL(message, getText(element)); } /** * Checks a log4j:message element against expectations. * @param element element, may not be null. * @param message expected message. */ void checkNDCElement(apr_xml_elem* element, std::string message) { std::string tagName = "NDC"; LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name); std::string dMessage = getText(element); LOGUNIT_ASSERT_EQUAL(message, dMessage); } /** * Checks a log4j:properties element against expectations. * @param element element, may not be null. * @param key key. * @param value value. */ void checkPropertiesElement( apr_xml_elem* element, std::string key, std::string value) { std::string tagName = "properties"; std::string dataTag = "data"; int childNodeCount = 0; LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name); for(apr_xml_elem* child = element->first_child; child != NULL; child = child->next) { LOGUNIT_ASSERT_EQUAL(dataTag, (std::string) child->name); LOGUNIT_ASSERT_EQUAL(key, getAttribute(child, "name")); LOGUNIT_ASSERT_EQUAL(value, getAttribute(child, "value")); childNodeCount++; } LOGUNIT_ASSERT_EQUAL(1, childNodeCount); } public: /** * Tests formatted results. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ void testFormat() { LogString logger = LOG4CXX_STR("org.apache.log4j.xml.XMLLayoutTest"); LoggingEventPtr event = new LoggingEvent( logger, Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION); Pool p; XMLLayout layout; LogString result; layout.format(result, event, p); apr_xml_elem* parsedResult = parse(result, p); checkEventElement(parsedResult, event); int childElementCount = 0; for ( apr_xml_elem* node = parsedResult->first_child; node != NULL; node = node->next) { childElementCount++; checkMessageElement(node, "Hello, World"); } LOGUNIT_ASSERT_EQUAL(1, childElementCount); } /** * Tests formatted results with an exception. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ void testFormatWithNDC() { LogString logger = LOG4CXX_STR("org.apache.log4j.xml.XMLLayoutTest"); NDC::push("NDC goes here"); LoggingEventPtr event = new LoggingEvent( logger, Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION); Pool p; XMLLayout layout; LogString result; layout.format(result, event, p); NDC::pop(); apr_xml_elem* parsedResult = parse(result, p); checkEventElement(parsedResult, event); int childElementCount = 0; for ( apr_xml_elem* node = parsedResult->first_child; node != NULL; node = node->next) { childElementCount++; if (childElementCount == 1) { checkMessageElement(node, "Hello, World"); } else { checkNDCElement(node, "NDC goes here"); } } LOGUNIT_ASSERT_EQUAL(2, childElementCount); } /** * Tests getLocationInfo and setLocationInfo. */ void testGetSetLocationInfo() { XMLLayout layout; LOGUNIT_ASSERT_EQUAL(false, layout.getLocationInfo()); layout.setLocationInfo(true); LOGUNIT_ASSERT_EQUAL(true, layout.getLocationInfo()); layout.setLocationInfo(false); LOGUNIT_ASSERT_EQUAL(false, layout.getLocationInfo()); } /** * Tests activateOptions(). */ void testActivateOptions() { Pool p; XMLLayout layout; layout.activateOptions(p); } /** * Tests problematic characters in multiple fields. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ void testProblemCharacters() { std::string problemName = "com.example.bar<>&\"'"; LogString problemNameLS = LOG4CXX_STR("com.example.bar<>&\"'"); LevelPtr level = new XLevel(6000, problemNameLS, 7); NDC::push(problemName); MDC::clear(); MDC::put(problemName, problemName); LoggingEventPtr event = new LoggingEvent(problemNameLS, level, problemNameLS, LOG4CXX_LOCATION); XMLLayout layout; layout.setProperties(true); Pool p; LogString result; layout.format(result, event, p); MDC::clear(); apr_xml_elem* parsedResult = parse(result, p); checkEventElement(parsedResult, event); int childElementCount = 0; for ( apr_xml_elem* node = parsedResult->first_child; node != NULL; node = node->next) { childElementCount++; switch(childElementCount) { case 1: checkMessageElement(node, problemName); break; case 2: checkNDCElement(node, problemName); break; case 3: checkPropertiesElement(node, problemName.c_str(), problemName.c_str()); break; default: break; } } LOGUNIT_ASSERT_EQUAL(3, childElementCount); } /** * Tests CDATA element within NDC content. See bug 37560. */ void testNDCWithCDATA() { LogString logger = LOG4CXX_STR("com.example.bar"); LevelPtr level = Level::getInfo(); std::string ndcMessage ="<envelope><faultstring><![CDATA[The EffectiveDate]]></faultstring><envelope>"; NDC::push(ndcMessage); LoggingEventPtr event = new LoggingEvent( logger, level, LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION); XMLLayout layout; Pool p; LogString result; layout.format(result, event, p); NDC::clear(); apr_xml_elem* parsedResult = parse(result, p); int ndcCount = 0; for(apr_xml_elem* node = parsedResult->first_child; node != NULL; node = node->next) { if (strcmp(node->name, "NDC") == 0) { ndcCount++; LOGUNIT_ASSERT_EQUAL(ndcMessage, getText(node)); } } LOGUNIT_ASSERT_EQUAL(1, ndcCount); } }; LOGUNIT_TEST_SUITE_REGISTRATION(XMLLayoutTest);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xlevel.h" #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_LEVEL(XLevel) XLevel::XLevel(int level1, const LogString& name1, int syslogEquivalent1) : Level(level1, name1, syslogEquivalent1) { } LevelPtr XLevel::getTrace() { static const LevelPtr trace(new XLevel(XLevel::TRACE_INT, LOG4CXX_STR("TRACE"), 7)); return trace; } LevelPtr XLevel::getLethal() { static const LevelPtr lethal(new XLevel(XLevel::LETHAL_INT, LOG4CXX_STR("LETHAL"), 0)); return lethal; } LevelPtr XLevel::toLevelLS(const LogString& sArg) { return toLevelLS(sArg, getTrace()); } LevelPtr XLevel::toLevel(int val) { return toLevel(val, getTrace()); } LevelPtr XLevel::toLevel(int val, const LevelPtr& defaultLevel) { switch(val) { case TRACE_INT: return getTrace(); case LETHAL_INT: return getLethal(); default: return defaultLevel; } } LevelPtr XLevel::toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel) { if (sArg.empty()) { return defaultLevel; } if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("TRACE"), LOG4CXX_STR("trace"))) { return getTrace(); } if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("LETHAL"), LOG4CXX_STR("lethal"))) { return getLethal(); } return Level::toLevel(sArg, defaultLevel); }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include <log4cxx/xml/domconfigurator.h> #include "../logunit.h" #include "../util/compare.h" #include "xlevel.h" #include "../util/controlfilter.h" #include "../util/iso8601filter.h" #include "../util/threadfilter.h" #include "../util/transformer.h" #include <iostream> #include <log4cxx/file.h> #include <log4cxx/fileappender.h> #include <apr_pools.h> #include <apr_file_io.h> #include "../testchar.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; #define TEST1_1A_PAT \ "(DEBUG|INFO |WARN |ERROR|FATAL) \\w*\\.\\w* - Message [0-9]" #define TEST1_1B_PAT "(DEBUG|INFO |WARN |ERROR|FATAL) root - Message [0-9]" #define TEST1_2_PAT "^[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\},[0-9]\\{3\\} " \ "\\[0x[0-9A-F]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]" LOGUNIT_CLASS(DOMTestCase) { LOGUNIT_TEST_SUITE(DOMTestCase); LOGUNIT_TEST(test1); #if defined(_WIN32) LOGUNIT_TEST(test2); #endif LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; static const File TEMP_A1; static const File TEMP_A2; static const File FILTERED_A1; static const File FILTERED_A2; static const File TEMP_A1_2; static const File TEMP_A2_2; static const File FILTERED_A1_2; static const File FILTERED_A2_2; public: void setUp() { root = Logger::getRootLogger(); logger = Logger::getLogger(LOG4CXX_TEST_STR("org.apache.log4j.xml.DOMTestCase")); } void tearDown() { root->getLoggerRepository()->resetConfiguration(); } void test1() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/DOMTestCase1.xml")); common(); ControlFilter cf1; cf1 << TEST1_1A_PAT << TEST1_1B_PAT; ControlFilter cf2; cf2 << TEST1_2_PAT; ThreadFilter threadFilter; ISO8601Filter iso8601Filter; std::vector<Filter *> filters1; filters1.push_back(&cf1); std::vector<Filter *> filters2; filters2.push_back(&cf2); filters2.push_back(&threadFilter); filters2.push_back(&iso8601Filter); try { Transformer::transform(TEMP_A1, FILTERED_A1, filters1); Transformer::transform(TEMP_A2, FILTERED_A2, filters2); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } const File witness1(LOG4CXX_TEST_STR("witness/dom.A1.1")); const File witness2(LOG4CXX_TEST_STR("witness/dom.A2.1")); // TODO: A1 doesn't contain duplicate entries // // LOGUNIT_ASSERT(Compare::compare(FILTERED_A1, witness1)); LOGUNIT_ASSERT(Compare::compare(FILTERED_A2, witness2)); } // // Same test but backslashes instead of forward // void test2() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input\\xml\\DOMTestCase2.xml")); common(); ThreadFilter threadFilter; ISO8601Filter iso8601Filter; std::vector<Filter *> filters1; std::vector<Filter *> filters2; filters2.push_back(&threadFilter); filters2.push_back(&iso8601Filter); try { Transformer::transform(TEMP_A1_2, FILTERED_A1_2, filters1); Transformer::transform(TEMP_A2_2, FILTERED_A2_2, filters2); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } const File witness1(LOG4CXX_TEST_STR("witness/dom.A1.2")); const File witness2(LOG4CXX_TEST_STR("witness/dom.A2.2")); // TODO: A1 doesn't contain duplicate entries // // LOGUNIT_ASSERT(Compare::compare(FILTERED_A1, witness1)); LOGUNIT_ASSERT(Compare::compare(FILTERED_A2, witness2)); } void common() { int i = 0; LOG4CXX_DEBUG(logger, "Message " << i); LOG4CXX_DEBUG(root, "Message " << i); i++; LOG4CXX_INFO(logger, "Message " << i); LOG4CXX_INFO(root, "Message " << i); i++; LOG4CXX_WARN(logger, "Message " << i); LOG4CXX_WARN(root, "Message " << i); i++; LOG4CXX_ERROR(logger, "Message " << i); LOG4CXX_ERROR(root, "Message " << i); i++; LOG4CXX_FATAL(logger, "Message " << i); LOG4CXX_FATAL(root, "Message " << i); } /** * Creates a output file that ends with a superscript 3. * Output file is checked by build.xml after completion. */ void test3() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/DOMTestCase3.xml")); LOG4CXX_INFO(logger, "File name is expected to end with a superscript 3"); #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, 0xC2, 0xB3, 0 }; #else const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, 0xB3, 0 }; #endif File file; file.setPath(fname); Pool p; bool exists = file.exists(p); LOGUNIT_ASSERT(exists); } /** * Creates a output file that ends with a ideographic 4. * Output file is checked by build.xml after completion. */ void test4() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/DOMTestCase4.xml")); LOG4CXX_INFO(logger, "File name is expected to end with an ideographic 4"); #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, 0xE3, 0x86, 0x95, 0 }; #else const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, 0x3195, 0 }; #endif File file; file.setPath(fname); Pool p; bool exists = file.exists(p); LOGUNIT_ASSERT(exists); } }; LOGUNIT_TEST_SUITE_REGISTRATION(DOMTestCase); const File DOMTestCase::TEMP_A1(LOG4CXX_TEST_STR("output/temp.A1")); const File DOMTestCase::TEMP_A2(LOG4CXX_TEST_STR("output/temp.A2")); const File DOMTestCase::FILTERED_A1(LOG4CXX_TEST_STR("output/filtered.A1")); const File DOMTestCase::FILTERED_A2(LOG4CXX_TEST_STR("output/filtered.A2")); const File DOMTestCase::TEMP_A1_2(LOG4CXX_TEST_STR("output/temp.A1.2")); const File DOMTestCase::TEMP_A2_2(LOG4CXX_TEST_STR("output/temp.A2.2")); const File DOMTestCase::FILTERED_A1_2(LOG4CXX_TEST_STR("output/filtered.A1.2")); const File DOMTestCase::FILTERED_A2_2(LOG4CXX_TEST_STR("output/filtered.A2.2"));
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/level.h> namespace log4cxx { class XLevel : public Level { DECLARE_LOG4CXX_LEVEL(XLevel) public: enum { TRACE_INT = Level::DEBUG_INT - 1, LETHAL_INT = Level::FATAL_INT + 1 }; static LevelPtr getTrace(); static LevelPtr getLethal(); XLevel(int level, const LogString& name, int syslogEquivalent); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns #DEBUG. */ static LevelPtr toLevelLS(const LogString& sArg); /** Convert an integer passed as argument to a level. If the conversion fails, then this method returns #DEBUG. */ static LevelPtr toLevel(int val); /** Convert an integer passed as argument to a level. If the conversion fails, then this method returns the specified default. */ static LevelPtr toLevel(int val, const LevelPtr& defaultLevel); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns the value of <code>defaultLevel</code>. */ static LevelPtr toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel); }; }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/level.h> #include "testchar.h" #include "logunit.h" #if LOG4CXX_CFSTRING_API #include <CoreFoundation/CFString.h> #endif using namespace log4cxx; LOGUNIT_CLASS(LevelTestCase) { LOGUNIT_TEST_SUITE(LevelTestCase); LOGUNIT_TEST(testToLevelFatal); LOGUNIT_TEST(testTraceInt); LOGUNIT_TEST(testTrace); LOGUNIT_TEST(testIntToTrace); LOGUNIT_TEST(testStringToTrace); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(testWideStringToTrace); #endif #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(testUniCharStringToTrace); #endif #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(testCFStringToTrace); #endif LOGUNIT_TEST_SUITE_END(); public: void testToLevelFatal() { LevelPtr level(Level::toLevel(LOG4CXX_TEST_STR("fATal"))); LOGUNIT_ASSERT_EQUAL((int) Level::FATAL_INT, level->toInt()); } /** * Tests Level::TRACE_INT. */ void testTraceInt() { LOGUNIT_ASSERT_EQUAL(5000, (int) Level::TRACE_INT); } /** * Tests Level.TRACE. */ void testTrace() { LOGUNIT_ASSERT(Level::getTrace()->toString() == LOG4CXX_STR("TRACE")); LOGUNIT_ASSERT_EQUAL(5000, Level::getTrace()->toInt()); LOGUNIT_ASSERT_EQUAL(7, Level::getTrace()->getSyslogEquivalent()); } /** * Tests Level.toLevel(Level.TRACE_INT). */ void testIntToTrace() { LevelPtr trace(Level::toLevel(5000)); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } /** * Tests Level.toLevel("TRACE"); */ void testStringToTrace() { LevelPtr trace(Level::toLevel("TRACE")); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } #if LOG4CXX_WCHAR_T_API /** * Tests Level.toLevel(L"TRACE"); */ void testWideStringToTrace() { LevelPtr trace(Level::toLevel(L"TRACE")); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } #endif #if LOG4CXX_UNICHAR_API /** * Tests Level.toLevel("TRACE"); */ void testUniCharStringToTrace() { const log4cxx::UniChar name[] = { 'T', 'R', 'A', 'C', 'E', 0 }; LevelPtr trace(Level::toLevel(name)); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } #endif #if LOG4CXX_CFSTRING_API /** * Tests Level.toLevel(CFSTR("TRACE")); */ void testCFStringToTrace() { LevelPtr trace(Level::toLevel(CFSTR("TRACE"))); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(LevelTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "logunit.h" #include <log4cxx/logger.h> #include <log4cxx/logmanager.h> #include <log4cxx/simplelayout.h> #include "vectorappender.h" #include <log4cxx/asyncappender.h> #include "appenderskeletontestcase.h" #include <log4cxx/helpers/pool.h> #include <apr_strings.h> #include "testchar.h" #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/synchronized.h> #include <log4cxx/spi/location/locationinfo.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/file.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; class NullPointerAppender : public AppenderSkeleton { public: NullPointerAppender() { } /** * @{inheritDoc} */ void append(const spi::LoggingEventPtr&, log4cxx::helpers::Pool&) { throw NullPointerException(LOG4CXX_STR("Intentional NullPointerException")); } void close() { } bool requiresLayout() const { return false; } }; /** * Vector appender that can be explicitly blocked. */ class BlockableVectorAppender : public VectorAppender { private: Mutex blocker; public: /** * Create new instance. */ BlockableVectorAppender() : blocker(pool) { } /** * {@inheritDoc} */ void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) { synchronized sync(blocker); VectorAppender::append(event, p); // // if fatal, echo messages for testLoggingInDispatcher // if (event->getLevel() == Level::getInfo()) { LoggerPtr logger = Logger::getLoggerLS(event->getLoggerName()); LOG4CXX_LOGLS(logger, Level::getError(), event->getMessage()); LOG4CXX_LOGLS(logger, Level::getWarn(), event->getMessage()); LOG4CXX_LOGLS(logger, Level::getInfo(), event->getMessage()); LOG4CXX_LOGLS(logger, Level::getDebug(), event->getMessage()); } } Mutex& getBlocker() { return blocker; } }; typedef helpers::ObjectPtrT<BlockableVectorAppender> BlockableVectorAppenderPtr; #if APR_HAS_THREADS /** * Tests of AsyncAppender. */ class AsyncAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(AsyncAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(closeTest); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); // // TODO: test fails on Linux. //LOGUNIT_TEST(testBadAppender); LOGUNIT_TEST(testLocationInfoTrue); LOGUNIT_TEST(testConfiguration); LOGUNIT_TEST_SUITE_END(); public: void setUp() { AppenderSkeletonTestCase::setUp(); } void tearDown() { LogManager::shutdown(); AppenderSkeletonTestCase::tearDown(); } AppenderSkeleton* createAppenderSkeleton() const { return new AsyncAppender(); } // this test checks whether it is possible to write to a closed AsyncAppender void closeTest() { LoggerPtr root = Logger::getRootLogger(); LayoutPtr layout = new SimpleLayout(); VectorAppenderPtr vectorAppender = new VectorAppender(); AsyncAppenderPtr asyncAppender = new AsyncAppender(); asyncAppender->setName(LOG4CXX_STR("async-CloseTest")); asyncAppender->addAppender(vectorAppender); root->addAppender(asyncAppender); root->debug(LOG4CXX_TEST_STR("m1")); asyncAppender->close(); root->debug(LOG4CXX_TEST_STR("m2")); const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL((size_t) 1, v.size()); } // this test checks whether appenders embedded within an AsyncAppender are also // closed void test2() { LoggerPtr root = Logger::getRootLogger(); LayoutPtr layout = new SimpleLayout(); VectorAppenderPtr vectorAppender = new VectorAppender(); AsyncAppenderPtr asyncAppender = new AsyncAppender(); asyncAppender->setName(LOG4CXX_STR("async-test2")); asyncAppender->addAppender(vectorAppender); root->addAppender(asyncAppender); root->debug(LOG4CXX_TEST_STR("m1")); asyncAppender->close(); root->debug(LOG4CXX_TEST_STR("m2")); const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL((size_t) 1, v.size()); LOGUNIT_ASSERT(vectorAppender->isClosed()); } // this test checks whether appenders embedded within an AsyncAppender are also // closed void test3() { size_t LEN = 200; LoggerPtr root = Logger::getRootLogger(); VectorAppenderPtr vectorAppender = new VectorAppender(); AsyncAppenderPtr asyncAppender = new AsyncAppender(); asyncAppender->setName(LOG4CXX_STR("async-test3")); asyncAppender->addAppender(vectorAppender); root->addAppender(asyncAppender); for (size_t i = 0; i < LEN; i++) { LOG4CXX_DEBUG(root, "message" << i); } asyncAppender->close(); root->debug(LOG4CXX_TEST_STR("m2")); const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL(LEN, v.size()); LOGUNIT_ASSERT_EQUAL(true, vectorAppender->isClosed()); } /** * Tests that a bad appender will switch async back to sync. */ void testBadAppender() { AppenderPtr nullPointerAppender = new NullPointerAppender(); AsyncAppenderPtr asyncAppender = new AsyncAppender(); asyncAppender->addAppender(nullPointerAppender); asyncAppender->setBufferSize(5); Pool p; asyncAppender->activateOptions(p); LoggerPtr root = Logger::getRootLogger(); root->addAppender(asyncAppender); LOG4CXX_INFO(root, "Message"); Thread::sleep(10); try { LOG4CXX_INFO(root, "Message"); LOGUNIT_FAIL("Should have thrown exception"); } catch(NullPointerException& ex) { } } /** * Tests non-blocking behavior. */ void testLocationInfoTrue() { BlockableVectorAppenderPtr blockableAppender = new BlockableVectorAppender(); AsyncAppenderPtr async = new AsyncAppender(); async->addAppender(blockableAppender); async->setBufferSize(5); async->setLocationInfo(true); async->setBlocking(false); Pool p; async->activateOptions(p); LoggerPtr rootLogger = Logger::getRootLogger(); rootLogger->addAppender(async); { synchronized sync(blockableAppender->getBlocker()); for (int i = 0; i < 100; i++) { LOG4CXX_INFO(rootLogger, "Hello, World"); Thread::sleep(1); } LOG4CXX_ERROR(rootLogger, "That's all folks."); } async->close(); const std::vector<spi::LoggingEventPtr>& events = blockableAppender->getVector(); LOGUNIT_ASSERT(events.size() > 0); LoggingEventPtr initialEvent = events[0]; LoggingEventPtr discardEvent = events[events.size() - 1]; LOGUNIT_ASSERT(initialEvent->getMessage() == LOG4CXX_STR("Hello, World")); LOGUNIT_ASSERT(discardEvent->getMessage().substr(0,10) == LOG4CXX_STR("Discarded ")); LOGUNIT_ASSERT_EQUAL(log4cxx::spi::LocationInfo::getLocationUnavailable().getClassName(), discardEvent->getLocationInformation().getClassName()); } void testConfiguration() { log4cxx::xml::DOMConfigurator::configure("input/xml/asyncAppender1.xml"); AsyncAppenderPtr asyncAppender(Logger::getRootLogger()->getAppender(LOG4CXX_STR("ASYNC"))); LOGUNIT_ASSERT(!(asyncAppender == 0)); LOGUNIT_ASSERT_EQUAL(100, asyncAppender->getBufferSize()); LOGUNIT_ASSERT_EQUAL(false, asyncAppender->getBlocking()); LOGUNIT_ASSERT_EQUAL(true, asyncAppender->getLocationInfo()); AppenderList nestedAppenders(asyncAppender->getAllAppenders()); // TODO: // test seems to work okay, but have not found a working way to // get a reference to the nested vector appender // // LOGUNIT_ASSERT_EQUAL((size_t) 1, nestedAppenders.size()); // VectorAppenderPtr vectorAppender(nestedAppenders[0]); // LOGUNIT_ASSERT(0 != vectorAppender); LoggerPtr root(Logger::getRootLogger()); size_t LEN = 20; for (size_t i = 0; i < LEN; i++) { LOG4CXX_DEBUG(root, "message" << i); } asyncAppender->close(); // const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector(); // LOGUNIT_ASSERT_EQUAL(LEN, v.size()); // LOGUNIT_ASSERT_EQUAL(true, vectorAppender->isClosed()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(AsyncAppenderTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/writerappender.h> #include "appenderskeletontestcase.h" /** An abstract set of tests for inclusion in concrete appender test case */ class WriterAppenderTestCase : public AppenderSkeletonTestCase { public: log4cxx::AppenderSkeleton* createAppenderSkeleton() const; virtual log4cxx::WriterAppender* createWriterAppender() const = 0; };
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include "logunit.h" #include <apr_general.h> #include <algorithm> #include <stdlib.h> #include <locale.h> void initialize() { setlocale(LC_CTYPE, ""); const char* ctype = setlocale(LC_CTYPE, 0); if (ctype == 0) { puts("LC_CTYPE: NULL"); } else { printf("LC_CTYPE: %s\n", ctype); } apr_initialize(); } extern const char** testlist; static bool suite_sort(const LogUnit::SuiteList::value_type& lhs, const LogUnit::SuiteList::value_type& rhs) { return lhs.first < rhs.first; } abts_suite* abts_run_suites(abts_suite* suite) { LogUnit::SuiteList sorted(LogUnit::getAllSuites()); #if !defined(_MSC_VER) std::sort(sorted.begin(), sorted.end(), suite_sort); #endif for(LogUnit::SuiteList::const_iterator iter = sorted.begin(); iter != sorted.end(); iter++) { // // if there is an explicit testlist or if the suite is not by default disabled // pump suite through filter if(testlist || !iter->second->isDisabled()) { suite = iter->second->run(suite); } } apr_terminate(); return suite; } using namespace LogUnit; using namespace std; TestException::TestException() {} TestException::TestException(const TestException& src) : std::exception(src) { } TestException& TestException::operator=(const TestException& src) { exception::operator=(src); return *this; } AssertException::AssertException(std::string message, int line) : msg(message), lineno(line) {} AssertException::AssertException(bool expected, const char* actualExpr, int line) : msg(actualExpr), lineno(line) { if (expected) { msg.append(" was expected to be true, was false."); } else { msg.append(" was expected to be true, was false."); } } AssertException::AssertException(const AssertException& src) : std::exception(src), msg(src.msg), lineno(src.lineno) { } AssertException::~AssertException() throw() { } AssertException& AssertException::operator=(const AssertException& src) { exception::operator=(src); msg = src.msg; lineno = src.lineno; return *this; } std::string AssertException::getMessage() const { return msg; } int AssertException::getLine() const { return lineno; } TestFixture::TestFixture() : tc(0) {} TestFixture::~TestFixture() {} void TestFixture::setCase(abts_case* tc) { this->tc = tc; } void TestFixture::setUp() {} void TestFixture::tearDown() {} void TestFixture::assertEquals(const char* expected, const char* actual, const char* expectedExpr, const char* actualExpr, int lineno) { abts_str_equal(tc, expected, actual, lineno); if ((expected == 0 || actual != 0) || (expected != 0 || actual == 0) || (expected != 0 && strcmp(expected, actual) != 0)) { throw TestException(); } } void TestFixture::assertEquals(const std::string expected, const std::string actual, const char* expectedExpr, const char* actualExpr, int lineno) { abts_str_equal(tc, expected.c_str(), actual.c_str(), lineno); if (expected != actual) { throw TestException(); } } template<class S> static void transcode(std::string& dst, const S& src) { for(typename S::const_iterator iter = src.begin(); iter != src.end(); iter++) { if (*iter <= 0x7F) { dst.append(1, (char) *iter); } else { dst.append(1, '?'); } } } #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_WCHAR_T_API void TestFixture::assertEquals(const std::wstring expected, const std::wstring actual, const char* expectedExpr, const char* actualExpr, int lineno) { if (expected != actual) { std::string exp, act; transcode(exp, expected); transcode(act, actual); abts_str_equal(tc, exp.c_str(), act.c_str(), lineno); throw TestException(); } } #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API || LOG4CXX_CFSTRING_API void TestFixture::assertEquals(const std::basic_string<log4cxx::UniChar> expected, const std::basic_string<log4cxx::UniChar> actual, const char* expectedExpr, const char* actualExpr, int lineno) { if (expected != actual) { std::string exp, act; transcode(exp, expected); transcode(act, actual); abts_str_equal(tc, exp.c_str(), act.c_str(), lineno); throw TestException(); } } #endif void TestFixture::assertEquals(const int expected, const int actual, int lineno) { abts_int_equal(tc, expected, actual, lineno); if (expected != actual) { throw TestException(); } } LogUnit::TestSuite::TestSuite(const char* fname) : filename(fname), disabled(false) { #if defined(_WIN32) for(size_t i = filename.find('\\'); i != std::string::npos; i = filename.find('\\', i+1)) { filename.replace(i, 1, 1, '/'); } #endif } void LogUnit::TestSuite::addTest(const char*, test_func func) { test_funcs.push_back(func); } std::string LogUnit::TestSuite::getName() const { return filename; } void LogUnit::TestSuite::setDisabled(bool newVal) { disabled = newVal; } bool LogUnit::TestSuite::isDisabled() const { return disabled; } abts_suite* TestSuite::run(abts_suite* suite) const { suite = abts_add_suite(suite, filename.c_str()); for(TestList::const_iterator iter = test_funcs.begin(); iter != test_funcs.end(); iter++) { abts_run_test(suite, *iter, NULL); } return suite; } LogUnit::SuiteList& LogUnit::getAllSuites() { static LogUnit::SuiteList allSuites; return allSuites; }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/appenderskeleton.h> #include "logunit.h" /** An abstract set of tests for inclusion in concrete appender test case */ LOGUNIT_CLASS(AppenderSkeletonTestCase) { public: virtual log4cxx::AppenderSkeleton* createAppenderSkeleton() const = 0; void testDefaultThreshold(); void testSetOptionThreshold(); };
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/helpers/datagramsocket.h> #include <log4cxx/net/syslogappender.h> #include "../appenderskeletontestcase.h" using namespace log4cxx; using namespace log4cxx::helpers; /** Unit tests of log4cxx::SyslogAppender */ class SyslogAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(SyslogAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::SyslogAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SyslogAppenderTestCase);
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/net/telnetappender.h> #include <log4cxx/ttcclayout.h> #include "../appenderskeletontestcase.h" #include <apr_thread_proc.h> #include <apr_time.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; #if APR_HAS_THREADS /** Unit tests of log4cxx::TelnetAppender */ class TelnetAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(TelnetAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testActivateClose); LOGUNIT_TEST(testActivateSleepClose); LOGUNIT_TEST(testActivateWriteClose); LOGUNIT_TEST_SUITE_END(); enum { TEST_PORT = 1723 }; public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::TelnetAppender(); } void testActivateClose() { TelnetAppenderPtr appender(new TelnetAppender()); appender->setLayout(new TTCCLayout()); appender->setPort(TEST_PORT); Pool p; appender->activateOptions(p); appender->close(); } void testActivateSleepClose() { TelnetAppenderPtr appender(new TelnetAppender()); appender->setLayout(new TTCCLayout()); appender->setPort(TEST_PORT); Pool p; appender->activateOptions(p); Thread::sleep(1000); appender->close(); } void testActivateWriteClose() { TelnetAppenderPtr appender(new TelnetAppender()); appender->setLayout(new TTCCLayout()); appender->setPort(TEST_PORT); Pool p; appender->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(appender); for (int i = 0; i < 50; i++) { LOG4CXX_INFO(root, "Hello, World " << i); } appender->close(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TelnetAppenderTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG4CXX_TEST 1 #include <log4cxx/private/log4cxx_private.h> #if LOG4CXX_HAVE_SMTP #include <log4cxx/net/smtpappender.h> #include "../appenderskeletontestcase.h" #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/logmanager.h> #include <log4cxx/ttcclayout.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; using namespace log4cxx::xml; using namespace log4cxx::spi; namespace log4cxx { namespace net { class MockTriggeringEventEvaluator : public virtual spi::TriggeringEventEvaluator, public virtual helpers::ObjectImpl { public: DECLARE_LOG4CXX_OBJECT(MockTriggeringEventEvaluator) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MockTriggeringEventEvaluator) LOG4CXX_CAST_ENTRY(spi::TriggeringEventEvaluator) END_LOG4CXX_CAST_MAP() MockTriggeringEventEvaluator() { } virtual bool isTriggeringEvent(const spi::LoggingEventPtr& event) { return true; } private: MockTriggeringEventEvaluator(const MockTriggeringEventEvaluator&); MockTriggeringEventEvaluator& operator=(const MockTriggeringEventEvaluator&); }; } } IMPLEMENT_LOG4CXX_OBJECT(MockTriggeringEventEvaluator) /** Unit tests of log4cxx::SocketAppender */ class SMTPAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(SMTPAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testTrigger); LOGUNIT_TEST(testInvalid); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::SMTPAppender(); } void setUp() { } void tearDown() { LogManager::resetConfiguration(); } /** * Tests that triggeringPolicy element will set evaluator. */ void testTrigger() { DOMConfigurator::configure("input/xml/smtpAppender1.xml"); SMTPAppenderPtr appender(Logger::getRootLogger()->getAppender(LOG4CXX_STR("A1"))); TriggeringEventEvaluatorPtr evaluator(appender->getEvaluator()); LOGUNIT_ASSERT_EQUAL(true, evaluator->instanceof(MockTriggeringEventEvaluator::getStaticClass())); } void testInvalid() { SMTPAppenderPtr appender(new SMTPAppender()); appender->setSMTPHost(LOG4CXX_STR("smtp.invalid")); appender->setTo(LOG4CXX_STR("you@example.invalid")); appender->setFrom(LOG4CXX_STR("me@example.invalid")); appender->setLayout(new TTCCLayout()); Pool p; appender->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(appender); LOG4CXX_INFO(root, "Hello, World."); LOG4CXX_ERROR(root, "Sending Message"); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SMTPAppenderTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/net/xmlsocketappender.h> #include "../appenderskeletontestcase.h" using namespace log4cxx; using namespace log4cxx::helpers; #if APR_HAS_THREADS /** Unit tests of log4cxx::net::XMLSocketAppender */ class XMLSocketAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(XMLSocketAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::XMLSocketAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(XMLSocketAppenderTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include <log4cxx/net/socketappender.h> #include <log4cxx/ndc.h> #include <log4cxx/mdc.h> #include <log4cxx/asyncappender.h> #include "socketservertestcase.h" #include "../util/compare.h" #include "../util/transformer.h" #include "../util/controlfilter.h" #include "../util/absolutedateandtimefilter.h" #include "../util/threadfilter.h" #include "../util/filenamefilter.h" #include <apr_time.h> #include <log4cxx/file.h> #include <iostream> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/stringhelper.h> #include "../testchar.h" #include "../logunit.h" #include <log4cxx/spi/loggerrepository.h> //Define INT64_C for compilers that don't have it #if (!defined(INT64_C)) #define INT64_C(value) value ## LL #endif #if defined(WIN32) || defined(_WIN32) #include <windows.h> #endif using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; #define REGEX_STR(x) x // %5p %x [%t] %c %m%n // DEBUG T1 [thread] org.apache.log4j.net.SocketAppenderTestCase Message 1 #define PAT1 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T1 \\[0x[0-9A-F]*]\\ ") \ REGEX_STR(".* Message [0-9]\\{1,2\\}") // DEBUG T2 [thread] patternlayouttest.cpp(?) Message 1 #define PAT2 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T2 \\[0x[0-9A-F]*]\\ ") \ REGEX_STR(".*socketservertestcase.cpp\\([0-9]\\{1,4\\}\\) Message [0-9]\\{1,2\\}") // DEBUG T3 [thread] patternlayouttest.cpp(?) Message 1 #define PAT3 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T3 \\[0x[0-9A-F]*]\\ ") \ REGEX_STR(".*socketservertestcase.cpp\\([0-9]\\{1,4\\}\\) Message [0-9]\\{1,2\\}") // DEBUG some T4 MDC-TEST4 [thread] SocketAppenderTestCase - Message 1 // DEBUG some T4 MDC-TEST4 [thread] SocketAppenderTestCase - Message 1 #define PAT4 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some T4 MDC-TEST4 \\[0x[0-9A-F]*]\\") \ REGEX_STR(" (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") #define PAT5 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some5 T5 MDC-TEST5 \\[0x[0-9A-F]*]\\") \ REGEX_STR(" (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") #define PAT6 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some6 T6 client-test6 MDC-TEST6") \ REGEX_STR(" \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") #define PAT7 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some7 T7 client-test7 MDC-TEST7") \ REGEX_STR(" \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") // DEBUG some8 T8 shortSocketServer MDC-TEST7 [thread] SocketServerTestCase - Message 1 #define PAT8 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some8 T8 shortSocketServer") \ REGEX_STR(" MDC-TEST8 \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") /** * This test checks receipt of SocketAppender messages by the ShortSocketServer * class from log4j. That class must be started externally to this class * for this test to succeed. */ LOGUNIT_CLASS(SocketServerTestCase) { LOGUNIT_TEST_SUITE(SocketServerTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST(test7); LOGUNIT_TEST(test8); LOGUNIT_TEST_SUITE_END(); SocketAppenderPtr socketAppender; LoggerPtr logger; LoggerPtr root; class LineNumberFilter : public Filter { public: LineNumberFilter() { patterns.push_back(PatternReplacement("cpp:[0-9]*", "cpp:XXX")); } }; public: void setUp() { logger = Logger::getLogger(LOG4CXX_STR("org.apache.log4j.net.SocketServerTestCase")); root = Logger::getRootLogger(); } void tearDown() { socketAppender = 0; root->getLoggerRepository()->resetConfiguration(); logger = 0; root = 0; } /** The pattern on the server side: %5p %x [%t] %c %m%n. We are testing NDC functionality across the wire. */ void test1() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); common("test1", LOG4CXX_STR("T1"), LOG4CXX_STR("key1"), LOG4CXX_STR("MDC-TEST1")); delay(1); ControlFilter cf; cf << PAT1; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.1"))); } void test2() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); common("test2", LOG4CXX_STR("T2"), LOG4CXX_STR("key2"), LOG4CXX_STR("MDC-TEST2")); delay(1); ControlFilter cf; cf << PAT2; ThreadFilter threadFilter; LineNumberFilter lineNumberFilter; LogString thisFile; FilenameFilter filenameFilter(__FILE__, "socketservertestcase.cpp"); std::vector<Filter *> filters; filters.push_back(&filenameFilter); filters.push_back(&cf); filters.push_back(&threadFilter); filters.push_back(&lineNumberFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.2"))); } void test3() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); common("test3", LOG4CXX_STR("T3"), LOG4CXX_STR("key3"), LOG4CXX_STR("MDC-TEST3")); delay(1); ControlFilter cf; cf << PAT3; ThreadFilter threadFilter; LineNumberFilter lineNumberFilter; LogString thisFile; FilenameFilter filenameFilter(__FILE__, "socketservertestcase.cpp"); std::vector<Filter *> filters; filters.push_back(&filenameFilter); filters.push_back(&cf); filters.push_back(&threadFilter); filters.push_back(&lineNumberFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.3"))); } void test4() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); NDC::push(LOG4CXX_TEST_STR("some")); common("test4", LOG4CXX_STR("T4"), LOG4CXX_STR("key4"), LOG4CXX_STR("MDC-TEST4")); NDC::pop(); delay(1); ControlFilter cf; cf << PAT4; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.4"))); } void test5() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); AsyncAppenderPtr asyncAppender = new AsyncAppender(); root->addAppender(socketAppender1); root->addAppender(asyncAppender); NDC::push(LOG4CXX_TEST_STR("some5")); common("test5", LOG4CXX_STR("T5"), LOG4CXX_STR("key5"), LOG4CXX_STR("MDC-TEST5")); NDC::pop(); delay(2); ControlFilter cf; cf << PAT5; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.5"))); } void test6() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); AsyncAppenderPtr asyncAppender = new AsyncAppender(); root->addAppender(socketAppender1); root->addAppender(asyncAppender); NDC::push(LOG4CXX_TEST_STR("some6")); MDC::put(LOG4CXX_TEST_STR("hostID"), LOG4CXX_TEST_STR("client-test6")); common("test6", LOG4CXX_STR("T6"), LOG4CXX_STR("key6"), LOG4CXX_STR("MDC-TEST6")); NDC::pop(); MDC::remove(LOG4CXX_TEST_STR("hostID")); delay(2); ControlFilter cf; cf << PAT6; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.6"))); } void test7() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); AsyncAppenderPtr asyncAppender = new AsyncAppender(); root->addAppender(socketAppender1); root->addAppender(asyncAppender); NDC::push(LOG4CXX_TEST_STR("some7")); MDC::put(LOG4CXX_TEST_STR("hostID"), LOG4CXX_TEST_STR("client-test7")); common("test7", LOG4CXX_STR("T7"), LOG4CXX_STR("key7"), LOG4CXX_STR("MDC-TEST7")); NDC::pop(); MDC::remove(LOG4CXX_TEST_STR("hostID")); delay(2); ControlFilter cf; cf << PAT7; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.7"))); } void test8() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); NDC::push(LOG4CXX_TEST_STR("some8")); common("test8", LOG4CXX_STR("T8"), LOG4CXX_STR("key8"), LOG4CXX_STR("MDC-TEST8")); NDC::pop(); delay(2); ControlFilter cf; cf << PAT8; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.8"))); } void common(const std::string& testName, const LogString& dc, const LogString& key, const LogString& val) { int i = -1; NDC::push(dc); MDC::put(key, val); logger->setLevel(Level::getDebug()); root->setLevel(Level::getDebug()); LOG4CXX_TRACE(logger, "Message " << i); i++; logger->setLevel(Level::getTrace()); root->setLevel(Level::getTrace()); LOG4CXX_TRACE(logger, "Message " << ++i); LOG4CXX_TRACE(root, "Message " << ++i); LOG4CXX_DEBUG(logger, "Message " << ++i); LOG4CXX_DEBUG(root, "Message " << ++i); LOG4CXX_INFO(logger, "Message " << ++i); LOG4CXX_WARN(logger, "Message " << ++i); LOG4CXX_FATAL(logger, "Message " << ++i); //5 std::string exceptionMsg("\njava.lang.Exception: Just testing\n" "\tat org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX)\n" "\tat org.apache.log4j.net.SocketServerTestCase."); exceptionMsg.append(testName); exceptionMsg.append("(SocketServerTestCase.java:XXX)\n" "\tat junit.framework.TestCase.runTest(TestCase.java:XXX)\n" "\tat junit.framework.TestCase.runBare(TestCase.java:XXX)\n" "\tat junit.framework.TestResult$1.protect(TestResult.java:XXX)\n" "\tat junit.framework.TestResult.runProtected(TestResult.java:XXX)\n" "\tat junit.framework.TestResult.run(TestResult.java:XXX)\n" "\tat junit.framework.TestCase.run(TestCase.java:XXX)\n" "\tat junit.framework.TestSuite.runTest(TestSuite.java:XXX)\n" "\tat junit.framework.TestSuite.run(TestSuite.java:XXX)"); LOG4CXX_DEBUG(logger, "Message " << ++i << exceptionMsg); LOG4CXX_ERROR(root, "Message " << ++i << exceptionMsg); NDC::pop(); MDC::remove(key); } void delay(int secs) { apr_sleep(APR_USEC_PER_SEC * secs); } private: static const File TEMP; static const File FILTERED; }; const File SocketServerTestCase::TEMP("output/temp"); const File SocketServerTestCase::FILTERED("output/filtered"); LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(SocketServerTestCase)
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/net/socketappender.h> #include "../appenderskeletontestcase.h" using namespace log4cxx; using namespace log4cxx::helpers; #if APR_HAS_THREADS /** Unit tests of log4cxx::SocketAppender */ class SocketAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(SocketAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::SocketAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SocketAppenderTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/net/sockethubappender.h> #include "../appenderskeletontestcase.h" #include <log4cxx/helpers/thread.h> #include <apr.h> using namespace log4cxx; using namespace log4cxx::net; using namespace log4cxx::helpers; #if APR_HAS_THREADS /** Unit tests of log4cxx::SocketHubAppender */ class SocketHubAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(SocketHubAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testActivateClose); LOGUNIT_TEST(testActivateSleepClose); LOGUNIT_TEST(testActivateWriteClose); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::SocketHubAppender(); } void testActivateClose() { SocketHubAppenderPtr hubAppender(new SocketHubAppender()); Pool p; hubAppender->activateOptions(p); hubAppender->close(); } void testActivateSleepClose() { SocketHubAppenderPtr hubAppender(new SocketHubAppender()); Pool p; hubAppender->activateOptions(p); Thread::sleep(1000); hubAppender->close(); } void testActivateWriteClose() { SocketHubAppenderPtr hubAppender(new SocketHubAppender()); Pool p; hubAppender->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(hubAppender); for(int i = 0; i < 50; i++) { LOG4CXX_INFO(root, "Hello, World " << i); } hubAppender->close(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SocketHubAppenderTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logger.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/system.h> #include <log4cxx/level.h> #include "num343patternconverter.h" #include "../testchar.h" #include "../insertwide.h" #include "../logunit.h" #include <log4cxx/spi/loggerrepository.h> #include <log4cxx/pattern/patternparser.h> #include <log4cxx/pattern/patternconverter.h> #include <log4cxx/helpers/relativetimedateformat.h> #include <log4cxx/helpers/simpledateformat.h> #include <log4cxx/pattern/loggerpatternconverter.h> #include <log4cxx/pattern/literalpatternconverter.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/pattern/classnamepatternconverter.h> #include <log4cxx/pattern/datepatternconverter.h> #include <log4cxx/pattern/filedatepatternconverter.h> #include <log4cxx/pattern/filelocationpatternconverter.h> #include <log4cxx/pattern/fulllocationpatternconverter.h> #include <log4cxx/pattern/integerpatternconverter.h> #include <log4cxx/pattern/linelocationpatternconverter.h> #include <log4cxx/pattern/messagepatternconverter.h> #include <log4cxx/pattern/lineseparatorpatternconverter.h> #include <log4cxx/pattern/methodlocationpatternconverter.h> #include <log4cxx/pattern/levelpatternconverter.h> #include <log4cxx/pattern/relativetimepatternconverter.h> #include <log4cxx/pattern/threadpatternconverter.h> #include <log4cxx/pattern/ndcpatternconverter.h> #include <log4cxx/pattern/propertiespatternconverter.h> #include <log4cxx/pattern/throwableinformationpatternconverter.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; using namespace log4cxx::pattern; #define RULES_PUT(spec, cls) \ map.insert(PatternMap::value_type(LOG4CXX_STR(spec), (PatternConstructor) cls ::newInstance)) LOGUNIT_CLASS(PatternParserTestCase) { LOGUNIT_TEST_SUITE(PatternParserTestCase); LOGUNIT_TEST(testNewWord); LOGUNIT_TEST(testNewWord2); LOGUNIT_TEST(testBogusWord1); LOGUNIT_TEST(testBogusWord2); LOGUNIT_TEST(testBasic1); LOGUNIT_TEST(testBasic2); LOGUNIT_TEST(testMultiOption); LOGUNIT_TEST_SUITE_END(); LoggingEventPtr event; public: void setUp() { event = new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION); } void tearDown() { } PatternMap getFormatSpecifiers() { PatternMap map; RULES_PUT("c", LoggerPatternConverter); RULES_PUT("logger", LoggerPatternConverter); RULES_PUT("C", ClassNamePatternConverter); RULES_PUT("class", ClassNamePatternConverter); RULES_PUT("d", DatePatternConverter); RULES_PUT("date", DatePatternConverter); RULES_PUT("F", FileLocationPatternConverter); RULES_PUT("file", FileLocationPatternConverter); RULES_PUT("l", FullLocationPatternConverter); RULES_PUT("L", LineLocationPatternConverter); RULES_PUT("line", LineLocationPatternConverter); RULES_PUT("m", MessagePatternConverter); RULES_PUT("message", MessagePatternConverter); RULES_PUT("n", LineSeparatorPatternConverter); RULES_PUT("M", MethodLocationPatternConverter); RULES_PUT("method", MethodLocationPatternConverter); RULES_PUT("p", LevelPatternConverter); RULES_PUT("level", LevelPatternConverter); RULES_PUT("r", RelativeTimePatternConverter); RULES_PUT("relative", RelativeTimePatternConverter); RULES_PUT("t", ThreadPatternConverter); RULES_PUT("thread", ThreadPatternConverter); RULES_PUT("x", NDCPatternConverter); RULES_PUT("ndc", NDCPatternConverter); RULES_PUT("X", PropertiesPatternConverter); RULES_PUT("properties", PropertiesPatternConverter); RULES_PUT("throwable", ThrowableInformationPatternConverter); return map; } void assertFormattedEquals(const LogString& pattern, const PatternMap& patternMap, const LogString& expected) { std::vector<PatternConverterPtr> converters; std::vector<FormattingInfoPtr> fields; PatternParser::parse(pattern, converters, fields, patternMap); Pool p; LogString actual; std::vector<FormattingInfoPtr>::const_iterator fieldIter = fields.begin(); for(std::vector<PatternConverterPtr>::const_iterator converterIter = converters.begin(); converterIter != converters.end(); converterIter++, fieldIter++) { int fieldStart = actual.length(); (*converterIter)->format(event, actual, p); (*fieldIter)->format(fieldStart, actual); } LOGUNIT_ASSERT_EQUAL(expected, actual); } void testNewWord() { PatternMap testRules(getFormatSpecifiers()); testRules.insert( PatternMap::value_type(LOG4CXX_STR("z343"), (PatternConstructor) Num343PatternConverter::newInstance)); assertFormattedEquals(LOG4CXX_STR("%z343"), testRules, LOG4CXX_STR("343")); } /* Test whether words starting with the letter 'n' are treated differently, * which was previously the case by mistake. */ void testNewWord2() { PatternMap testRules(getFormatSpecifiers()); testRules.insert( PatternMap::value_type(LOG4CXX_STR("n343"), (PatternConstructor) Num343PatternConverter::newInstance)); assertFormattedEquals(LOG4CXX_STR("%n343"), testRules, LOG4CXX_STR("343")); } void testBogusWord1() { assertFormattedEquals(LOG4CXX_STR("%, foobar"), getFormatSpecifiers(), LOG4CXX_STR("%, foobar")); } void testBogusWord2() { assertFormattedEquals(LOG4CXX_STR("xyz %, foobar"), getFormatSpecifiers(), LOG4CXX_STR("xyz %, foobar")); } void testBasic1() { assertFormattedEquals(LOG4CXX_STR("hello %-5level - %m%n"), getFormatSpecifiers(), LogString(LOG4CXX_STR("hello INFO - msg 1")) + LOG4CXX_EOL); } void testBasic2() { Pool pool; RelativeTimeDateFormat relativeFormat; LogString expected; relativeFormat.format(expected, event->getTimeStamp(), pool); expected.append(LOG4CXX_STR(" INFO [")); expected.append(event->getThreadName()); expected.append(LOG4CXX_STR("] org.foobar - msg 1")); expected.append(LOG4CXX_EOL); assertFormattedEquals(LOG4CXX_STR("%relative %-5level [%thread] %logger - %m%n"), getFormatSpecifiers(), expected); } void testMultiOption() { Pool pool; SimpleDateFormat dateFormat(LOG4CXX_STR("HH:mm:ss")); LogString localTime; dateFormat.format(localTime, event->getTimeStamp(), pool); dateFormat.setTimeZone(TimeZone::getGMT()); LogString utcTime; dateFormat.format(utcTime, event->getTimeStamp(), pool); LogString expected(utcTime); expected.append(1, LOG4CXX_STR(' ')); expected.append(localTime); expected.append(LOG4CXX_STR(" org.foobar - msg 1")); assertFormattedEquals(LOG4CXX_STR("%d{HH:mm:ss}{GMT} %d{HH:mm:ss} %c - %m"), getFormatSpecifiers(), expected); } }; // // See bug LOGCXX-204 // #if !defined(_MSC_VER) || _MSC_VER > 1200 LOGUNIT_TEST_SUITE_REGISTRATION(PatternParserTestCase); #endif
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/pattern/loggingeventpatternconverter.h> #include <vector> namespace log4cxx { namespace pattern { class Num343PatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_OBJECT(Num343PatternConverter) Num343PatternConverter(); static PatternConverterPtr newInstance( const std::vector<LogString>& options); protected: void format( const log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& pool) const; }; } }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(_MSC_VER) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include <log4cxx/logstring.h> #include "num343patternconverter.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::pattern; IMPLEMENT_LOG4CXX_OBJECT(Num343PatternConverter) Num343PatternConverter::Num343PatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Num343"), LOG4CXX_STR("num343")) { } PatternConverterPtr Num343PatternConverter::newInstance( const std::vector<LogString>&) { return new Num343PatternConverter(); } void Num343PatternConverter::format( const spi::LoggingEventPtr&, LogString& sbuf, Pool&) const { sbuf.append(LOG4CXX_STR("343")); }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H #define _LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H #include "filter.h" namespace log4cxx { class XMLLineAttributeFilter : public Filter { public: XMLLineAttributeFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "serializationtesthelper.h" #include <log4cxx/helpers/bytearrayoutputstream.h> #include <log4cxx/helpers/objectoutputstream.h> #include <log4cxx/helpers/fileinputstream.h> #include <log4cxx/helpers/bytebuffer.h> #include <log4cxx/file.h> #include "apr_pools.h" using namespace log4cxx; using namespace log4cxx::util; using namespace log4cxx::helpers; using namespace log4cxx::spi; bool SerializationTestHelper::compare( const char* witness, const LoggingEventPtr& event, size_t endCompare) { ByteArrayOutputStreamPtr memOut = new ByteArrayOutputStream(); Pool p; ObjectOutputStream objOut(memOut, p); event->write(objOut, p); objOut.close(p); return compare(witness, memOut->toByteArray(), endCompare, p); } /** * Asserts the serialized form of an object. * @param witness file name of expected serialization. * @param actual byte array of actual serialization. * @param skip positions to skip comparison. * @param endCompare position to stop comparison. * @throws IOException thrown on IO or serialization exception. */ bool SerializationTestHelper::compare( const char* witness, const std::vector<unsigned char>& actual, size_t endCompare, Pool& p) { File witnessFile(witness); char* expected = p.pstralloc(actual.size()); FileInputStreamPtr is(new FileInputStream(witnessFile)); ByteBuffer readBuffer(expected, actual.size()); int bytesRead = is->read(readBuffer); is->close(); if(bytesRead < endCompare) { puts("Witness file is shorter than expected"); return false; } int endScan = actual.size(); if (endScan > endCompare) { endScan = endCompare; } for (int i = 0; i < endScan; i++) { if (((unsigned char) expected[i]) != actual[i]) { printf("Difference at offset %d, expected %x, actual %x\n", i, expected[i], actual[i]); return false; } } return true; }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "absolutetimefilter.h" using namespace log4cxx; using namespace log4cxx::helpers; AbsoluteTimeFilter::AbsoluteTimeFilter() : Filter(ABSOLUTE_TIME_PAT, "") {}
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "iso8601filter.h" using namespace log4cxx; using namespace log4cxx::helpers; ISO8601Filter::ISO8601Filter() : Filter(ISO8601_PAT, "") {}
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "compare.h" #include <log4cxx/helpers/pool.h> #include <log4cxx/file.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/fileinputstream.h> #include <log4cxx/helpers/inputstreamreader.h> #include <log4cxx/helpers/systemoutwriter.h> using namespace log4cxx; using namespace log4cxx::helpers; bool Compare::compare(const File& file1, const File& file2) { Pool pool; InputStreamPtr fileIn1 = new FileInputStream(file1); InputStreamReaderPtr reader1 = new InputStreamReader(fileIn1); LogString in1(reader1->read(pool)); Pool pool2; InputStreamPtr fileIn2 = new FileInputStream(file2); InputStreamReaderPtr reader2 = new InputStreamReader(fileIn2); LogString in2(reader2->read(pool2)); LogString back1(in1); LogString back2(in2); LogString s1; LogString s2; int lineCounter = 0; while (getline(in1, s1)) { lineCounter++; if(!getline(in2, s2)) { s2.erase(s2.begin(), s2.end()); } if (s1 != s2) { LogString msg(LOG4CXX_STR("Files [")); msg += file1.getPath(); msg += LOG4CXX_STR("] and ["); msg += file2.getPath(); msg += LOG4CXX_STR("] differ on line "); StringHelper::toString(lineCounter, pool, msg); msg += LOG4CXX_EOL; msg += LOG4CXX_STR("One reads: ["); msg += s1; msg += LOG4CXX_STR("]."); msg += LOG4CXX_EOL; msg += LOG4CXX_STR("Other reads:["); msg += s2; msg += LOG4CXX_STR("]."); msg += LOG4CXX_EOL; emit(msg); outputFile(file1, back1, pool); outputFile(file2, back2, pool); return false; } } // the second file is longer if (getline(in2, s2)) { LogString msg(LOG4CXX_STR("File [")); msg += file2.getPath(); msg += LOG4CXX_STR("] longer than file ["); msg += file1.getPath(); msg += LOG4CXX_STR("]."); msg += LOG4CXX_EOL; emit(msg); outputFile(file1, back1, pool); outputFile(file2, back2, pool); return false; } return true; } void Compare::outputFile(const File& file, const LogString& contents, log4cxx::helpers::Pool& pool) { int lineCounter = 0; emit(LOG4CXX_STR("--------------------------------")); emit(LOG4CXX_EOL); LogString msg(LOG4CXX_STR("Contents of ")); msg += file.getPath(); msg += LOG4CXX_STR(":"); msg += LOG4CXX_EOL; emit(msg); LogString in1(contents); LogString s1; while (getline(in1, s1)) { lineCounter++; LogString line; StringHelper::toString(lineCounter, pool, line); emit(line); if (lineCounter < 10) { emit(LOG4CXX_STR(" : ")); } else if (lineCounter < 100) { emit(LOG4CXX_STR(" : ")); } else if (lineCounter < 1000) { emit(LOG4CXX_STR(" : ")); } else { emit(LOG4CXX_STR(": ")); } emit(s1); emit(LOG4CXX_EOL); } } void Compare::emit(const LogString& s1) { SystemOutWriter::write(s1); } bool Compare::getline(LogString& in, LogString& line) { if (in.empty()) { return false; } size_t nl = in.find(0x0A); if (nl == std::string::npos) { line = in; in.erase(in.begin(), in.end()); } else { // // if the file has CR-LF then // drop the carriage return alse // if(nl > 0 && in[nl -1] == 0x0D) { line.assign(in, 0, nl - 1); } else { line.assign(in, 0, nl); } in.erase(in.begin(), in.begin() + nl + 1); } return true; }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "binarycompare.h" #include <apr_file_io.h> #include <log4cxx/helpers/pool.h> #include "../logunit.h" #include <apr_pools.h> #include <apr_strings.h> using namespace log4cxx; using namespace log4cxx::util; using namespace log4cxx::helpers; void BinaryCompare::compare(const char* filename1, const char* filename2) { Pool p; apr_pool_t* pool = p.getAPRPool(); apr_file_t* file1; apr_int32_t flags = APR_FOPEN_READ; apr_fileperms_t perm = APR_OS_DEFAULT; apr_status_t stat1 = apr_file_open(&file1, filename1, flags, perm, pool); if (stat1 != APR_SUCCESS) { LOGUNIT_FAIL(std::string("Unable to open ") + filename1); } apr_file_t* file2; apr_status_t stat2 = apr_file_open(&file2, filename2, flags, perm, pool); if (stat2 != APR_SUCCESS) { LOGUNIT_FAIL(std::string("Unable to open ") + filename2); } enum { BUFSIZE = 1024 }; char* contents1 = (char*) apr_palloc(pool, BUFSIZE); char* contents2 = (char*) apr_palloc(pool, BUFSIZE); memset(contents1, 0, BUFSIZE); memset(contents2, 0, BUFSIZE); apr_size_t bytesRead1 = BUFSIZE; apr_size_t bytesRead2 = BUFSIZE; stat1 = apr_file_read(file1, contents1, &bytesRead1); if (stat1 != APR_SUCCESS) { LOGUNIT_FAIL(std::string("Unable to read ") + filename1); } stat2 = apr_file_read(file2, contents2, &bytesRead2); if (stat2 != APR_SUCCESS) { LOGUNIT_FAIL(std::string("Unable to read ") + filename2); } for (int i = 0; i < BUFSIZE; i++) { if (contents1[i] != contents2[i]) { std::string msg("Contents differ at position "); msg += apr_itoa(pool, i); msg += ": ["; msg += filename1; msg += "] has "; msg += apr_itoa(pool, contents1[i]); msg += ", ["; msg += filename2; msg += "] has "; msg += apr_itoa(pool, contents2[i]); msg += "."; LOGUNIT_FAIL(msg); } } }
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xmltimestampfilter.h" using namespace log4cxx; using namespace log4cxx::helpers; XMLTimestampFilter::XMLTimestampFilter() : Filter("[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*", "XXX") {}
C++
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xmlthreadfilter.h" using namespace log4cxx; using namespace log4cxx::helpers; XMLThreadFilter::XMLThreadFilter() : Filter("thread=\\\"[0-9A-Fa-fXx]*", "thread=\\\"main") { }
C++