code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
@GET
@Path("teams")
public Response authorizedTeams(@HeaderParam("Authorization") @DefaultValue("no token") String auth) throws Exception {
if(!this.isAuth(auth)) {
return Response.status(Status.FORBIDDEN).build();
}
Integer teams[] = getAuthorizedTeams();
return Response.ok(new Gson().toJson(... | java |
private void sendRequest(HttpUriRequest request, int expectedStatus)
throws Exception {
addAuthHeader(request);
HttpClient client = httpClient();
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
EntityUtils.c... | java |
private String hashPasswordForShiro() {
//Hash password
HashFormatFactory HASH_FORMAT_FACTORY = new DefaultHashFormatFactory();
SecureRandomNumberGenerator generator = new SecureRandomNumberGenerator();
int byteSize = 128 / 8;
ByteSource salt = generator.nextBytes(byteSize);
SimpleHash has... | java |
public static Field createTupleField(String name, Schema schema) {
return Field.createTupleField(name, schema);
} | java |
@Override
protected void configure() {
try {
InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
File appRoot = new File(System.getProperty(CadmiumListener.BASE_PATH_ENV), "maven");
FileUtils.forceMkdir(appRoot);
String remoteMavenRepo = System.getProperty(MAVEN_REPOSITORY);... | java |
public static Response internalError(Throwable throwable, UriInfo uriInfo) {
GenericError error = new GenericError(
ExceptionUtils.getRootCauseMessage(throwable),
ErrorCode.INTERNAL.getCode(),
uriInfo.getAbsolutePath().toString());
if (!isProduction()) {
error.setStack(ExceptionU... | java |
public static GitService initializeConfigDirectory(String uri, String branch, String root, String warName, HistoryManager historyManager, ConfigManager configManager) throws Exception {
initializeBaseDirectoryStructure(root, warName);
String warDir = FileSystemManager.getChildDirectoryIfExists(root, warName);
... | java |
public String checkinNewContent(String sourceDirectory, String message) throws Exception {
RmCommand remove = git.rm();
boolean hasFiles = false;
for(String filename : new File(getBaseDirectory()).list()) {
if(!filename.equals(".git")) {
remove.addFilepattern(filename);
hasFiles = true... | java |
public ObjectNode convertToObjectNode(ILoggingEvent event) {
final ObjectNode logLine = mapper.valueToTree(
event instanceof OtlType ? event : new ApplicationLogEvent(event));
final Marker marker = event.getMarker();
if (marker instanceof LogMetadata) {
ObjectNode me... | java |
protected byte[] getLogMessage(final ObjectNode event) {
try(ByteArrayBuilder buf = new ByteArrayBuilder()){
mapper.writeValue(buf, event);
buf.append('\n');
return buf.toByteArray();
} catch (IOException e) {
addError("while serializing log event", e);
... | java |
public void execute() throws Exception {
String content = null;
String siteUrl = null;
if (params.size() == 2) {
content = params.get(0);
siteUrl = getSecureBaseUrl(params.get(1));
} else if (params.size() == 0) {
System.err.println("The content directory and site must be specifed.");... | java |
public static void enableSerialization(Configuration conf) {
String serClass = TupleSerialization.class.getName();
Collection<String> currentSers = conf.getStringCollection("io.serializations");
if(currentSers.size() == 0) {
conf.set("io.serializations", serClass);
return;
}
// Check if it is already ... | java |
public static void disableSerialization(Configuration conf) {
String ser = conf.get("io.serializations").trim();
String stToSearch = Pattern.quote("," + TupleSerialization.class.getName());
ser = ser.replaceAll(stToSearch, "");
conf.set("io.serializations", ser);
} | java |
public static int compare(String ns1, String ln1, String ns2, String ln2) {
if (ns1 == null) {
ns1 = Constants.XML_NULL_NS_URI;
}
if (ns2 == null) {
ns2 = Constants.XML_NULL_NS_URI;
}
int cLocalPart = ln1.compareTo(ln2);
return (cLocalPart == 0 ? ns1.compareTo(ns2) : cLocalPart);
} | java |
public static void postConstructQuietly(Object obj, Logger log) {
try {
postConstruct(obj, log);
}
catch( Throwable t ) {
log.warn("Could not @PostConstruct object", t);
}
} | java |
public static void preDestroyQuietly(Object obj, Logger log) {
try {
preDestroy(obj, log);
}
catch( Throwable t ) {
log.warn("Could not @PreDestroy object", t);
}
} | java |
private static List<Method> getAnnotatedMethodsFromChildToParent(Class<?> clazz, Class<? extends Annotation> annotation,
Logger log) {
List<Method> methodsToRun = new ArrayList<Method>();
while(clazz != null) {
List<Method> newMethods = getMethodsWithAnnotation(clazz, annotation, log);
for(Met... | java |
private static boolean containsMethod(Method method, List<Method> methods) {
if(methods != null) {
for(Method aMethod : methods){
if(method.getName().equals(aMethod.getName())) {
return true;
}
}
}
return false;
} | java |
private static void removeMethodByName(Method method, List<Method> methods) {
if(methods != null) {
Iterator<Method> itr = methods.iterator();
Method aMethod = null;
while(itr.hasNext()) {
aMethod = itr.next();
if(aMethod.getName().equals(method.getName())) {
itr.remove()... | java |
private static List<Method> getMethodsWithAnnotation(Class<?> clazz, Class<? extends Annotation> annotation, Logger log) {
List<Method> annotatedMethods = new ArrayList<Method>();
Method classMethods[] = clazz.getDeclaredMethods();
for(Method classMethod : classMethods) {
if(classMethod.isAnnotationPr... | java |
public static Jsr250Executor createJsr250Executor(Injector injector, final Logger log, Scope... scopes ) {
final Set<Object> instances = findInstancesInScopes(injector, scopes);
final List<Object> reverseInstances = new ArrayList<Object>(instances);
Collections.reverse(reverseInstances);
return new Jsr2... | java |
public static Set<Object> findInstancesInScopes(Injector injector, Class<? extends Annotation>... scopeAnnotations) {
Set<Object> objects = new TreeSet<Object>(new Comparator<Object>() {
@Override
public int compare(Object o0, Object o1) {
return o0.getClass().getName().compareTo(o1.getClass().... | java |
public static Map<Key<?>, Binding<?>> findBindingsInScope(Injector injector, Class<? extends Annotation>... scopeAnnotations) {
Map<Key<?>,Binding<?>> bindings = new LinkedHashMap<Key<?>, Binding<?>>();
ALL_BINDINGS: for( Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet() ) {
for( ... | java |
public static Map<Key<?>, Binding<?>> findBindingsInScope(Injector injector, Scope... scopes) {
Map<Key<?>,Binding<?>> bindings = new LinkedHashMap<Key<?>, Binding<?>>();
ALL_BINDINGS: for( Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet() ) {
for( Scope scope : scopes ) {
... | java |
public static boolean inScope(final Injector injector, final Binding<?> binding, final Class<? extends Annotation> scope) {
return binding.acceptScopingVisitor(new BindingScopingVisitor<Boolean>() {
@Override
public Boolean visitEagerSingleton() {
return scope == Singleton.class || scope == jav... | java |
private void init(Class<?> type) {
if(method.isAnnotationPresent(CoordinatorOnly.class)
|| type.isAnnotationPresent(CoordinatorOnly.class)) {
coordinatorOnly = true;
}
if(method.isAnnotationPresent(Scheduled.class)) {
annotation = method.getAnnotation(Scheduled.class);
} else if(typ... | java |
private void checkRunnable(Class<?> type) {
if(Runnable.class.isAssignableFrom(type)) {
try{
this.method = type.getMethod("run");
} catch(Exception e) {
throw new RuntimeException("Cannot get run method of runnable class.", e);
}
}
} | java |
public static String[] sendRequest(String token, String site, OPERATION op, String path) throws Exception {
HttpClient client = httpClient();
HttpUriRequest message = null;
if(op == OPERATION.DISABLE) {
message = new HttpPut(site + ENDPOINT + path);
} else if(op == OPERATION.ENABLE){
message... | java |
public void shallowCopy(ITuple tupleDest) {
for(Field field: this.getSchema().getFields()) {
tupleDest.set(field.getName(), this.get(field.getName()));
}
} | java |
public static final String getQualifiedName(String localName, String pfx) {
pfx = pfx == null ? "" : pfx;
return pfx.length() == 0 ? localName
: (pfx + Constants.COLON + localName);
} | java |
public void setOption(String key, Object value) throws UnsupportedOption {
if (key.equals(INCLUDE_COOKIE)) {
options.put(key, null);
} else if (key.equals(INCLUDE_OPTIONS)) {
options.put(key, null);
} else if (key.equals(INCLUDE_SCHEMA_ID)) {
options.put(key, null);
} else if (key.equals(RETAIN_ENTITY_... | java |
public boolean unsetOption(String key) {
// we do have null values --> check for key
boolean b = options.containsKey(key);
options.remove(key);
return b;
} | java |
private static void checkNamedOutputName(JobContext job, String namedOutput, boolean alreadyDefined) {
validateOutputName(namedOutput);
List<String> definedChannels = getNamedOutputsList(job);
if(alreadyDefined && definedChannels.contains(namedOutput)) {
throw new IllegalArgumentException("Named output '" + na... | java |
private static String getDefaultNamedOutputFormatInstanceFile(JobContext job) {
return job.getConfiguration().get(DEFAULT_MO_PREFIX + FORMAT_INSTANCE_FILE, null);
} | java |
private static Class<?> getDefaultNamedOutputKeyClass(JobContext job) {
return job.getConfiguration().getClass(DEFAULT_MO_PREFIX + KEY, null, Object.class);
} | java |
private static Class<?> getDefaultNamedOutputValueClass(JobContext job) {
return job.getConfiguration().getClass(DEFAULT_MO_PREFIX + VALUE, null, Object.class);
} | java |
public static String addNamedOutput(Job job, String namedOutput, OutputFormat outputFormat,
Class<?> keyClass, Class<?> valueClass) throws FileNotFoundException, IOException,
URISyntaxException {
checkNamedOutputName(job, namedOutput, true);
Configuration conf = job.getConfiguration();
String uniqueName... | java |
@SuppressWarnings("unchecked")
public <K, V> void write(String namedOutput, K key, V value, String baseOutputPath)
throws IOException, InterruptedException {
checkNamedOutputName(context, namedOutput, false);
checkBaseOutputPath(baseOutputPath);
if(!namedOutputs.contains(namedOutput)) {
throw new Illegal... | java |
public void close() throws IOException, InterruptedException {
for(OutputContext outputContext : this.outputContexts.values()) {
outputContext.recordWriter.close(outputContext.taskAttemptContext);
outputContext.outputCommitter.commitTask(outputContext.taskAttemptContext);
// This is a trick for Hadoop 2.0 wh... | java |
private WhiteSpace getDatatypeWhiteSpace() {
Grammar currGr = this.getCurrentGrammar();
if (currGr.isSchemaInformed() && currGr.getNumberOfEvents() > 0) {
Production prod = currGr.getProduction(0);
if (prod.getEvent().getEventType() == EventType.CHARACTERS) {
Characters ch = (Characters) prod.getEvent();
... | java |
public void skip(long n) throws IOException {
if (capacity == 0) {
// aligned
while (n != 0) {
n -= istream.skip(n);
}
} else {
// not aligned, grrr
for (int i = 0; i < n; n++) {
readBits(8);
}
}
} | java |
public int readBits(int n) throws IOException {
assert (n > 0);
int result;
if (n <= capacity) {
// buffer already holds all necessary bits
result = (buffer >> (capacity -= n))
& (0xff >> (BUFFER_CAPACITY - n));
} else if (capacity == 0 && n == BUFFER_CAPACITY) {
// possible to read direct byte, ... | java |
public void readFields(ITuple tuple, Deserializer[] customDeserializers) throws IOException {
readFields(tuple, readSchema, customDeserializers);
} | java |
@Override
public final void mutate(Context context)
throws MutagenException {
// Perform the mutation
performMutation(context);
int version=getResultingState().getID();
String change=getChangeSummary();
if (change==null) {
change="";
}
String changeHash=md5String(change);
// The straightforw... | java |
public static String toHex(byte[] bytes) {
StringBuilder hexString=new StringBuilder();
for (int i=0; i<bytes.length; i++) {
String hex=Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} | java |
public static List<String> getDeployed(String url, String token) throws Exception {
List<String> deployed = new ArrayList<String> ();
HttpClient client = httpClient();
HttpGet get = new HttpGet(url + "/system/deployment/list");
addAuthHeader(token, get);
HttpResponse resp = client.execute(... | java |
public static void undeploy(String url, String warName, String token) throws Exception {
HttpClient client = httpClient();
HttpPost del = new HttpPost(url + "/system/undeploy");
addAuthHeader(token, del);
del.addHeader("Content-Type", MediaType.APPLICATION_JSON);
UndeployRequest req = new ... | java |
public void set(int bit, boolean value) {
int bite = byteForBit(bit);
ensureSpace(bite + 1);
int bitOnByte = bitOnByte(bit, bite);
if (value) {
bits[bite] = byteBitSet(bitOnByte, bits[bite]);
} else {
bits[bite] = byteBitUnset(bitOnByte, bits[bite]);
}
} | java |
public boolean isSet(int bit) {
int bite = byteForBit(bit);
if (bite >= bits.length || bits.length == 0) {
return false;
}
int bitOnByte = bitOnByte(bit, bite);
return ((1 << bitOnByte) & bits[bite]) != 0;
} | java |
public void ser(DataOutput out) throws IOException {
if (bits.length == 0) {
out.writeByte(0);
return;
}
// removing trailing empty bytes.
int bytesToWrite;
for (bytesToWrite = bits.length; bytesToWrite > 1 && bits[bytesToWrite - 1] == 0; bytesToWrite--) ;
// Writing first bytes, wit... | java |
public int deser(byte[] bytes, int start) throws IOException {
int idx = 0;
byte current;
do {
current = bytes[start+idx];
ensureSpace(idx + 1);
// The last bit must be clear
bits[idx] = (byte) (current & ~1);
idx++;
} while ((current & 1) != 0);
// clear the remaining ... | java |
protected void ensureSpace(int bytes) {
if (bits.length < bytes) {
bits = Arrays.copyOf(bits, bytes);
}
} | java |
@Override
public TypeDescription addTypeDescription(TypeDescription definition) {
if(definition != null && definition.getTag() != null) {
tagsDefined.add(definition.getTag());
}
return super.addTypeDescription(definition);
} | java |
@Override
protected Construct getConstructor(Node node) {
Construct construct = super.getConstructor(node);
logger.trace("getting constructor for node {} Tag {} = {}", new Object[] {node, node.getTag(), construct});
if(construct instanceof ConstructYamlObject && !tagsDefined.contains(node.getTag())) {
... | java |
private void resolveType(Node node) throws ClassNotFoundException {
String typeName = node.getTag().getClassName();
if(typeName.equals("int")) {
node.setType(Integer.TYPE);
} else if(typeName.equals("float")) {
node.setType(Float.TYPE);
} else if(typeName.equals("double")) {
node.setTy... | java |
protected UUID getRequestIdFrom(Request request, Response response) {
return optUuid(response.getHeader(OTHeaders.REQUEST_ID));
} | java |
public static LoggerConfig[] setLogLevel(String loggerName, String level) {
if(StringUtils.isBlank(loggerName)) {
loggerName = ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME;
}
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
log.debug("Setting {} to level {}", loggerName... | java |
public int decodeNBitUnsignedInteger(int n) throws IOException {
assert (n >= 0);
int bitsRead = 0;
int result = 0;
while (bitsRead < n) {
// result = (result << 8) | is.read();
result += (decode() << bitsRead);
bitsRead += 8;
}
return result;
} | java |
public Set<String> configureJob(Job job) throws FileNotFoundException, IOException, TupleMRException {
Set<String> instanceFiles = new HashSet<String>();
for(Output output : getNamedOutputs()) {
try {
if(output.isDefault) {
instanceFiles.add(PangoolMultipleOutputs.setDefaultNamedOutput(job, output.outpu... | java |
public boolean canCheckWar(String warName, String url, HttpClient client) {
HttpOptions opt = new HttpOptions(url + "/" + warName);
try {
HttpResponse response = client.execute(opt);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Header allowHeader[] = response.getHeaders... | java |
public void encodeBinary(byte[] b) throws IOException {
encodeUnsignedInteger(b.length);
encode(b, 0, b.length);
} | java |
public void encodeString(final String s) throws IOException {
final int lenChars = s.length();
final int lenCharacters = s.codePointCount(0, lenChars);
encodeUnsignedInteger(lenCharacters);
encodeStringOnly(s);
} | java |
public void encodeInteger(int n) throws IOException {
// signalize sign
if (n < 0) {
encodeBoolean(true);
// For negative values, the Unsigned Integer holds the
// magnitude of the value minus 1
encodeUnsignedInteger((-n) - 1);
} else {
encodeBoolean(false);
encodeUnsignedInteger(n);
}
} | java |
public void encodeUnsignedInteger(int n) throws IOException {
if (n < 0) {
throw new UnsupportedOperationException();
}
if (n < 128) {
// write byte as is
encode(n);
} else {
final int n7BitBlocks = MethodsBag.numberOf7BitBlocksToRepresent(n);
switch (n7BitBlocks) {
case 5:
encode(128 | ... | java |
public void encodeFloat(FloatValue fv) throws IOException {
// encode mantissa and exponent
encodeIntegerValue(fv.getMantissa());
encodeIntegerValue(fv.getExponent());
} | java |
private void addAddressHelper(InternetAddressSet set, String address) {
if (address.contains(",") || address.contains(";")) {
String[] addresses = address.split("[,;]");
for (String a : addresses) {
set.add(a);
}
}
else {
set.add(address);
}
} | java |
public void simplify()
{
// remove all addresses from the cc and bcc that are in the to address set.
ccSet.removeAll(toSet);
bccSet.removeAll(toSet);
// remove all address from the bcc set that are in the cc set.
bccSet.removeAll(ccSet);
} | java |
protected void populate( MimeMessage message )
throws MessagingException
{
// add all of the to addresses.
message.addRecipients(Message.RecipientType.TO, toSet.toInternetAddressArray());
message.addRecipients(Message.RecipientType.CC, ccSet.toInternetAddressArray());
message.addRecipients(Message... | java |
public static AttachLogFilter attach(Filter<ILoggingEvent> filter, String configKey) {
return new AttachLogFilter(filter, configKey);
} | java |
public static void enableThriftSerialization(Configuration conf) {
String ser = conf.get("io.serializations").trim();
if (ser.length() !=0 ) {
ser += ",";
}
//Adding the Thrift serialization
ser += ThriftSerialization.class.getName();
conf.set("io.serializations", ser);
} | java |
public static void main(String[] args) {
try {
jCommander = new JCommander();
jCommander.setProgramName("cadmium");
HelpCommand helpCommand = new HelpCommand();
jCommander.addCommand("help", helpCommand);
Map<String, CliCommand> commands = wireCommands(jCommander);
try {
... | java |
private static void setupSsh(boolean noPrompt) {
File sshDir = new File(System.getProperty("user.home"), ".ssh");
if(sshDir.exists()) {
GitService.setupLocalSsh(sshDir.getAbsolutePath(), noPrompt);
}
} | java |
public static void emptyMatrix(byte[][] matrix, int maxX, int maxY) {
for(int i = 0; i < maxX; i++) {
for(int j = 0; j < maxY; j++) {
matrix[i][j] = 0;
}
}
} | java |
static public byte[] decode(String encoded) {
if (encoded == null)
return null;
int lengthData = encoded.length();
if (lengthData % 2 != 0)
return null;
char[] binaryData = encoded.toCharArray();
int lengthDecode = lengthData / 2;
byte[] decodedData = new byte[lengthDecode];
byte temp1, temp2;
ch... | java |
public static DateTimeValue parse(Calendar cal, DateTimeType type) {
int sYear = 0;
int sMonthDay = 0;
int sTime = 0;
int sFractionalSecs = 0;
boolean sPresenceTimezone = false;
int sTimezone;
switch (type) {
case gYear: // gYear Year, [Time-Zone]
case gYearMonth: // gYearMonth Year, MonthDay, [Time... | java |
protected static void setMonthDay(int monthDay, Calendar cal) {
// monthDay = month * 32 + day;
int month = monthDay / MONTH_MULTIPLICATOR;
cal.set(Calendar.MONTH, month - 1);
int day = monthDay - month * MONTH_MULTIPLICATOR;
cal.set(Calendar.DAY_OF_MONTH, day);
} | java |
protected static void setTime(int time, Calendar cal) {
// ((Hour * 64) + Minutes) * 64 + seconds
int hour = time / (64 * 64);
time -= hour * (64 * 64);
int minute = time / 64;
time -= minute * 64; // second
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, ... | java |
private static void addPortMapping( Integer insecurePort, Integer securePort ) {
TO_SECURE_PORT_MAP.put(insecurePort, securePort);
TO_INSECURE_PORT_MAP.put(securePort, insecurePort);
} | java |
public static int getDefaultPort( String protocol ) {
if( HTTP_PROTOCOL.equals(protocol) ) { return DEFAULT_HTTP_PORT; }
else if( HTTPS_PROTOCOL.equals(protocol) ) { return DEFAULT_HTTPS_PORT; }
else { throw new IllegalArgumentException("No known default for "+protocol); }
} | java |
public static int mapPort(Map<Integer, Integer> mapping, int port) {
Integer mappedPort = mapping.get(port);
if( mappedPort == null ) throw new RuntimeException("Could not map port "+port);
return mappedPort;
} | java |
public String secureUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
String protocol = getProtocol(request);
if( protocol.equalsIgnoreCase(HTTP_PROTOCOL) ) {
int port = mapPort(TO_SECURE_PORT_MAP, getPort(request));
try {
URI newUri = changeProtocolAndPort(H... | java |
public String insecureUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
String protocol = getProtocol(request);
if( protocol.equalsIgnoreCase(HTTPS_PROTOCOL) ) {
int port = mapPort(TO_INSECURE_PORT_MAP, getPort(request));
try {
return changeProtocolAndPort(HT... | java |
@Override
public void makeSecure(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", secureUrl(request, response));
response.getOutputStream().flush();
response.getOutputStream... | java |
@Override
public void makeInsecure(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", insecureUrl(request, response));
response.getOutputStream().flush();
response.getOutputStream()... | java |
public void init(Configuration conf, Path generatedModel) throws IOException, InterruptedException {
FileSystem fileSystem = FileSystem.get(conf);
for(Category category : Category.values()) {
wordCountPerCategory.put(category, new HashMap<String, Integer>()); // init token count
}
// Use a HashSet to calcula... | java |
public Category classify(String text) {
StringTokenizer itr = new StringTokenizer(text);
Map<Category, Double> scorePerCategory = new HashMap<Category, Double>();
double bestScore = Double.NEGATIVE_INFINITY;
Category bestCategory = null;
while(itr.hasMoreTokens()) {
String token = NaiveBayesGenerate.normal... | java |
public static int numberOf7BitBlocksToRepresent(final long l) {
if (l < 0xffffffff) {
return numberOf7BitBlocksToRepresent((int) l);
}
// 35 bits
else if (l < 0x800000000L) {
return 5;
}
// 42 bits
else if (l < 0x40000000000L) {
return 6;
}
// 49 bits
else if (l < 0x2000000000000L) {
ret... | java |
public static MimeBodyPart newMultipartBodyPart( Multipart multipart )
throws MessagingException
{
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(multipart);
return mimeBodyPart;
} | java |
public static MimeBodyPart newHtmlAttachmentBodyPart( URL contentUrl, String contentId )
throws MessagingException
{
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDataHandler(new DataHandler(contentUrl));
if( contentId != null ) {
mimeBodyPart.setHeader("Content-ID", contentId)... | java |
public static String fileNameForUrl( URL contentUrl )
{
String fileName = null;
Matcher matcher = FILE_NAME_PATTERN.matcher(contentUrl.getPath());
if( matcher.find() ) {
fileName = matcher.group(1);
}
return fileName;
} | java |
private void initCommonAndGroupSchemaSerialization() {
//TODO Should SerializationInfo contain Configuration ?
commonSerializers = getSerializers(commonSchema, null);
commonDeserializers = getDeserializers(commonSchema, commonSchema, null);
groupSerializers = getSerializers(groupSchema, null);
grou... | java |
private Field checkFieldInAllSchemas(String name) throws TupleMRException {
Field field = null;
for (int i = 0; i < mrConfig.getIntermediateSchemas().size(); i++) {
Field fieldInSource = checkFieldInSchema(name, i);
if (field == null) {
field = fieldInSource;
} else if (field.getType()... | java |
public File resolveMavenArtifact(String artifact) throws ArtifactResolutionException {
// NOTE: This page on Aether (https://docs.sonatype.org/display/AETHER/Home) states that
// the plexus container uses the context class loader.
ClassLoader oldContext = Thread.currentThread().getContextClassLoader();
... | java |
protected RepositorySystemSession newSession( RepositorySystem system )
{
MavenRepositorySystemSession session = new MavenRepositorySystemSession();
LocalRepository localRepo = new LocalRepository( localRepository );
session.setLocalRepositoryManager( system.newLocalRepositoryManager( localRepo ) )... | java |
private static Path locateFileInCache(Configuration conf, String filename) throws IOException {
return new Path(getInstancesFolder(FileSystem.get(conf), conf), filename);
} | java |
public static File getWritableDirectoryWithFailovers(String... directories) throws FileNotFoundException {
File logDir = null;
for(String directory : directories) {
if(directory != null) {
try {
logDir = ensureDirectoryWriteable(new File(directory));
} catch(FileNotFoundException... | java |
public static File ensureDirectoryWriteable(File logDir) throws FileNotFoundException {
try {
FileUtils.forceMkdir(logDir);
} catch(IOException e){
log.debug("Failed to create directory " + logDir, e);
throw new FileNotFoundException("Failed to create directory: " + logDir + " IOException: " +... | java |
@Override
public int getPartition(DatumWrapper<ITuple> key, NullWritable value, int numPartitions) {
if(numPartitions == 1) {
// in this case the schema is not checked if it's valid
return 0;
} else {
ITuple tuple = key.datum();
String sourceName = tuple.getSchema().getName();
Integer schemaId = tup... | java |
public int partialHashCode(ITuple tuple, int[] fields) {
int result = 0;
for(int field : fields) {
Object o = tuple.get(field);
if(o == null) { // nulls don't account for hashcode
continue;
}
int hashCode;
if(o instanceof String) { // since String.hashCode() != Utf8.hashCode()
HELPER_UTF8.set... | java |
@Override
public void init(FilterConfig config)
throws ServletException {
if(config.getInitParameter("ignorePrefix") != null) {
ignorePath = config.getInitParameter("ignorePrefix");
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.