This repository was archived by the owner on Oct 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathUtil.java
More file actions
427 lines (376 loc) · 14.4 KB
/
Copy pathUtil.java
File metadata and controls
427 lines (376 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.swarm.tokenization.common;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.beam.sdk.schemas.Schema.toSchema;
import com.google.api.services.bigquery.model.TableCell;
import com.google.api.services.bigquery.model.TableRow;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.base.Charsets;
import com.google.gson.Gson;
import com.google.privacy.dlp.v2.InspectContentResponse;
import com.google.privacy.dlp.v2.Table;
import com.google.privacy.dlp.v2.Value;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URI;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.beam.sdk.extensions.gcp.util.gcsfs.GcsPath;
import org.apache.beam.sdk.io.FileIO.ReadableFile;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.Field;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Iterables;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.io.BaseEncoding;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.Instant;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("serial")
public class Util {
public static final Logger LOG = LoggerFactory.getLogger(Util.class);
public enum DLPMethod {
INSPECT,
DEID,
REID
}
public enum FileType {
CSV,
AVRO,
JSON,
TXT
}
public static final Gson gson = new Gson();
private static final char DEFAULT_SEPARATOR = ',';
private static final char DEFAULT_QUOTE = '"';
private static final DateTimeFormatter BIGQUERY_TIMESTAMP_PRINTER;
public static final TupleTag<KV<String, String>> agentTranscriptTuple =
new TupleTag<KV<String, String>>() {};
public static final TupleTag<KV<String, String>> customerTranscriptTuple =
new TupleTag<KV<String, String>>() {};
public static final TupleTag<KV<String, TableRow>> inspectOrDeidSuccess =
new TupleTag<KV<String, TableRow>>() {};
public static final TupleTag<KV<String, TableRow>> inspectOrDeidFailure =
new TupleTag<KV<String, TableRow>>() {};
public static final TupleTag<KV<String, TableRow>> reidSuccess =
new TupleTag<KV<String, TableRow>>() {};
public static final TupleTag<KV<String, TableRow>> reidFailure =
new TupleTag<KV<String, TableRow>>() {};
public static final String BQ_DLP_INSPECT_TABLE_NAME = "dlp_inspection_result";
public static final String BQ_ERROR_TABLE_NAME = "error_log";
public static final String BQ_REID_TABLE_EXT = "re_id";
public static final DateTimeFormatter TIMESTAMP_FORMATTER =
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
public static String checkHeaderName(String name) {
String checkedHeader = name.replaceAll("\\s", "_");
checkedHeader = checkedHeader.replaceAll("'", "");
checkedHeader = checkedHeader.replaceAll("/", "");
checkedHeader = checkedHeader.replaceAll("\\W", "");
LOG.debug("Name {} checkedHeader {}", name, checkedHeader);
return checkedHeader;
}
public static final Schema dlpInspectionSchema =
Stream.of(
Schema.Field.of("job_name", FieldType.STRING).withNullable(true),
Schema.Field.of("source_file", FieldType.STRING).withNullable(true),
Schema.Field.of("transaction_time", FieldType.STRING).withNullable(true),
Schema.Field.of("quote", FieldType.STRING).withNullable(true),
Schema.Field.of("info_type_name", FieldType.STRING).withNullable(true),
Schema.Field.of("likelihood", FieldType.STRING).withNullable(true),
Schema.Field.of("location_start_byte_range", FieldType.INT64).withNullable(true),
Schema.Field.of("location_end_byte_range", FieldType.INT64).withNullable(true),
Schema.Field.of("record_loc_field_id", FieldType.STRING).withNullable(true))
.collect(toSchema());
public static final Schema errorSchema =
Stream.of(
Schema.Field.of("file_name", FieldType.STRING).withNullable(true),
Schema.Field.of("transaction_timestamp", FieldType.STRING).withNullable(true),
Schema.Field.of("error_messagee", FieldType.STRING).withNullable(true),
Schema.Field.of("stack_trace", FieldType.STRING).withNullable(true))
.collect(toSchema());
public static String getTimeStamp() {
return TIMESTAMP_FORMATTER.print(Instant.now().toDateTime(DateTimeZone.UTC));
}
public static BufferedReader getReader(ReadableFile csvFile) {
BufferedReader br = null;
ReadableByteChannel channel = null;
/** read the file and create buffered reader */
try {
channel = csvFile.openSeekable();
} catch (IOException e) {
LOG.error("Failed to Read File {}", e.getMessage());
throw new RuntimeException(e);
}
if (channel != null) {
br = new BufferedReader(Channels.newReader(channel, Charsets.ISO_8859_1.name()));
}
return br;
}
static {
DateTimeFormatter dateTimePart =
new DateTimeFormatterBuilder()
.appendYear(4, 4)
.appendLiteral('-')
.appendMonthOfYear(2)
.appendLiteral('-')
.appendDayOfMonth(2)
.appendLiteral(' ')
.appendHourOfDay(2)
.appendLiteral(':')
.appendMinuteOfHour(2)
.appendLiteral(':')
.appendSecondOfMinute(2)
.toFormatter()
.withZoneUTC();
BIGQUERY_TIMESTAMP_PRINTER =
new DateTimeFormatterBuilder()
.append(dateTimePart)
.appendLiteral('.')
.appendFractionOfSecond(3, 3)
.appendLiteral(" UTC")
.toFormatter();
}
private static Object fromBeamField(FieldType fieldType, Object fieldValue) {
if (fieldValue == null) {
if (!fieldType.getNullable()) {
throw new IllegalArgumentException("Field is not nullable.");
}
return null;
}
switch (fieldType.getTypeName()) {
case ARRAY:
case ITERABLE:
FieldType elementType = fieldType.getCollectionElementType();
Iterable<?> items = (Iterable<?>) fieldValue;
List<Object> convertedItems = Lists.newArrayListWithCapacity(Iterables.size(items));
for (Object item : items) {
convertedItems.add(fromBeamField(elementType, item));
}
return convertedItems;
case ROW:
return toTableRow((Row) fieldValue);
case DATETIME:
return ((Instant) fieldValue)
.toDateTime(DateTimeZone.UTC)
.toString(BIGQUERY_TIMESTAMP_PRINTER);
case INT16:
case INT32:
case INT64:
case FLOAT:
case DOUBLE:
case STRING:
case BOOLEAN:
return fieldValue.toString();
case DECIMAL:
return fieldValue.toString();
case BYTES:
return BaseEncoding.base64().encode((byte[]) fieldValue);
default:
return fieldValue;
}
}
public static TableRow toTableRow(Row row) {
TableRow output = new TableRow();
for (int i = 0; i < row.getFieldCount(); i++) {
Object value = row.getValue(i);
Field schemaField = row.getSchema().getField(i);
output = output.set(schemaField.getName(), fromBeamField(schemaField.getType(), value));
}
return output;
}
@SuppressWarnings("null")
// custom parser for csv- will be taken out
public static List<String> parseLine(String cvsLine, char separators, char customQuote) {
List<String> result = new ArrayList<>();
// if empty, return!
if (cvsLine == null && cvsLine.isEmpty()) {
return result;
}
if (customQuote == ' ') {
customQuote = DEFAULT_QUOTE;
}
if (separators == ' ') {
separators = DEFAULT_SEPARATOR;
}
StringBuffer curVal = new StringBuffer();
boolean inQuotes = false;
boolean startCollectChar = false;
boolean doubleQuotesInColumn = false;
char[] chars = cvsLine.toCharArray();
for (char ch : chars) {
if (inQuotes) {
startCollectChar = true;
if (ch == customQuote) {
inQuotes = false;
doubleQuotesInColumn = false;
} else {
// Fixed : allow "" in custom quote enclosed
if (ch == '\"') {
if (!doubleQuotesInColumn) {
curVal.append(ch);
doubleQuotesInColumn = true;
}
} else {
curVal.append(ch);
}
}
} else {
if (ch == customQuote) {
inQuotes = true;
// Fixed : allow "" in empty quote enclosed
if (chars[0] != '"' && customQuote == '\"') {
curVal.append('"');
}
// double quotes in column will hit this!
if (startCollectChar) {
curVal.append('"');
}
} else if (ch == separators) {
result.add(curVal.toString());
curVal = new StringBuffer();
startCollectChar = false;
} else if (ch == '\r') {
// ignore LF characters
continue;
} else if (ch == '\n') {
// the end, break!
break;
} else {
curVal.append(ch);
}
}
}
result.add(curVal.toString());
return result;
}
public static TableRow createBqRow(Table.Row tokenizedValue, String[] headers) {
TableRow bqRow = new TableRow();
AtomicInteger headerIndex = new AtomicInteger(0);
List<TableCell> cells = new ArrayList<>();
tokenizedValue
.getValuesList()
.forEach(
value -> {
String checkedHeaderName =
Util.checkHeaderName(headers[headerIndex.getAndIncrement()]);
bqRow.set(checkedHeaderName, value.getStringValue());
cells.add(new TableCell().set(checkedHeaderName, value.getStringValue()));
});
bqRow.setF(cells);
return bqRow;
}
public static String getQueryFromGcs(String gcsPath) {
GcsPath path = GcsPath.fromUri(URI.create(gcsPath));
Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of(path.getBucket(), path.getObject());
byte[] content = storage.readAllBytes(blobId);
String contentString = new String(content, UTF_8);
LOG.debug("Query: {}", contentString);
return contentString;
}
// index, transcript -> 0 [Customer]: <text> [Agent]:
public static String parseChatlog(String fileName, String chatLog) {
String index = chatLog.substring(0, 1);
String transcript = chatLog.substring(1);
Random r = new Random();
// escape header fields
if (StringUtils.isNumeric(index)) {
try (Scanner scanner = new Scanner(transcript.trim())) {
scanner.useDelimiter("\\ ");
int position = 1;
StringBuilder agentTranscript = new StringBuilder();
StringBuilder customerTranscript = new StringBuilder();
boolean agentScript = true;
while (scanner.hasNext()) {
String word = scanner.next().trim();
if (word.contains("[Customer]:")) {
customerTranscript.append(StringUtils.remove(word, "[Customer]:"));
agentScript = false;
if (agentTranscript.length() > 0) {
String[] tempValues = {
String.format("%s%s%s%s%d", fileName, "_", index, "_", r.nextInt(100)),
"agent",
agentTranscript.toString(),
String.valueOf(position),
"N/A"
};
agentTranscript.setLength(0);
position = position + 1;
String finalTranscript =
Arrays.asList(tempValues).stream().collect(Collectors.joining(","));
return finalTranscript;
}
} else if (word.contains("[Agent]:")) {
agentTranscript.append(StringUtils.remove(word, "[Agent]:"));
agentScript = true;
if (customerTranscript.length() > 0) {
String[] tempValues = {
String.format("%s%s%s%s%d", fileName, "_", index, "_", r.nextInt(100)),
"customer",
customerTranscript.toString(),
String.valueOf(position),
"N/A"
};
customerTranscript.setLength(0);
position = position + 1;
String finalTranscript =
Arrays.asList(tempValues).stream().collect(Collectors.joining(","));
return finalTranscript;
}
} else {
if (agentScript) {
agentTranscript.append(StringUtils.SPACE);
agentTranscript.append(word);
} else {
customerTranscript.append(StringUtils.SPACE);
customerTranscript.append(word);
}
}
}
}
}
return StringUtils.EMPTY;
}
// needed to transform after parsing contextual text io read metadata for csv files.
public static String sanitizeCSVFileName(String fileName){
// fileName.csv
if(fileName.contains(".")){
return fileName.replace(".","_");
}
return fileName;
}
}